X86: Lower SMUL_LOHI of v4i32 to pmuldq when SSE4.1 is available.
[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,
1937                      MVT::Other, &RetOps[0], RetOps.size());
1938 }
1939
1940 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1941   if (N->getNumValues() != 1)
1942     return false;
1943   if (!N->hasNUsesOfValue(1, 0))
1944     return false;
1945
1946   SDValue TCChain = Chain;
1947   SDNode *Copy = *N->use_begin();
1948   if (Copy->getOpcode() == ISD::CopyToReg) {
1949     // If the copy has a glue operand, we conservatively assume it isn't safe to
1950     // perform a tail call.
1951     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1952       return false;
1953     TCChain = Copy->getOperand(0);
1954   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1955     return false;
1956
1957   bool HasRet = false;
1958   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1959        UI != UE; ++UI) {
1960     if (UI->getOpcode() != X86ISD::RET_FLAG)
1961       return false;
1962     HasRet = true;
1963   }
1964
1965   if (!HasRet)
1966     return false;
1967
1968   Chain = TCChain;
1969   return true;
1970 }
1971
1972 MVT
1973 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1974                                             ISD::NodeType ExtendKind) const {
1975   MVT ReturnMVT;
1976   // TODO: Is this also valid on 32-bit?
1977   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1978     ReturnMVT = MVT::i8;
1979   else
1980     ReturnMVT = MVT::i32;
1981
1982   MVT MinVT = getRegisterType(ReturnMVT);
1983   return VT.bitsLT(MinVT) ? MinVT : VT;
1984 }
1985
1986 /// LowerCallResult - Lower the result values of a call into the
1987 /// appropriate copies out of appropriate physical registers.
1988 ///
1989 SDValue
1990 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1991                                    CallingConv::ID CallConv, bool isVarArg,
1992                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1993                                    SDLoc dl, SelectionDAG &DAG,
1994                                    SmallVectorImpl<SDValue> &InVals) const {
1995
1996   // Assign locations to each value returned by this call.
1997   SmallVector<CCValAssign, 16> RVLocs;
1998   bool Is64Bit = Subtarget->is64Bit();
1999   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2000                  getTargetMachine(), RVLocs, *DAG.getContext());
2001   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2002
2003   // Copy all of the result registers out of their specified physreg.
2004   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2005     CCValAssign &VA = RVLocs[i];
2006     EVT CopyVT = VA.getValVT();
2007
2008     // If this is x86-64, and we disabled SSE, we can't return FP values
2009     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2010         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2011       report_fatal_error("SSE register return with SSE disabled");
2012     }
2013
2014     SDValue Val;
2015
2016     // If this is a call to a function that returns an fp value on the floating
2017     // point stack, we must guarantee the value is popped from the stack, so
2018     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2019     // if the return value is not used. We use the FpPOP_RETVAL instruction
2020     // instead.
2021     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2022       // If we prefer to use the value in xmm registers, copy it out as f80 and
2023       // use a truncate to move it from fp stack reg to xmm reg.
2024       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2025       SDValue Ops[] = { Chain, InFlag };
2026       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2027                                          MVT::Other, MVT::Glue, Ops), 1);
2028       Val = Chain.getValue(0);
2029
2030       // Round the f80 to the right size, which also moves it to the appropriate
2031       // xmm register.
2032       if (CopyVT != VA.getValVT())
2033         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2034                           // This truncation won't change the value.
2035                           DAG.getIntPtrConstant(1));
2036     } else {
2037       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2038                                  CopyVT, InFlag).getValue(1);
2039       Val = Chain.getValue(0);
2040     }
2041     InFlag = Chain.getValue(2);
2042     InVals.push_back(Val);
2043   }
2044
2045   return Chain;
2046 }
2047
2048 //===----------------------------------------------------------------------===//
2049 //                C & StdCall & Fast Calling Convention implementation
2050 //===----------------------------------------------------------------------===//
2051 //  StdCall calling convention seems to be standard for many Windows' API
2052 //  routines and around. It differs from C calling convention just a little:
2053 //  callee should clean up the stack, not caller. Symbols should be also
2054 //  decorated in some fancy way :) It doesn't support any vector arguments.
2055 //  For info on fast calling convention see Fast Calling Convention (tail call)
2056 //  implementation LowerX86_32FastCCCallTo.
2057
2058 /// CallIsStructReturn - Determines whether a call uses struct return
2059 /// semantics.
2060 enum StructReturnType {
2061   NotStructReturn,
2062   RegStructReturn,
2063   StackStructReturn
2064 };
2065 static StructReturnType
2066 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2067   if (Outs.empty())
2068     return NotStructReturn;
2069
2070   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2071   if (!Flags.isSRet())
2072     return NotStructReturn;
2073   if (Flags.isInReg())
2074     return RegStructReturn;
2075   return StackStructReturn;
2076 }
2077
2078 /// ArgsAreStructReturn - Determines whether a function uses struct
2079 /// return semantics.
2080 static StructReturnType
2081 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2082   if (Ins.empty())
2083     return NotStructReturn;
2084
2085   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2086   if (!Flags.isSRet())
2087     return NotStructReturn;
2088   if (Flags.isInReg())
2089     return RegStructReturn;
2090   return StackStructReturn;
2091 }
2092
2093 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2094 /// by "Src" to address "Dst" with size and alignment information specified by
2095 /// the specific parameter attribute. The copy will be passed as a byval
2096 /// function parameter.
2097 static SDValue
2098 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2099                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2100                           SDLoc dl) {
2101   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2102
2103   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2104                        /*isVolatile*/false, /*AlwaysInline=*/true,
2105                        MachinePointerInfo(), MachinePointerInfo());
2106 }
2107
2108 /// IsTailCallConvention - Return true if the calling convention is one that
2109 /// supports tail call optimization.
2110 static bool IsTailCallConvention(CallingConv::ID CC) {
2111   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2112           CC == CallingConv::HiPE);
2113 }
2114
2115 /// \brief Return true if the calling convention is a C calling convention.
2116 static bool IsCCallConvention(CallingConv::ID CC) {
2117   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2118           CC == CallingConv::X86_64_SysV);
2119 }
2120
2121 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2122   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123     return false;
2124
2125   CallSite CS(CI);
2126   CallingConv::ID CalleeCC = CS.getCallingConv();
2127   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2128     return false;
2129
2130   return true;
2131 }
2132
2133 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2134 /// a tailcall target by changing its ABI.
2135 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2136                                    bool GuaranteedTailCallOpt) {
2137   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 }
2139
2140 SDValue
2141 X86TargetLowering::LowerMemArgument(SDValue Chain,
2142                                     CallingConv::ID CallConv,
2143                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2144                                     SDLoc dl, SelectionDAG &DAG,
2145                                     const CCValAssign &VA,
2146                                     MachineFrameInfo *MFI,
2147                                     unsigned i) const {
2148   // Create the nodes corresponding to a load from this parameter slot.
2149   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2150   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2151                               getTargetMachine().Options.GuaranteedTailCallOpt);
2152   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2153   EVT ValVT;
2154
2155   // If value is passed by pointer we have address passed instead of the value
2156   // itself.
2157   if (VA.getLocInfo() == CCValAssign::Indirect)
2158     ValVT = VA.getLocVT();
2159   else
2160     ValVT = VA.getValVT();
2161
2162   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2163   // changed with more analysis.
2164   // In case of tail call optimization mark all arguments mutable. Since they
2165   // could be overwritten by lowering of arguments in case of a tail call.
2166   if (Flags.isByVal()) {
2167     unsigned Bytes = Flags.getByValSize();
2168     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2169     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2170     return DAG.getFrameIndex(FI, getPointerTy());
2171   } else {
2172     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2173                                     VA.getLocMemOffset(), isImmutable);
2174     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2175     return DAG.getLoad(ValVT, dl, Chain, FIN,
2176                        MachinePointerInfo::getFixedStack(FI),
2177                        false, false, false, 0);
2178   }
2179 }
2180
2181 SDValue
2182 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2183                                         CallingConv::ID CallConv,
2184                                         bool isVarArg,
2185                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2186                                         SDLoc dl,
2187                                         SelectionDAG &DAG,
2188                                         SmallVectorImpl<SDValue> &InVals)
2189                                           const {
2190   MachineFunction &MF = DAG.getMachineFunction();
2191   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2192
2193   const Function* Fn = MF.getFunction();
2194   if (Fn->hasExternalLinkage() &&
2195       Subtarget->isTargetCygMing() &&
2196       Fn->getName() == "main")
2197     FuncInfo->setForceFramePointer(true);
2198
2199   MachineFrameInfo *MFI = MF.getFrameInfo();
2200   bool Is64Bit = Subtarget->is64Bit();
2201   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2202
2203   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204          "Var args not supported with calling convention fastcc, ghc or hipe");
2205
2206   // Assign locations to all of the incoming arguments.
2207   SmallVector<CCValAssign, 16> ArgLocs;
2208   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209                  ArgLocs, *DAG.getContext());
2210
2211   // Allocate shadow area for Win64
2212   if (IsWin64)
2213     CCInfo.AllocateStack(32, 8);
2214
2215   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2216
2217   unsigned LastVal = ~0U;
2218   SDValue ArgValue;
2219   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2220     CCValAssign &VA = ArgLocs[i];
2221     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2222     // places.
2223     assert(VA.getValNo() != LastVal &&
2224            "Don't support value assigned to multiple locs yet");
2225     (void)LastVal;
2226     LastVal = VA.getValNo();
2227
2228     if (VA.isRegLoc()) {
2229       EVT RegVT = VA.getLocVT();
2230       const TargetRegisterClass *RC;
2231       if (RegVT == MVT::i32)
2232         RC = &X86::GR32RegClass;
2233       else if (Is64Bit && RegVT == MVT::i64)
2234         RC = &X86::GR64RegClass;
2235       else if (RegVT == MVT::f32)
2236         RC = &X86::FR32RegClass;
2237       else if (RegVT == MVT::f64)
2238         RC = &X86::FR64RegClass;
2239       else if (RegVT.is512BitVector())
2240         RC = &X86::VR512RegClass;
2241       else if (RegVT.is256BitVector())
2242         RC = &X86::VR256RegClass;
2243       else if (RegVT.is128BitVector())
2244         RC = &X86::VR128RegClass;
2245       else if (RegVT == MVT::x86mmx)
2246         RC = &X86::VR64RegClass;
2247       else if (RegVT == MVT::i1)
2248         RC = &X86::VK1RegClass;
2249       else if (RegVT == MVT::v8i1)
2250         RC = &X86::VK8RegClass;
2251       else if (RegVT == MVT::v16i1)
2252         RC = &X86::VK16RegClass;
2253       else
2254         llvm_unreachable("Unknown argument type!");
2255
2256       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2257       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2258
2259       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2260       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2261       // right size.
2262       if (VA.getLocInfo() == CCValAssign::SExt)
2263         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2264                                DAG.getValueType(VA.getValVT()));
2265       else if (VA.getLocInfo() == CCValAssign::ZExt)
2266         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2267                                DAG.getValueType(VA.getValVT()));
2268       else if (VA.getLocInfo() == CCValAssign::BCvt)
2269         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2270
2271       if (VA.isExtInLoc()) {
2272         // Handle MMX values passed in XMM regs.
2273         if (RegVT.isVector())
2274           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2275         else
2276           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2277       }
2278     } else {
2279       assert(VA.isMemLoc());
2280       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2281     }
2282
2283     // If value is passed via pointer - do a load.
2284     if (VA.getLocInfo() == CCValAssign::Indirect)
2285       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2286                              MachinePointerInfo(), false, false, false, 0);
2287
2288     InVals.push_back(ArgValue);
2289   }
2290
2291   // The x86-64 ABIs require that for returning structs by value we copy
2292   // the sret argument into %rax/%eax (depending on ABI) for the return.
2293   // Win32 requires us to put the sret argument to %eax as well.
2294   // Save the argument into a virtual register so that we can access it
2295   // from the return points.
2296   if (MF.getFunction()->hasStructRetAttr() &&
2297       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2298     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2299     unsigned Reg = FuncInfo->getSRetReturnReg();
2300     if (!Reg) {
2301       MVT PtrTy = getPointerTy();
2302       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2303       FuncInfo->setSRetReturnReg(Reg);
2304     }
2305     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2306     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2307   }
2308
2309   unsigned StackSize = CCInfo.getNextStackOffset();
2310   // Align stack specially for tail calls.
2311   if (FuncIsMadeTailCallSafe(CallConv,
2312                              MF.getTarget().Options.GuaranteedTailCallOpt))
2313     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2314
2315   // If the function takes variable number of arguments, make a frame index for
2316   // the start of the first vararg value... for expansion of llvm.va_start.
2317   if (isVarArg) {
2318     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2319                     CallConv != CallingConv::X86_ThisCall)) {
2320       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2321     }
2322     if (Is64Bit) {
2323       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2324
2325       // FIXME: We should really autogenerate these arrays
2326       static const MCPhysReg GPR64ArgRegsWin64[] = {
2327         X86::RCX, X86::RDX, X86::R8,  X86::R9
2328       };
2329       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2330         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2331       };
2332       static const MCPhysReg XMMArgRegs64Bit[] = {
2333         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2335       };
2336       const MCPhysReg *GPR64ArgRegs;
2337       unsigned NumXMMRegs = 0;
2338
2339       if (IsWin64) {
2340         // The XMM registers which might contain var arg parameters are shadowed
2341         // in their paired GPR.  So we only need to save the GPR to their home
2342         // slots.
2343         TotalNumIntRegs = 4;
2344         GPR64ArgRegs = GPR64ArgRegsWin64;
2345       } else {
2346         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2347         GPR64ArgRegs = GPR64ArgRegs64Bit;
2348
2349         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2350                                                 TotalNumXMMRegs);
2351       }
2352       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2353                                                        TotalNumIntRegs);
2354
2355       bool NoImplicitFloatOps = Fn->getAttributes().
2356         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2357       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2358              "SSE register cannot be used when SSE is disabled!");
2359       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2360                NoImplicitFloatOps) &&
2361              "SSE register cannot be used when SSE is disabled!");
2362       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2363           !Subtarget->hasSSE1())
2364         // Kernel mode asks for SSE to be disabled, so don't push them
2365         // on the stack.
2366         TotalNumXMMRegs = 0;
2367
2368       if (IsWin64) {
2369         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2370         // Get to the caller-allocated home save location.  Add 8 to account
2371         // for the return address.
2372         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2373         FuncInfo->setRegSaveFrameIndex(
2374           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2375         // Fixup to set vararg frame on shadow area (4 x i64).
2376         if (NumIntRegs < 4)
2377           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2378       } else {
2379         // For X86-64, if there are vararg parameters that are passed via
2380         // registers, then we must store them to their spots on the stack so
2381         // they may be loaded by deferencing the result of va_next.
2382         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2383         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2384         FuncInfo->setRegSaveFrameIndex(
2385           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386                                false));
2387       }
2388
2389       // Store the integer parameter registers.
2390       SmallVector<SDValue, 8> MemOps;
2391       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2392                                         getPointerTy());
2393       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2394       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2395         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2396                                   DAG.getIntPtrConstant(Offset));
2397         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2398                                      &X86::GR64RegClass);
2399         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2400         SDValue Store =
2401           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2402                        MachinePointerInfo::getFixedStack(
2403                          FuncInfo->getRegSaveFrameIndex(), Offset),
2404                        false, false, 0);
2405         MemOps.push_back(Store);
2406         Offset += 8;
2407       }
2408
2409       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2410         // Now store the XMM (fp + vector) parameter registers.
2411         SmallVector<SDValue, 11> SaveXMMOps;
2412         SaveXMMOps.push_back(Chain);
2413
2414         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2415         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2416         SaveXMMOps.push_back(ALVal);
2417
2418         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2419                                FuncInfo->getRegSaveFrameIndex()));
2420         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421                                FuncInfo->getVarArgsFPOffset()));
2422
2423         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2424           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2425                                        &X86::VR128RegClass);
2426           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2427           SaveXMMOps.push_back(Val);
2428         }
2429         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2430                                      MVT::Other,
2431                                      &SaveXMMOps[0], SaveXMMOps.size()));
2432       }
2433
2434       if (!MemOps.empty())
2435         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2436                             &MemOps[0], MemOps.size());
2437     }
2438   }
2439
2440   // Some CCs need callee pop.
2441   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2442                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2443     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2444   } else {
2445     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2446     // If this is an sret function, the return should pop the hidden pointer.
2447     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2448         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2449         argsAreStructReturn(Ins) == StackStructReturn)
2450       FuncInfo->setBytesToPopOnReturn(4);
2451   }
2452
2453   if (!Is64Bit) {
2454     // RegSaveFrameIndex is X86-64 only.
2455     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2456     if (CallConv == CallingConv::X86_FastCall ||
2457         CallConv == CallingConv::X86_ThisCall)
2458       // fastcc functions can't have varargs.
2459       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2460   }
2461
2462   FuncInfo->setArgumentStackSize(StackSize);
2463
2464   return Chain;
2465 }
2466
2467 SDValue
2468 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2469                                     SDValue StackPtr, SDValue Arg,
2470                                     SDLoc dl, SelectionDAG &DAG,
2471                                     const CCValAssign &VA,
2472                                     ISD::ArgFlagsTy Flags) const {
2473   unsigned LocMemOffset = VA.getLocMemOffset();
2474   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2475   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2476   if (Flags.isByVal())
2477     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2478
2479   return DAG.getStore(Chain, dl, Arg, PtrOff,
2480                       MachinePointerInfo::getStack(LocMemOffset),
2481                       false, false, 0);
2482 }
2483
2484 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2485 /// optimization is performed and it is required.
2486 SDValue
2487 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2488                                            SDValue &OutRetAddr, SDValue Chain,
2489                                            bool IsTailCall, bool Is64Bit,
2490                                            int FPDiff, SDLoc dl) const {
2491   // Adjust the Return address stack slot.
2492   EVT VT = getPointerTy();
2493   OutRetAddr = getReturnAddressFrameIndex(DAG);
2494
2495   // Load the "old" Return address.
2496   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2497                            false, false, false, 0);
2498   return SDValue(OutRetAddr.getNode(), 1);
2499 }
2500
2501 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2502 /// optimization is performed and it is required (FPDiff!=0).
2503 static SDValue
2504 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2505                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2506                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2507   // Store the return address to the appropriate stack slot.
2508   if (!FPDiff) return Chain;
2509   // Calculate the new stack slot for the return address.
2510   int NewReturnAddrFI =
2511     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2512                                          false);
2513   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2514   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2515                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2516                        false, false, 0);
2517   return Chain;
2518 }
2519
2520 SDValue
2521 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2522                              SmallVectorImpl<SDValue> &InVals) const {
2523   SelectionDAG &DAG                     = CLI.DAG;
2524   SDLoc &dl                             = CLI.DL;
2525   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2526   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2527   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2528   SDValue Chain                         = CLI.Chain;
2529   SDValue Callee                        = CLI.Callee;
2530   CallingConv::ID CallConv              = CLI.CallConv;
2531   bool &isTailCall                      = CLI.IsTailCall;
2532   bool isVarArg                         = CLI.IsVarArg;
2533
2534   MachineFunction &MF = DAG.getMachineFunction();
2535   bool Is64Bit        = Subtarget->is64Bit();
2536   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2537   StructReturnType SR = callIsStructReturn(Outs);
2538   bool IsSibcall      = false;
2539
2540   if (MF.getTarget().Options.DisableTailCalls)
2541     isTailCall = false;
2542
2543   if (isTailCall) {
2544     // Check if it's really possible to do a tail call.
2545     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2546                     isVarArg, SR != NotStructReturn,
2547                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2548                     Outs, OutVals, Ins, DAG);
2549
2550     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2551       report_fatal_error("failed to perform tail call elimination on a call "
2552                          "site marked musttail");
2553
2554     // Sibcalls are automatically detected tailcalls which do not require
2555     // ABI changes.
2556     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2557       IsSibcall = true;
2558
2559     if (isTailCall)
2560       ++NumTailCalls;
2561   }
2562
2563   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2564          "Var args not supported with calling convention fastcc, ghc or hipe");
2565
2566   // Analyze operands of the call, assigning locations to each operand.
2567   SmallVector<CCValAssign, 16> ArgLocs;
2568   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2569                  ArgLocs, *DAG.getContext());
2570
2571   // Allocate shadow area for Win64
2572   if (IsWin64)
2573     CCInfo.AllocateStack(32, 8);
2574
2575   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2576
2577   // Get a count of how many bytes are to be pushed on the stack.
2578   unsigned NumBytes = CCInfo.getNextStackOffset();
2579   if (IsSibcall)
2580     // This is a sibcall. The memory operands are available in caller's
2581     // own caller's stack.
2582     NumBytes = 0;
2583   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2584            IsTailCallConvention(CallConv))
2585     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2586
2587   int FPDiff = 0;
2588   if (isTailCall && !IsSibcall) {
2589     // Lower arguments at fp - stackoffset + fpdiff.
2590     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2591     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2592
2593     FPDiff = NumBytesCallerPushed - NumBytes;
2594
2595     // Set the delta of movement of the returnaddr stackslot.
2596     // But only set if delta is greater than previous delta.
2597     if (FPDiff < X86Info->getTCReturnAddrDelta())
2598       X86Info->setTCReturnAddrDelta(FPDiff);
2599   }
2600
2601   unsigned NumBytesToPush = NumBytes;
2602   unsigned NumBytesToPop = NumBytes;
2603
2604   // If we have an inalloca argument, all stack space has already been allocated
2605   // for us and be right at the top of the stack.  We don't support multiple
2606   // arguments passed in memory when using inalloca.
2607   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2608     NumBytesToPush = 0;
2609     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2610            "an inalloca argument must be the only memory argument");
2611   }
2612
2613   if (!IsSibcall)
2614     Chain = DAG.getCALLSEQ_START(
2615         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2616
2617   SDValue RetAddrFrIdx;
2618   // Load return address for tail calls.
2619   if (isTailCall && FPDiff)
2620     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2621                                     Is64Bit, FPDiff, dl);
2622
2623   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2624   SmallVector<SDValue, 8> MemOpChains;
2625   SDValue StackPtr;
2626
2627   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2628   // of tail call optimization arguments are handle later.
2629   const X86RegisterInfo *RegInfo =
2630     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2631   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2632     // Skip inalloca arguments, they have already been written.
2633     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2634     if (Flags.isInAlloca())
2635       continue;
2636
2637     CCValAssign &VA = ArgLocs[i];
2638     EVT RegVT = VA.getLocVT();
2639     SDValue Arg = OutVals[i];
2640     bool isByVal = Flags.isByVal();
2641
2642     // Promote the value if needed.
2643     switch (VA.getLocInfo()) {
2644     default: llvm_unreachable("Unknown loc info!");
2645     case CCValAssign::Full: break;
2646     case CCValAssign::SExt:
2647       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2648       break;
2649     case CCValAssign::ZExt:
2650       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2651       break;
2652     case CCValAssign::AExt:
2653       if (RegVT.is128BitVector()) {
2654         // Special case: passing MMX values in XMM registers.
2655         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2656         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2657         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2658       } else
2659         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2660       break;
2661     case CCValAssign::BCvt:
2662       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2663       break;
2664     case CCValAssign::Indirect: {
2665       // Store the argument.
2666       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2667       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2668       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2669                            MachinePointerInfo::getFixedStack(FI),
2670                            false, false, 0);
2671       Arg = SpillSlot;
2672       break;
2673     }
2674     }
2675
2676     if (VA.isRegLoc()) {
2677       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2678       if (isVarArg && IsWin64) {
2679         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2680         // shadow reg if callee is a varargs function.
2681         unsigned ShadowReg = 0;
2682         switch (VA.getLocReg()) {
2683         case X86::XMM0: ShadowReg = X86::RCX; break;
2684         case X86::XMM1: ShadowReg = X86::RDX; break;
2685         case X86::XMM2: ShadowReg = X86::R8; break;
2686         case X86::XMM3: ShadowReg = X86::R9; break;
2687         }
2688         if (ShadowReg)
2689           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2690       }
2691     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2692       assert(VA.isMemLoc());
2693       if (!StackPtr.getNode())
2694         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2695                                       getPointerTy());
2696       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2697                                              dl, DAG, VA, Flags));
2698     }
2699   }
2700
2701   if (!MemOpChains.empty())
2702     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2703                         &MemOpChains[0], MemOpChains.size());
2704
2705   if (Subtarget->isPICStyleGOT()) {
2706     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2707     // GOT pointer.
2708     if (!isTailCall) {
2709       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2710                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2711     } else {
2712       // If we are tail calling and generating PIC/GOT style code load the
2713       // address of the callee into ECX. The value in ecx is used as target of
2714       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2715       // for tail calls on PIC/GOT architectures. Normally we would just put the
2716       // address of GOT into ebx and then call target@PLT. But for tail calls
2717       // ebx would be restored (since ebx is callee saved) before jumping to the
2718       // target@PLT.
2719
2720       // Note: The actual moving to ECX is done further down.
2721       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2722       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2723           !G->getGlobal()->hasProtectedVisibility())
2724         Callee = LowerGlobalAddress(Callee, DAG);
2725       else if (isa<ExternalSymbolSDNode>(Callee))
2726         Callee = LowerExternalSymbol(Callee, DAG);
2727     }
2728   }
2729
2730   if (Is64Bit && isVarArg && !IsWin64) {
2731     // From AMD64 ABI document:
2732     // For calls that may call functions that use varargs or stdargs
2733     // (prototype-less calls or calls to functions containing ellipsis (...) in
2734     // the declaration) %al is used as hidden argument to specify the number
2735     // of SSE registers used. The contents of %al do not need to match exactly
2736     // the number of registers, but must be an ubound on the number of SSE
2737     // registers used and is in the range 0 - 8 inclusive.
2738
2739     // Count the number of XMM registers allocated.
2740     static const MCPhysReg XMMArgRegs[] = {
2741       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2742       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2743     };
2744     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2745     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2746            && "SSE registers cannot be used when SSE is disabled");
2747
2748     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2749                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2750   }
2751
2752   // For tail calls lower the arguments to the 'real' stack slot.
2753   if (isTailCall) {
2754     // Force all the incoming stack arguments to be loaded from the stack
2755     // before any new outgoing arguments are stored to the stack, because the
2756     // outgoing stack slots may alias the incoming argument stack slots, and
2757     // the alias isn't otherwise explicit. This is slightly more conservative
2758     // than necessary, because it means that each store effectively depends
2759     // on every argument instead of just those arguments it would clobber.
2760     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2761
2762     SmallVector<SDValue, 8> MemOpChains2;
2763     SDValue FIN;
2764     int FI = 0;
2765     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2766       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2767         CCValAssign &VA = ArgLocs[i];
2768         if (VA.isRegLoc())
2769           continue;
2770         assert(VA.isMemLoc());
2771         SDValue Arg = OutVals[i];
2772         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2773         // Create frame index.
2774         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2775         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2776         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2777         FIN = DAG.getFrameIndex(FI, getPointerTy());
2778
2779         if (Flags.isByVal()) {
2780           // Copy relative to framepointer.
2781           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2782           if (!StackPtr.getNode())
2783             StackPtr = DAG.getCopyFromReg(Chain, dl,
2784                                           RegInfo->getStackRegister(),
2785                                           getPointerTy());
2786           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2787
2788           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2789                                                            ArgChain,
2790                                                            Flags, DAG, dl));
2791         } else {
2792           // Store relative to framepointer.
2793           MemOpChains2.push_back(
2794             DAG.getStore(ArgChain, dl, Arg, FIN,
2795                          MachinePointerInfo::getFixedStack(FI),
2796                          false, false, 0));
2797         }
2798       }
2799     }
2800
2801     if (!MemOpChains2.empty())
2802       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2803                           &MemOpChains2[0], MemOpChains2.size());
2804
2805     // Store the return address to the appropriate stack slot.
2806     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2807                                      getPointerTy(), RegInfo->getSlotSize(),
2808                                      FPDiff, dl);
2809   }
2810
2811   // Build a sequence of copy-to-reg nodes chained together with token chain
2812   // and flag operands which copy the outgoing args into registers.
2813   SDValue InFlag;
2814   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2815     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2816                              RegsToPass[i].second, InFlag);
2817     InFlag = Chain.getValue(1);
2818   }
2819
2820   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2821     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2822     // In the 64-bit large code model, we have to make all calls
2823     // through a register, since the call instruction's 32-bit
2824     // pc-relative offset may not be large enough to hold the whole
2825     // address.
2826   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2827     // If the callee is a GlobalAddress node (quite common, every direct call
2828     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2829     // it.
2830
2831     // We should use extra load for direct calls to dllimported functions in
2832     // non-JIT mode.
2833     const GlobalValue *GV = G->getGlobal();
2834     if (!GV->hasDLLImportStorageClass()) {
2835       unsigned char OpFlags = 0;
2836       bool ExtraLoad = false;
2837       unsigned WrapperKind = ISD::DELETED_NODE;
2838
2839       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2840       // external symbols most go through the PLT in PIC mode.  If the symbol
2841       // has hidden or protected visibility, or if it is static or local, then
2842       // we don't need to use the PLT - we can directly call it.
2843       if (Subtarget->isTargetELF() &&
2844           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2845           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2846         OpFlags = X86II::MO_PLT;
2847       } else if (Subtarget->isPICStyleStubAny() &&
2848                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2849                  (!Subtarget->getTargetTriple().isMacOSX() ||
2850                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2851         // PC-relative references to external symbols should go through $stub,
2852         // unless we're building with the leopard linker or later, which
2853         // automatically synthesizes these stubs.
2854         OpFlags = X86II::MO_DARWIN_STUB;
2855       } else if (Subtarget->isPICStyleRIPRel() &&
2856                  isa<Function>(GV) &&
2857                  cast<Function>(GV)->getAttributes().
2858                    hasAttribute(AttributeSet::FunctionIndex,
2859                                 Attribute::NonLazyBind)) {
2860         // If the function is marked as non-lazy, generate an indirect call
2861         // which loads from the GOT directly. This avoids runtime overhead
2862         // at the cost of eager binding (and one extra byte of encoding).
2863         OpFlags = X86II::MO_GOTPCREL;
2864         WrapperKind = X86ISD::WrapperRIP;
2865         ExtraLoad = true;
2866       }
2867
2868       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2869                                           G->getOffset(), OpFlags);
2870
2871       // Add a wrapper if needed.
2872       if (WrapperKind != ISD::DELETED_NODE)
2873         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2874       // Add extra indirection if needed.
2875       if (ExtraLoad)
2876         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2877                              MachinePointerInfo::getGOT(),
2878                              false, false, false, 0);
2879     }
2880   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2881     unsigned char OpFlags = 0;
2882
2883     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2884     // external symbols should go through the PLT.
2885     if (Subtarget->isTargetELF() &&
2886         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2887       OpFlags = X86II::MO_PLT;
2888     } else if (Subtarget->isPICStyleStubAny() &&
2889                (!Subtarget->getTargetTriple().isMacOSX() ||
2890                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2891       // PC-relative references to external symbols should go through $stub,
2892       // unless we're building with the leopard linker or later, which
2893       // automatically synthesizes these stubs.
2894       OpFlags = X86II::MO_DARWIN_STUB;
2895     }
2896
2897     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2898                                          OpFlags);
2899   }
2900
2901   // Returns a chain & a flag for retval copy to use.
2902   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2903   SmallVector<SDValue, 8> Ops;
2904
2905   if (!IsSibcall && isTailCall) {
2906     Chain = DAG.getCALLSEQ_END(Chain,
2907                                DAG.getIntPtrConstant(NumBytesToPop, true),
2908                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2909     InFlag = Chain.getValue(1);
2910   }
2911
2912   Ops.push_back(Chain);
2913   Ops.push_back(Callee);
2914
2915   if (isTailCall)
2916     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2917
2918   // Add argument registers to the end of the list so that they are known live
2919   // into the call.
2920   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2921     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2922                                   RegsToPass[i].second.getValueType()));
2923
2924   // Add a register mask operand representing the call-preserved registers.
2925   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2926   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2927   assert(Mask && "Missing call preserved mask for calling convention");
2928   Ops.push_back(DAG.getRegisterMask(Mask));
2929
2930   if (InFlag.getNode())
2931     Ops.push_back(InFlag);
2932
2933   if (isTailCall) {
2934     // We used to do:
2935     //// If this is the first return lowered for this function, add the regs
2936     //// to the liveout set for the function.
2937     // This isn't right, although it's probably harmless on x86; liveouts
2938     // should be computed from returns not tail calls.  Consider a void
2939     // function making a tail call to a function returning int.
2940     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2941   }
2942
2943   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2944   InFlag = Chain.getValue(1);
2945
2946   // Create the CALLSEQ_END node.
2947   unsigned NumBytesForCalleeToPop;
2948   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2949                        getTargetMachine().Options.GuaranteedTailCallOpt))
2950     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2951   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2952            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2953            SR == StackStructReturn)
2954     // If this is a call to a struct-return function, the callee
2955     // pops the hidden struct pointer, so we have to push it back.
2956     // This is common for Darwin/X86, Linux & Mingw32 targets.
2957     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2958     NumBytesForCalleeToPop = 4;
2959   else
2960     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2961
2962   // Returns a flag for retval copy to use.
2963   if (!IsSibcall) {
2964     Chain = DAG.getCALLSEQ_END(Chain,
2965                                DAG.getIntPtrConstant(NumBytesToPop, true),
2966                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2967                                                      true),
2968                                InFlag, dl);
2969     InFlag = Chain.getValue(1);
2970   }
2971
2972   // Handle result values, copying them out of physregs into vregs that we
2973   // return.
2974   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2975                          Ins, dl, DAG, InVals);
2976 }
2977
2978 //===----------------------------------------------------------------------===//
2979 //                Fast Calling Convention (tail call) implementation
2980 //===----------------------------------------------------------------------===//
2981
2982 //  Like std call, callee cleans arguments, convention except that ECX is
2983 //  reserved for storing the tail called function address. Only 2 registers are
2984 //  free for argument passing (inreg). Tail call optimization is performed
2985 //  provided:
2986 //                * tailcallopt is enabled
2987 //                * caller/callee are fastcc
2988 //  On X86_64 architecture with GOT-style position independent code only local
2989 //  (within module) calls are supported at the moment.
2990 //  To keep the stack aligned according to platform abi the function
2991 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2992 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2993 //  If a tail called function callee has more arguments than the caller the
2994 //  caller needs to make sure that there is room to move the RETADDR to. This is
2995 //  achieved by reserving an area the size of the argument delta right after the
2996 //  original REtADDR, but before the saved framepointer or the spilled registers
2997 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2998 //  stack layout:
2999 //    arg1
3000 //    arg2
3001 //    RETADDR
3002 //    [ new RETADDR
3003 //      move area ]
3004 //    (possible EBP)
3005 //    ESI
3006 //    EDI
3007 //    local1 ..
3008
3009 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3010 /// for a 16 byte align requirement.
3011 unsigned
3012 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3013                                                SelectionDAG& DAG) const {
3014   MachineFunction &MF = DAG.getMachineFunction();
3015   const TargetMachine &TM = MF.getTarget();
3016   const X86RegisterInfo *RegInfo =
3017     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3018   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3019   unsigned StackAlignment = TFI.getStackAlignment();
3020   uint64_t AlignMask = StackAlignment - 1;
3021   int64_t Offset = StackSize;
3022   unsigned SlotSize = RegInfo->getSlotSize();
3023   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3024     // Number smaller than 12 so just add the difference.
3025     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3026   } else {
3027     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3028     Offset = ((~AlignMask) & Offset) + StackAlignment +
3029       (StackAlignment-SlotSize);
3030   }
3031   return Offset;
3032 }
3033
3034 /// MatchingStackOffset - Return true if the given stack call argument is
3035 /// already available in the same position (relatively) of the caller's
3036 /// incoming argument stack.
3037 static
3038 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3039                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3040                          const X86InstrInfo *TII) {
3041   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3042   int FI = INT_MAX;
3043   if (Arg.getOpcode() == ISD::CopyFromReg) {
3044     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3045     if (!TargetRegisterInfo::isVirtualRegister(VR))
3046       return false;
3047     MachineInstr *Def = MRI->getVRegDef(VR);
3048     if (!Def)
3049       return false;
3050     if (!Flags.isByVal()) {
3051       if (!TII->isLoadFromStackSlot(Def, FI))
3052         return false;
3053     } else {
3054       unsigned Opcode = Def->getOpcode();
3055       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3056           Def->getOperand(1).isFI()) {
3057         FI = Def->getOperand(1).getIndex();
3058         Bytes = Flags.getByValSize();
3059       } else
3060         return false;
3061     }
3062   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3063     if (Flags.isByVal())
3064       // ByVal argument is passed in as a pointer but it's now being
3065       // dereferenced. e.g.
3066       // define @foo(%struct.X* %A) {
3067       //   tail call @bar(%struct.X* byval %A)
3068       // }
3069       return false;
3070     SDValue Ptr = Ld->getBasePtr();
3071     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3072     if (!FINode)
3073       return false;
3074     FI = FINode->getIndex();
3075   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3076     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3077     FI = FINode->getIndex();
3078     Bytes = Flags.getByValSize();
3079   } else
3080     return false;
3081
3082   assert(FI != INT_MAX);
3083   if (!MFI->isFixedObjectIndex(FI))
3084     return false;
3085   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3086 }
3087
3088 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3089 /// for tail call optimization. Targets which want to do tail call
3090 /// optimization should implement this function.
3091 bool
3092 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3093                                                      CallingConv::ID CalleeCC,
3094                                                      bool isVarArg,
3095                                                      bool isCalleeStructRet,
3096                                                      bool isCallerStructRet,
3097                                                      Type *RetTy,
3098                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3099                                     const SmallVectorImpl<SDValue> &OutVals,
3100                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3101                                                      SelectionDAG &DAG) const {
3102   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3103     return false;
3104
3105   // If -tailcallopt is specified, make fastcc functions tail-callable.
3106   const MachineFunction &MF = DAG.getMachineFunction();
3107   const Function *CallerF = MF.getFunction();
3108
3109   // If the function return type is x86_fp80 and the callee return type is not,
3110   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3111   // perform a tailcall optimization here.
3112   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3113     return false;
3114
3115   CallingConv::ID CallerCC = CallerF->getCallingConv();
3116   bool CCMatch = CallerCC == CalleeCC;
3117   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3118   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3119
3120   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3121     if (IsTailCallConvention(CalleeCC) && CCMatch)
3122       return true;
3123     return false;
3124   }
3125
3126   // Look for obvious safe cases to perform tail call optimization that do not
3127   // require ABI changes. This is what gcc calls sibcall.
3128
3129   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3130   // emit a special epilogue.
3131   const X86RegisterInfo *RegInfo =
3132     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3133   if (RegInfo->needsStackRealignment(MF))
3134     return false;
3135
3136   // Also avoid sibcall optimization if either caller or callee uses struct
3137   // return semantics.
3138   if (isCalleeStructRet || isCallerStructRet)
3139     return false;
3140
3141   // An stdcall/thiscall caller is expected to clean up its arguments; the
3142   // callee isn't going to do that.
3143   // FIXME: this is more restrictive than needed. We could produce a tailcall
3144   // when the stack adjustment matches. For example, with a thiscall that takes
3145   // only one argument.
3146   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3147                    CallerCC == CallingConv::X86_ThisCall))
3148     return false;
3149
3150   // Do not sibcall optimize vararg calls unless all arguments are passed via
3151   // registers.
3152   if (isVarArg && !Outs.empty()) {
3153
3154     // Optimizing for varargs on Win64 is unlikely to be safe without
3155     // additional testing.
3156     if (IsCalleeWin64 || IsCallerWin64)
3157       return false;
3158
3159     SmallVector<CCValAssign, 16> ArgLocs;
3160     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3161                    getTargetMachine(), ArgLocs, *DAG.getContext());
3162
3163     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3164     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3165       if (!ArgLocs[i].isRegLoc())
3166         return false;
3167   }
3168
3169   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3170   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3171   // this into a sibcall.
3172   bool Unused = false;
3173   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3174     if (!Ins[i].Used) {
3175       Unused = true;
3176       break;
3177     }
3178   }
3179   if (Unused) {
3180     SmallVector<CCValAssign, 16> RVLocs;
3181     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3182                    getTargetMachine(), RVLocs, *DAG.getContext());
3183     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3184     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3185       CCValAssign &VA = RVLocs[i];
3186       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3187         return false;
3188     }
3189   }
3190
3191   // If the calling conventions do not match, then we'd better make sure the
3192   // results are returned in the same way as what the caller expects.
3193   if (!CCMatch) {
3194     SmallVector<CCValAssign, 16> RVLocs1;
3195     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3196                     getTargetMachine(), RVLocs1, *DAG.getContext());
3197     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3198
3199     SmallVector<CCValAssign, 16> RVLocs2;
3200     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3201                     getTargetMachine(), RVLocs2, *DAG.getContext());
3202     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3203
3204     if (RVLocs1.size() != RVLocs2.size())
3205       return false;
3206     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3207       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3208         return false;
3209       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3210         return false;
3211       if (RVLocs1[i].isRegLoc()) {
3212         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3213           return false;
3214       } else {
3215         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3216           return false;
3217       }
3218     }
3219   }
3220
3221   // If the callee takes no arguments then go on to check the results of the
3222   // call.
3223   if (!Outs.empty()) {
3224     // Check if stack adjustment is needed. For now, do not do this if any
3225     // argument is passed on the stack.
3226     SmallVector<CCValAssign, 16> ArgLocs;
3227     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3228                    getTargetMachine(), ArgLocs, *DAG.getContext());
3229
3230     // Allocate shadow area for Win64
3231     if (IsCalleeWin64)
3232       CCInfo.AllocateStack(32, 8);
3233
3234     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3235     if (CCInfo.getNextStackOffset()) {
3236       MachineFunction &MF = DAG.getMachineFunction();
3237       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3238         return false;
3239
3240       // Check if the arguments are already laid out in the right way as
3241       // the caller's fixed stack objects.
3242       MachineFrameInfo *MFI = MF.getFrameInfo();
3243       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3244       const X86InstrInfo *TII =
3245         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3246       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3247         CCValAssign &VA = ArgLocs[i];
3248         SDValue Arg = OutVals[i];
3249         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3250         if (VA.getLocInfo() == CCValAssign::Indirect)
3251           return false;
3252         if (!VA.isRegLoc()) {
3253           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3254                                    MFI, MRI, TII))
3255             return false;
3256         }
3257       }
3258     }
3259
3260     // If the tailcall address may be in a register, then make sure it's
3261     // possible to register allocate for it. In 32-bit, the call address can
3262     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3263     // callee-saved registers are restored. These happen to be the same
3264     // registers used to pass 'inreg' arguments so watch out for those.
3265     if (!Subtarget->is64Bit() &&
3266         ((!isa<GlobalAddressSDNode>(Callee) &&
3267           !isa<ExternalSymbolSDNode>(Callee)) ||
3268          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3269       unsigned NumInRegs = 0;
3270       // In PIC we need an extra register to formulate the address computation
3271       // for the callee.
3272       unsigned MaxInRegs =
3273           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3274
3275       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3276         CCValAssign &VA = ArgLocs[i];
3277         if (!VA.isRegLoc())
3278           continue;
3279         unsigned Reg = VA.getLocReg();
3280         switch (Reg) {
3281         default: break;
3282         case X86::EAX: case X86::EDX: case X86::ECX:
3283           if (++NumInRegs == MaxInRegs)
3284             return false;
3285           break;
3286         }
3287       }
3288     }
3289   }
3290
3291   return true;
3292 }
3293
3294 FastISel *
3295 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3296                                   const TargetLibraryInfo *libInfo) const {
3297   return X86::createFastISel(funcInfo, libInfo);
3298 }
3299
3300 //===----------------------------------------------------------------------===//
3301 //                           Other Lowering Hooks
3302 //===----------------------------------------------------------------------===//
3303
3304 static bool MayFoldLoad(SDValue Op) {
3305   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3306 }
3307
3308 static bool MayFoldIntoStore(SDValue Op) {
3309   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3310 }
3311
3312 static bool isTargetShuffle(unsigned Opcode) {
3313   switch(Opcode) {
3314   default: return false;
3315   case X86ISD::PSHUFD:
3316   case X86ISD::PSHUFHW:
3317   case X86ISD::PSHUFLW:
3318   case X86ISD::SHUFP:
3319   case X86ISD::PALIGNR:
3320   case X86ISD::MOVLHPS:
3321   case X86ISD::MOVLHPD:
3322   case X86ISD::MOVHLPS:
3323   case X86ISD::MOVLPS:
3324   case X86ISD::MOVLPD:
3325   case X86ISD::MOVSHDUP:
3326   case X86ISD::MOVSLDUP:
3327   case X86ISD::MOVDDUP:
3328   case X86ISD::MOVSS:
3329   case X86ISD::MOVSD:
3330   case X86ISD::UNPCKL:
3331   case X86ISD::UNPCKH:
3332   case X86ISD::VPERMILP:
3333   case X86ISD::VPERM2X128:
3334   case X86ISD::VPERMI:
3335     return true;
3336   }
3337 }
3338
3339 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3340                                     SDValue V1, SelectionDAG &DAG) {
3341   switch(Opc) {
3342   default: llvm_unreachable("Unknown x86 shuffle node");
3343   case X86ISD::MOVSHDUP:
3344   case X86ISD::MOVSLDUP:
3345   case X86ISD::MOVDDUP:
3346     return DAG.getNode(Opc, dl, VT, V1);
3347   }
3348 }
3349
3350 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3351                                     SDValue V1, unsigned TargetMask,
3352                                     SelectionDAG &DAG) {
3353   switch(Opc) {
3354   default: llvm_unreachable("Unknown x86 shuffle node");
3355   case X86ISD::PSHUFD:
3356   case X86ISD::PSHUFHW:
3357   case X86ISD::PSHUFLW:
3358   case X86ISD::VPERMILP:
3359   case X86ISD::VPERMI:
3360     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3361   }
3362 }
3363
3364 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3365                                     SDValue V1, SDValue V2, unsigned TargetMask,
3366                                     SelectionDAG &DAG) {
3367   switch(Opc) {
3368   default: llvm_unreachable("Unknown x86 shuffle node");
3369   case X86ISD::PALIGNR:
3370   case X86ISD::SHUFP:
3371   case X86ISD::VPERM2X128:
3372     return DAG.getNode(Opc, dl, VT, V1, V2,
3373                        DAG.getConstant(TargetMask, MVT::i8));
3374   }
3375 }
3376
3377 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3378                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3379   switch(Opc) {
3380   default: llvm_unreachable("Unknown x86 shuffle node");
3381   case X86ISD::MOVLHPS:
3382   case X86ISD::MOVLHPD:
3383   case X86ISD::MOVHLPS:
3384   case X86ISD::MOVLPS:
3385   case X86ISD::MOVLPD:
3386   case X86ISD::MOVSS:
3387   case X86ISD::MOVSD:
3388   case X86ISD::UNPCKL:
3389   case X86ISD::UNPCKH:
3390     return DAG.getNode(Opc, dl, VT, V1, V2);
3391   }
3392 }
3393
3394 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3395   MachineFunction &MF = DAG.getMachineFunction();
3396   const X86RegisterInfo *RegInfo =
3397     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3398   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3399   int ReturnAddrIndex = FuncInfo->getRAIndex();
3400
3401   if (ReturnAddrIndex == 0) {
3402     // Set up a frame object for the return address.
3403     unsigned SlotSize = RegInfo->getSlotSize();
3404     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3405                                                            -(int64_t)SlotSize,
3406                                                            false);
3407     FuncInfo->setRAIndex(ReturnAddrIndex);
3408   }
3409
3410   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3411 }
3412
3413 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3414                                        bool hasSymbolicDisplacement) {
3415   // Offset should fit into 32 bit immediate field.
3416   if (!isInt<32>(Offset))
3417     return false;
3418
3419   // If we don't have a symbolic displacement - we don't have any extra
3420   // restrictions.
3421   if (!hasSymbolicDisplacement)
3422     return true;
3423
3424   // FIXME: Some tweaks might be needed for medium code model.
3425   if (M != CodeModel::Small && M != CodeModel::Kernel)
3426     return false;
3427
3428   // For small code model we assume that latest object is 16MB before end of 31
3429   // bits boundary. We may also accept pretty large negative constants knowing
3430   // that all objects are in the positive half of address space.
3431   if (M == CodeModel::Small && Offset < 16*1024*1024)
3432     return true;
3433
3434   // For kernel code model we know that all object resist in the negative half
3435   // of 32bits address space. We may not accept negative offsets, since they may
3436   // be just off and we may accept pretty large positive ones.
3437   if (M == CodeModel::Kernel && Offset > 0)
3438     return true;
3439
3440   return false;
3441 }
3442
3443 /// isCalleePop - Determines whether the callee is required to pop its
3444 /// own arguments. Callee pop is necessary to support tail calls.
3445 bool X86::isCalleePop(CallingConv::ID CallingConv,
3446                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3447   if (IsVarArg)
3448     return false;
3449
3450   switch (CallingConv) {
3451   default:
3452     return false;
3453   case CallingConv::X86_StdCall:
3454     return !is64Bit;
3455   case CallingConv::X86_FastCall:
3456     return !is64Bit;
3457   case CallingConv::X86_ThisCall:
3458     return !is64Bit;
3459   case CallingConv::Fast:
3460     return TailCallOpt;
3461   case CallingConv::GHC:
3462     return TailCallOpt;
3463   case CallingConv::HiPE:
3464     return TailCallOpt;
3465   }
3466 }
3467
3468 /// \brief Return true if the condition is an unsigned comparison operation.
3469 static bool isX86CCUnsigned(unsigned X86CC) {
3470   switch (X86CC) {
3471   default: llvm_unreachable("Invalid integer condition!");
3472   case X86::COND_E:     return true;
3473   case X86::COND_G:     return false;
3474   case X86::COND_GE:    return false;
3475   case X86::COND_L:     return false;
3476   case X86::COND_LE:    return false;
3477   case X86::COND_NE:    return true;
3478   case X86::COND_B:     return true;
3479   case X86::COND_A:     return true;
3480   case X86::COND_BE:    return true;
3481   case X86::COND_AE:    return true;
3482   }
3483   llvm_unreachable("covered switch fell through?!");
3484 }
3485
3486 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3487 /// specific condition code, returning the condition code and the LHS/RHS of the
3488 /// comparison to make.
3489 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3490                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3491   if (!isFP) {
3492     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3493       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3494         // X > -1   -> X == 0, jump !sign.
3495         RHS = DAG.getConstant(0, RHS.getValueType());
3496         return X86::COND_NS;
3497       }
3498       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3499         // X < 0   -> X == 0, jump on sign.
3500         return X86::COND_S;
3501       }
3502       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3503         // X < 1   -> X <= 0
3504         RHS = DAG.getConstant(0, RHS.getValueType());
3505         return X86::COND_LE;
3506       }
3507     }
3508
3509     switch (SetCCOpcode) {
3510     default: llvm_unreachable("Invalid integer condition!");
3511     case ISD::SETEQ:  return X86::COND_E;
3512     case ISD::SETGT:  return X86::COND_G;
3513     case ISD::SETGE:  return X86::COND_GE;
3514     case ISD::SETLT:  return X86::COND_L;
3515     case ISD::SETLE:  return X86::COND_LE;
3516     case ISD::SETNE:  return X86::COND_NE;
3517     case ISD::SETULT: return X86::COND_B;
3518     case ISD::SETUGT: return X86::COND_A;
3519     case ISD::SETULE: return X86::COND_BE;
3520     case ISD::SETUGE: return X86::COND_AE;
3521     }
3522   }
3523
3524   // First determine if it is required or is profitable to flip the operands.
3525
3526   // If LHS is a foldable load, but RHS is not, flip the condition.
3527   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3528       !ISD::isNON_EXTLoad(RHS.getNode())) {
3529     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3530     std::swap(LHS, RHS);
3531   }
3532
3533   switch (SetCCOpcode) {
3534   default: break;
3535   case ISD::SETOLT:
3536   case ISD::SETOLE:
3537   case ISD::SETUGT:
3538   case ISD::SETUGE:
3539     std::swap(LHS, RHS);
3540     break;
3541   }
3542
3543   // On a floating point condition, the flags are set as follows:
3544   // ZF  PF  CF   op
3545   //  0 | 0 | 0 | X > Y
3546   //  0 | 0 | 1 | X < Y
3547   //  1 | 0 | 0 | X == Y
3548   //  1 | 1 | 1 | unordered
3549   switch (SetCCOpcode) {
3550   default: llvm_unreachable("Condcode should be pre-legalized away");
3551   case ISD::SETUEQ:
3552   case ISD::SETEQ:   return X86::COND_E;
3553   case ISD::SETOLT:              // flipped
3554   case ISD::SETOGT:
3555   case ISD::SETGT:   return X86::COND_A;
3556   case ISD::SETOLE:              // flipped
3557   case ISD::SETOGE:
3558   case ISD::SETGE:   return X86::COND_AE;
3559   case ISD::SETUGT:              // flipped
3560   case ISD::SETULT:
3561   case ISD::SETLT:   return X86::COND_B;
3562   case ISD::SETUGE:              // flipped
3563   case ISD::SETULE:
3564   case ISD::SETLE:   return X86::COND_BE;
3565   case ISD::SETONE:
3566   case ISD::SETNE:   return X86::COND_NE;
3567   case ISD::SETUO:   return X86::COND_P;
3568   case ISD::SETO:    return X86::COND_NP;
3569   case ISD::SETOEQ:
3570   case ISD::SETUNE:  return X86::COND_INVALID;
3571   }
3572 }
3573
3574 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3575 /// code. Current x86 isa includes the following FP cmov instructions:
3576 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3577 static bool hasFPCMov(unsigned X86CC) {
3578   switch (X86CC) {
3579   default:
3580     return false;
3581   case X86::COND_B:
3582   case X86::COND_BE:
3583   case X86::COND_E:
3584   case X86::COND_P:
3585   case X86::COND_A:
3586   case X86::COND_AE:
3587   case X86::COND_NE:
3588   case X86::COND_NP:
3589     return true;
3590   }
3591 }
3592
3593 /// isFPImmLegal - Returns true if the target can instruction select the
3594 /// specified FP immediate natively. If false, the legalizer will
3595 /// materialize the FP immediate as a load from a constant pool.
3596 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3597   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3598     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3599       return true;
3600   }
3601   return false;
3602 }
3603
3604 /// \brief Returns true if it is beneficial to convert a load of a constant
3605 /// to just the constant itself.
3606 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3607                                                           Type *Ty) const {
3608   assert(Ty->isIntegerTy());
3609
3610   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3611   if (BitSize == 0 || BitSize > 64)
3612     return false;
3613   return true;
3614 }
3615
3616 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3617 /// the specified range (L, H].
3618 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3619   return (Val < 0) || (Val >= Low && Val < Hi);
3620 }
3621
3622 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3623 /// specified value.
3624 static bool isUndefOrEqual(int Val, int CmpVal) {
3625   return (Val < 0 || Val == CmpVal);
3626 }
3627
3628 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3629 /// from position Pos and ending in Pos+Size, falls within the specified
3630 /// sequential range (L, L+Pos]. or is undef.
3631 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3632                                        unsigned Pos, unsigned Size, int Low) {
3633   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3634     if (!isUndefOrEqual(Mask[i], Low))
3635       return false;
3636   return true;
3637 }
3638
3639 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3640 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3641 /// the second operand.
3642 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3643   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3644     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3645   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3646     return (Mask[0] < 2 && Mask[1] < 2);
3647   return false;
3648 }
3649
3650 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3651 /// is suitable for input to PSHUFHW.
3652 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3653   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3654     return false;
3655
3656   // Lower quadword copied in order or undef.
3657   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3658     return false;
3659
3660   // Upper quadword shuffled.
3661   for (unsigned i = 4; i != 8; ++i)
3662     if (!isUndefOrInRange(Mask[i], 4, 8))
3663       return false;
3664
3665   if (VT == MVT::v16i16) {
3666     // Lower quadword copied in order or undef.
3667     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3668       return false;
3669
3670     // Upper quadword shuffled.
3671     for (unsigned i = 12; i != 16; ++i)
3672       if (!isUndefOrInRange(Mask[i], 12, 16))
3673         return false;
3674   }
3675
3676   return true;
3677 }
3678
3679 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3680 /// is suitable for input to PSHUFLW.
3681 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3682   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3683     return false;
3684
3685   // Upper quadword copied in order.
3686   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3687     return false;
3688
3689   // Lower quadword shuffled.
3690   for (unsigned i = 0; i != 4; ++i)
3691     if (!isUndefOrInRange(Mask[i], 0, 4))
3692       return false;
3693
3694   if (VT == MVT::v16i16) {
3695     // Upper quadword copied in order.
3696     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3697       return false;
3698
3699     // Lower quadword shuffled.
3700     for (unsigned i = 8; i != 12; ++i)
3701       if (!isUndefOrInRange(Mask[i], 8, 12))
3702         return false;
3703   }
3704
3705   return true;
3706 }
3707
3708 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3709 /// is suitable for input to PALIGNR.
3710 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3711                           const X86Subtarget *Subtarget) {
3712   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3713       (VT.is256BitVector() && !Subtarget->hasInt256()))
3714     return false;
3715
3716   unsigned NumElts = VT.getVectorNumElements();
3717   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3718   unsigned NumLaneElts = NumElts/NumLanes;
3719
3720   // Do not handle 64-bit element shuffles with palignr.
3721   if (NumLaneElts == 2)
3722     return false;
3723
3724   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3725     unsigned i;
3726     for (i = 0; i != NumLaneElts; ++i) {
3727       if (Mask[i+l] >= 0)
3728         break;
3729     }
3730
3731     // Lane is all undef, go to next lane
3732     if (i == NumLaneElts)
3733       continue;
3734
3735     int Start = Mask[i+l];
3736
3737     // Make sure its in this lane in one of the sources
3738     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3739         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3740       return false;
3741
3742     // If not lane 0, then we must match lane 0
3743     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3744       return false;
3745
3746     // Correct second source to be contiguous with first source
3747     if (Start >= (int)NumElts)
3748       Start -= NumElts - NumLaneElts;
3749
3750     // Make sure we're shifting in the right direction.
3751     if (Start <= (int)(i+l))
3752       return false;
3753
3754     Start -= i;
3755
3756     // Check the rest of the elements to see if they are consecutive.
3757     for (++i; i != NumLaneElts; ++i) {
3758       int Idx = Mask[i+l];
3759
3760       // Make sure its in this lane
3761       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3762           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3763         return false;
3764
3765       // If not lane 0, then we must match lane 0
3766       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3767         return false;
3768
3769       if (Idx >= (int)NumElts)
3770         Idx -= NumElts - NumLaneElts;
3771
3772       if (!isUndefOrEqual(Idx, Start+i))
3773         return false;
3774
3775     }
3776   }
3777
3778   return true;
3779 }
3780
3781 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3782 /// the two vector operands have swapped position.
3783 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3784                                      unsigned NumElems) {
3785   for (unsigned i = 0; i != NumElems; ++i) {
3786     int idx = Mask[i];
3787     if (idx < 0)
3788       continue;
3789     else if (idx < (int)NumElems)
3790       Mask[i] = idx + NumElems;
3791     else
3792       Mask[i] = idx - NumElems;
3793   }
3794 }
3795
3796 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3797 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3798 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3799 /// reverse of what x86 shuffles want.
3800 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3801
3802   unsigned NumElems = VT.getVectorNumElements();
3803   unsigned NumLanes = VT.getSizeInBits()/128;
3804   unsigned NumLaneElems = NumElems/NumLanes;
3805
3806   if (NumLaneElems != 2 && NumLaneElems != 4)
3807     return false;
3808
3809   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3810   bool symetricMaskRequired =
3811     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3812
3813   // VSHUFPSY divides the resulting vector into 4 chunks.
3814   // The sources are also splitted into 4 chunks, and each destination
3815   // chunk must come from a different source chunk.
3816   //
3817   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3818   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3819   //
3820   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3821   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3822   //
3823   // VSHUFPDY divides the resulting vector into 4 chunks.
3824   // The sources are also splitted into 4 chunks, and each destination
3825   // chunk must come from a different source chunk.
3826   //
3827   //  SRC1 =>      X3       X2       X1       X0
3828   //  SRC2 =>      Y3       Y2       Y1       Y0
3829   //
3830   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3831   //
3832   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3833   unsigned HalfLaneElems = NumLaneElems/2;
3834   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3835     for (unsigned i = 0; i != NumLaneElems; ++i) {
3836       int Idx = Mask[i+l];
3837       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3838       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3839         return false;
3840       // For VSHUFPSY, the mask of the second half must be the same as the
3841       // first but with the appropriate offsets. This works in the same way as
3842       // VPERMILPS works with masks.
3843       if (!symetricMaskRequired || Idx < 0)
3844         continue;
3845       if (MaskVal[i] < 0) {
3846         MaskVal[i] = Idx - l;
3847         continue;
3848       }
3849       if ((signed)(Idx - l) != MaskVal[i])
3850         return false;
3851     }
3852   }
3853
3854   return true;
3855 }
3856
3857 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3858 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3859 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3860   if (!VT.is128BitVector())
3861     return false;
3862
3863   unsigned NumElems = VT.getVectorNumElements();
3864
3865   if (NumElems != 4)
3866     return false;
3867
3868   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3869   return isUndefOrEqual(Mask[0], 6) &&
3870          isUndefOrEqual(Mask[1], 7) &&
3871          isUndefOrEqual(Mask[2], 2) &&
3872          isUndefOrEqual(Mask[3], 3);
3873 }
3874
3875 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3876 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3877 /// <2, 3, 2, 3>
3878 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3879   if (!VT.is128BitVector())
3880     return false;
3881
3882   unsigned NumElems = VT.getVectorNumElements();
3883
3884   if (NumElems != 4)
3885     return false;
3886
3887   return isUndefOrEqual(Mask[0], 2) &&
3888          isUndefOrEqual(Mask[1], 3) &&
3889          isUndefOrEqual(Mask[2], 2) &&
3890          isUndefOrEqual(Mask[3], 3);
3891 }
3892
3893 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3895 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3896   if (!VT.is128BitVector())
3897     return false;
3898
3899   unsigned NumElems = VT.getVectorNumElements();
3900
3901   if (NumElems != 2 && NumElems != 4)
3902     return false;
3903
3904   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3905     if (!isUndefOrEqual(Mask[i], i + NumElems))
3906       return false;
3907
3908   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3909     if (!isUndefOrEqual(Mask[i], i))
3910       return false;
3911
3912   return true;
3913 }
3914
3915 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3916 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3917 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3918   if (!VT.is128BitVector())
3919     return false;
3920
3921   unsigned NumElems = VT.getVectorNumElements();
3922
3923   if (NumElems != 2 && NumElems != 4)
3924     return false;
3925
3926   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3927     if (!isUndefOrEqual(Mask[i], i))
3928       return false;
3929
3930   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3931     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3932       return false;
3933
3934   return true;
3935 }
3936
3937 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3938 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3939 /// i. e: If all but one element come from the same vector.
3940 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3941   // TODO: Deal with AVX's VINSERTPS
3942   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3943     return false;
3944
3945   unsigned CorrectPosV1 = 0;
3946   unsigned CorrectPosV2 = 0;
3947   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3948     if (Mask[i] == i)
3949       ++CorrectPosV1;
3950     else if (Mask[i] == i + 4)
3951       ++CorrectPosV2;
3952
3953   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3954     // We have 3 elements from one vector, and one from another.
3955     return true;
3956
3957   return false;
3958 }
3959
3960 //
3961 // Some special combinations that can be optimized.
3962 //
3963 static
3964 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3965                                SelectionDAG &DAG) {
3966   MVT VT = SVOp->getSimpleValueType(0);
3967   SDLoc dl(SVOp);
3968
3969   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3970     return SDValue();
3971
3972   ArrayRef<int> Mask = SVOp->getMask();
3973
3974   // These are the special masks that may be optimized.
3975   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3976   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3977   bool MatchEvenMask = true;
3978   bool MatchOddMask  = true;
3979   for (int i=0; i<8; ++i) {
3980     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3981       MatchEvenMask = false;
3982     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3983       MatchOddMask = false;
3984   }
3985
3986   if (!MatchEvenMask && !MatchOddMask)
3987     return SDValue();
3988
3989   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3990
3991   SDValue Op0 = SVOp->getOperand(0);
3992   SDValue Op1 = SVOp->getOperand(1);
3993
3994   if (MatchEvenMask) {
3995     // Shift the second operand right to 32 bits.
3996     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3997     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3998   } else {
3999     // Shift the first operand left to 32 bits.
4000     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4001     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4002   }
4003   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4004   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4005 }
4006
4007 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4008 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4009 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4010                          bool HasInt256, bool V2IsSplat = false) {
4011
4012   assert(VT.getSizeInBits() >= 128 &&
4013          "Unsupported vector type for unpckl");
4014
4015   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4016   unsigned NumLanes;
4017   unsigned NumOf256BitLanes;
4018   unsigned NumElts = VT.getVectorNumElements();
4019   if (VT.is256BitVector()) {
4020     if (NumElts != 4 && NumElts != 8 &&
4021         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4022     return false;
4023     NumLanes = 2;
4024     NumOf256BitLanes = 1;
4025   } else if (VT.is512BitVector()) {
4026     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4027            "Unsupported vector type for unpckh");
4028     NumLanes = 2;
4029     NumOf256BitLanes = 2;
4030   } else {
4031     NumLanes = 1;
4032     NumOf256BitLanes = 1;
4033   }
4034
4035   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4036   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4037
4038   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4039     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4040       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4041         int BitI  = Mask[l256*NumEltsInStride+l+i];
4042         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4043         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4044           return false;
4045         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4046           return false;
4047         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4048           return false;
4049       }
4050     }
4051   }
4052   return true;
4053 }
4054
4055 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4056 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4057 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4058                          bool HasInt256, bool V2IsSplat = false) {
4059   assert(VT.getSizeInBits() >= 128 &&
4060          "Unsupported vector type for unpckh");
4061
4062   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4063   unsigned NumLanes;
4064   unsigned NumOf256BitLanes;
4065   unsigned NumElts = VT.getVectorNumElements();
4066   if (VT.is256BitVector()) {
4067     if (NumElts != 4 && NumElts != 8 &&
4068         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4069     return false;
4070     NumLanes = 2;
4071     NumOf256BitLanes = 1;
4072   } else if (VT.is512BitVector()) {
4073     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4074            "Unsupported vector type for unpckh");
4075     NumLanes = 2;
4076     NumOf256BitLanes = 2;
4077   } else {
4078     NumLanes = 1;
4079     NumOf256BitLanes = 1;
4080   }
4081
4082   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4083   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4084
4085   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4086     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4087       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4088         int BitI  = Mask[l256*NumEltsInStride+l+i];
4089         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4090         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4091           return false;
4092         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4093           return false;
4094         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4095           return false;
4096       }
4097     }
4098   }
4099   return true;
4100 }
4101
4102 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4103 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4104 /// <0, 0, 1, 1>
4105 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4106   unsigned NumElts = VT.getVectorNumElements();
4107   bool Is256BitVec = VT.is256BitVector();
4108
4109   if (VT.is512BitVector())
4110     return false;
4111   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4112          "Unsupported vector type for unpckh");
4113
4114   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4115       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4116     return false;
4117
4118   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4119   // FIXME: Need a better way to get rid of this, there's no latency difference
4120   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4121   // the former later. We should also remove the "_undef" special mask.
4122   if (NumElts == 4 && Is256BitVec)
4123     return false;
4124
4125   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4126   // independently on 128-bit lanes.
4127   unsigned NumLanes = VT.getSizeInBits()/128;
4128   unsigned NumLaneElts = NumElts/NumLanes;
4129
4130   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4131     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4132       int BitI  = Mask[l+i];
4133       int BitI1 = Mask[l+i+1];
4134
4135       if (!isUndefOrEqual(BitI, j))
4136         return false;
4137       if (!isUndefOrEqual(BitI1, j))
4138         return false;
4139     }
4140   }
4141
4142   return true;
4143 }
4144
4145 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4146 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4147 /// <2, 2, 3, 3>
4148 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4149   unsigned NumElts = VT.getVectorNumElements();
4150
4151   if (VT.is512BitVector())
4152     return false;
4153
4154   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4155          "Unsupported vector type for unpckh");
4156
4157   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4158       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4159     return false;
4160
4161   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4162   // independently on 128-bit lanes.
4163   unsigned NumLanes = VT.getSizeInBits()/128;
4164   unsigned NumLaneElts = NumElts/NumLanes;
4165
4166   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4167     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4168       int BitI  = Mask[l+i];
4169       int BitI1 = Mask[l+i+1];
4170       if (!isUndefOrEqual(BitI, j))
4171         return false;
4172       if (!isUndefOrEqual(BitI1, j))
4173         return false;
4174     }
4175   }
4176   return true;
4177 }
4178
4179 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4180 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4181 /// MOVSD, and MOVD, i.e. setting the lowest element.
4182 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4183   if (VT.getVectorElementType().getSizeInBits() < 32)
4184     return false;
4185   if (!VT.is128BitVector())
4186     return false;
4187
4188   unsigned NumElts = VT.getVectorNumElements();
4189
4190   if (!isUndefOrEqual(Mask[0], NumElts))
4191     return false;
4192
4193   for (unsigned i = 1; i != NumElts; ++i)
4194     if (!isUndefOrEqual(Mask[i], i))
4195       return false;
4196
4197   return true;
4198 }
4199
4200 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4201 /// as permutations between 128-bit chunks or halves. As an example: this
4202 /// shuffle bellow:
4203 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4204 /// The first half comes from the second half of V1 and the second half from the
4205 /// the second half of V2.
4206 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4207   if (!HasFp256 || !VT.is256BitVector())
4208     return false;
4209
4210   // The shuffle result is divided into half A and half B. In total the two
4211   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4212   // B must come from C, D, E or F.
4213   unsigned HalfSize = VT.getVectorNumElements()/2;
4214   bool MatchA = false, MatchB = false;
4215
4216   // Check if A comes from one of C, D, E, F.
4217   for (unsigned Half = 0; Half != 4; ++Half) {
4218     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4219       MatchA = true;
4220       break;
4221     }
4222   }
4223
4224   // Check if B comes from one of C, D, E, F.
4225   for (unsigned Half = 0; Half != 4; ++Half) {
4226     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4227       MatchB = true;
4228       break;
4229     }
4230   }
4231
4232   return MatchA && MatchB;
4233 }
4234
4235 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4236 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4237 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4238   MVT VT = SVOp->getSimpleValueType(0);
4239
4240   unsigned HalfSize = VT.getVectorNumElements()/2;
4241
4242   unsigned FstHalf = 0, SndHalf = 0;
4243   for (unsigned i = 0; i < HalfSize; ++i) {
4244     if (SVOp->getMaskElt(i) > 0) {
4245       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4246       break;
4247     }
4248   }
4249   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4250     if (SVOp->getMaskElt(i) > 0) {
4251       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4252       break;
4253     }
4254   }
4255
4256   return (FstHalf | (SndHalf << 4));
4257 }
4258
4259 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4260 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4261   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4262   if (EltSize < 32)
4263     return false;
4264
4265   unsigned NumElts = VT.getVectorNumElements();
4266   Imm8 = 0;
4267   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4268     for (unsigned i = 0; i != NumElts; ++i) {
4269       if (Mask[i] < 0)
4270         continue;
4271       Imm8 |= Mask[i] << (i*2);
4272     }
4273     return true;
4274   }
4275
4276   unsigned LaneSize = 4;
4277   SmallVector<int, 4> MaskVal(LaneSize, -1);
4278
4279   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4280     for (unsigned i = 0; i != LaneSize; ++i) {
4281       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4282         return false;
4283       if (Mask[i+l] < 0)
4284         continue;
4285       if (MaskVal[i] < 0) {
4286         MaskVal[i] = Mask[i+l] - l;
4287         Imm8 |= MaskVal[i] << (i*2);
4288         continue;
4289       }
4290       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4291         return false;
4292     }
4293   }
4294   return true;
4295 }
4296
4297 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4298 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4299 /// Note that VPERMIL mask matching is different depending whether theunderlying
4300 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4301 /// to the same elements of the low, but to the higher half of the source.
4302 /// In VPERMILPD the two lanes could be shuffled independently of each other
4303 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4304 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4305   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4306   if (VT.getSizeInBits() < 256 || EltSize < 32)
4307     return false;
4308   bool symetricMaskRequired = (EltSize == 32);
4309   unsigned NumElts = VT.getVectorNumElements();
4310
4311   unsigned NumLanes = VT.getSizeInBits()/128;
4312   unsigned LaneSize = NumElts/NumLanes;
4313   // 2 or 4 elements in one lane
4314
4315   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4316   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4317     for (unsigned i = 0; i != LaneSize; ++i) {
4318       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4319         return false;
4320       if (symetricMaskRequired) {
4321         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4322           ExpectedMaskVal[i] = Mask[i+l] - l;
4323           continue;
4324         }
4325         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4326           return false;
4327       }
4328     }
4329   }
4330   return true;
4331 }
4332
4333 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4334 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4335 /// element of vector 2 and the other elements to come from vector 1 in order.
4336 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4337                                bool V2IsSplat = false, bool V2IsUndef = false) {
4338   if (!VT.is128BitVector())
4339     return false;
4340
4341   unsigned NumOps = VT.getVectorNumElements();
4342   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4343     return false;
4344
4345   if (!isUndefOrEqual(Mask[0], 0))
4346     return false;
4347
4348   for (unsigned i = 1; i != NumOps; ++i)
4349     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4350           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4351           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4352       return false;
4353
4354   return true;
4355 }
4356
4357 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4358 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4359 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4360 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4361                            const X86Subtarget *Subtarget) {
4362   if (!Subtarget->hasSSE3())
4363     return false;
4364
4365   unsigned NumElems = VT.getVectorNumElements();
4366
4367   if ((VT.is128BitVector() && NumElems != 4) ||
4368       (VT.is256BitVector() && NumElems != 8) ||
4369       (VT.is512BitVector() && NumElems != 16))
4370     return false;
4371
4372   // "i+1" is the value the indexed mask element must have
4373   for (unsigned i = 0; i != NumElems; i += 2)
4374     if (!isUndefOrEqual(Mask[i], i+1) ||
4375         !isUndefOrEqual(Mask[i+1], i+1))
4376       return false;
4377
4378   return true;
4379 }
4380
4381 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4382 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4383 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4384 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4385                            const X86Subtarget *Subtarget) {
4386   if (!Subtarget->hasSSE3())
4387     return false;
4388
4389   unsigned NumElems = VT.getVectorNumElements();
4390
4391   if ((VT.is128BitVector() && NumElems != 4) ||
4392       (VT.is256BitVector() && NumElems != 8) ||
4393       (VT.is512BitVector() && NumElems != 16))
4394     return false;
4395
4396   // "i" is the value the indexed mask element must have
4397   for (unsigned i = 0; i != NumElems; i += 2)
4398     if (!isUndefOrEqual(Mask[i], i) ||
4399         !isUndefOrEqual(Mask[i+1], i))
4400       return false;
4401
4402   return true;
4403 }
4404
4405 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4406 /// specifies a shuffle of elements that is suitable for input to 256-bit
4407 /// version of MOVDDUP.
4408 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4409   if (!HasFp256 || !VT.is256BitVector())
4410     return false;
4411
4412   unsigned NumElts = VT.getVectorNumElements();
4413   if (NumElts != 4)
4414     return false;
4415
4416   for (unsigned i = 0; i != NumElts/2; ++i)
4417     if (!isUndefOrEqual(Mask[i], 0))
4418       return false;
4419   for (unsigned i = NumElts/2; i != NumElts; ++i)
4420     if (!isUndefOrEqual(Mask[i], NumElts/2))
4421       return false;
4422   return true;
4423 }
4424
4425 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4426 /// specifies a shuffle of elements that is suitable for input to 128-bit
4427 /// version of MOVDDUP.
4428 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4429   if (!VT.is128BitVector())
4430     return false;
4431
4432   unsigned e = VT.getVectorNumElements() / 2;
4433   for (unsigned i = 0; i != e; ++i)
4434     if (!isUndefOrEqual(Mask[i], i))
4435       return false;
4436   for (unsigned i = 0; i != e; ++i)
4437     if (!isUndefOrEqual(Mask[e+i], i))
4438       return false;
4439   return true;
4440 }
4441
4442 /// isVEXTRACTIndex - Return true if the specified
4443 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4444 /// suitable for instruction that extract 128 or 256 bit vectors
4445 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4446   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4447   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4448     return false;
4449
4450   // The index should be aligned on a vecWidth-bit boundary.
4451   uint64_t Index =
4452     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4453
4454   MVT VT = N->getSimpleValueType(0);
4455   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4456   bool Result = (Index * ElSize) % vecWidth == 0;
4457
4458   return Result;
4459 }
4460
4461 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4462 /// operand specifies a subvector insert that is suitable for input to
4463 /// insertion of 128 or 256-bit subvectors
4464 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4465   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4466   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4467     return false;
4468   // The index should be aligned on a vecWidth-bit boundary.
4469   uint64_t Index =
4470     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4471
4472   MVT VT = N->getSimpleValueType(0);
4473   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4474   bool Result = (Index * ElSize) % vecWidth == 0;
4475
4476   return Result;
4477 }
4478
4479 bool X86::isVINSERT128Index(SDNode *N) {
4480   return isVINSERTIndex(N, 128);
4481 }
4482
4483 bool X86::isVINSERT256Index(SDNode *N) {
4484   return isVINSERTIndex(N, 256);
4485 }
4486
4487 bool X86::isVEXTRACT128Index(SDNode *N) {
4488   return isVEXTRACTIndex(N, 128);
4489 }
4490
4491 bool X86::isVEXTRACT256Index(SDNode *N) {
4492   return isVEXTRACTIndex(N, 256);
4493 }
4494
4495 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4496 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4497 /// Handles 128-bit and 256-bit.
4498 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4499   MVT VT = N->getSimpleValueType(0);
4500
4501   assert((VT.getSizeInBits() >= 128) &&
4502          "Unsupported vector type for PSHUF/SHUFP");
4503
4504   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4505   // independently on 128-bit lanes.
4506   unsigned NumElts = VT.getVectorNumElements();
4507   unsigned NumLanes = VT.getSizeInBits()/128;
4508   unsigned NumLaneElts = NumElts/NumLanes;
4509
4510   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4511          "Only supports 2, 4 or 8 elements per lane");
4512
4513   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4514   unsigned Mask = 0;
4515   for (unsigned i = 0; i != NumElts; ++i) {
4516     int Elt = N->getMaskElt(i);
4517     if (Elt < 0) continue;
4518     Elt &= NumLaneElts - 1;
4519     unsigned ShAmt = (i << Shift) % 8;
4520     Mask |= Elt << ShAmt;
4521   }
4522
4523   return Mask;
4524 }
4525
4526 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4527 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4528 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4529   MVT VT = N->getSimpleValueType(0);
4530
4531   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4532          "Unsupported vector type for PSHUFHW");
4533
4534   unsigned NumElts = VT.getVectorNumElements();
4535
4536   unsigned Mask = 0;
4537   for (unsigned l = 0; l != NumElts; l += 8) {
4538     // 8 nodes per lane, but we only care about the last 4.
4539     for (unsigned i = 0; i < 4; ++i) {
4540       int Elt = N->getMaskElt(l+i+4);
4541       if (Elt < 0) continue;
4542       Elt &= 0x3; // only 2-bits.
4543       Mask |= Elt << (i * 2);
4544     }
4545   }
4546
4547   return Mask;
4548 }
4549
4550 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4551 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4552 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4553   MVT VT = N->getSimpleValueType(0);
4554
4555   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4556          "Unsupported vector type for PSHUFHW");
4557
4558   unsigned NumElts = VT.getVectorNumElements();
4559
4560   unsigned Mask = 0;
4561   for (unsigned l = 0; l != NumElts; l += 8) {
4562     // 8 nodes per lane, but we only care about the first 4.
4563     for (unsigned i = 0; i < 4; ++i) {
4564       int Elt = N->getMaskElt(l+i);
4565       if (Elt < 0) continue;
4566       Elt &= 0x3; // only 2-bits
4567       Mask |= Elt << (i * 2);
4568     }
4569   }
4570
4571   return Mask;
4572 }
4573
4574 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4575 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4576 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4577   MVT VT = SVOp->getSimpleValueType(0);
4578   unsigned EltSize = VT.is512BitVector() ? 1 :
4579     VT.getVectorElementType().getSizeInBits() >> 3;
4580
4581   unsigned NumElts = VT.getVectorNumElements();
4582   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4583   unsigned NumLaneElts = NumElts/NumLanes;
4584
4585   int Val = 0;
4586   unsigned i;
4587   for (i = 0; i != NumElts; ++i) {
4588     Val = SVOp->getMaskElt(i);
4589     if (Val >= 0)
4590       break;
4591   }
4592   if (Val >= (int)NumElts)
4593     Val -= NumElts - NumLaneElts;
4594
4595   assert(Val - i > 0 && "PALIGNR imm should be positive");
4596   return (Val - i) * EltSize;
4597 }
4598
4599 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4600   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4601   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4602     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4603
4604   uint64_t Index =
4605     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4606
4607   MVT VecVT = N->getOperand(0).getSimpleValueType();
4608   MVT ElVT = VecVT.getVectorElementType();
4609
4610   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4611   return Index / NumElemsPerChunk;
4612 }
4613
4614 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4615   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4616   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4617     llvm_unreachable("Illegal insert subvector for VINSERT");
4618
4619   uint64_t Index =
4620     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4621
4622   MVT VecVT = N->getSimpleValueType(0);
4623   MVT ElVT = VecVT.getVectorElementType();
4624
4625   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4626   return Index / NumElemsPerChunk;
4627 }
4628
4629 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4630 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4631 /// and VINSERTI128 instructions.
4632 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4633   return getExtractVEXTRACTImmediate(N, 128);
4634 }
4635
4636 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4637 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4638 /// and VINSERTI64x4 instructions.
4639 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4640   return getExtractVEXTRACTImmediate(N, 256);
4641 }
4642
4643 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4644 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4645 /// and VINSERTI128 instructions.
4646 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4647   return getInsertVINSERTImmediate(N, 128);
4648 }
4649
4650 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4651 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4652 /// and VINSERTI64x4 instructions.
4653 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4654   return getInsertVINSERTImmediate(N, 256);
4655 }
4656
4657 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4658 /// constant +0.0.
4659 bool X86::isZeroNode(SDValue Elt) {
4660   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4661     return CN->isNullValue();
4662   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4663     return CFP->getValueAPF().isPosZero();
4664   return false;
4665 }
4666
4667 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4668 /// their permute mask.
4669 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4670                                     SelectionDAG &DAG) {
4671   MVT VT = SVOp->getSimpleValueType(0);
4672   unsigned NumElems = VT.getVectorNumElements();
4673   SmallVector<int, 8> MaskVec;
4674
4675   for (unsigned i = 0; i != NumElems; ++i) {
4676     int Idx = SVOp->getMaskElt(i);
4677     if (Idx >= 0) {
4678       if (Idx < (int)NumElems)
4679         Idx += NumElems;
4680       else
4681         Idx -= NumElems;
4682     }
4683     MaskVec.push_back(Idx);
4684   }
4685   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4686                               SVOp->getOperand(0), &MaskVec[0]);
4687 }
4688
4689 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4690 /// match movhlps. The lower half elements should come from upper half of
4691 /// V1 (and in order), and the upper half elements should come from the upper
4692 /// half of V2 (and in order).
4693 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4694   if (!VT.is128BitVector())
4695     return false;
4696   if (VT.getVectorNumElements() != 4)
4697     return false;
4698   for (unsigned i = 0, e = 2; i != e; ++i)
4699     if (!isUndefOrEqual(Mask[i], i+2))
4700       return false;
4701   for (unsigned i = 2; i != 4; ++i)
4702     if (!isUndefOrEqual(Mask[i], i+4))
4703       return false;
4704   return true;
4705 }
4706
4707 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4708 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4709 /// required.
4710 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4711   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4712     return false;
4713   N = N->getOperand(0).getNode();
4714   if (!ISD::isNON_EXTLoad(N))
4715     return false;
4716   if (LD)
4717     *LD = cast<LoadSDNode>(N);
4718   return true;
4719 }
4720
4721 // Test whether the given value is a vector value which will be legalized
4722 // into a load.
4723 static bool WillBeConstantPoolLoad(SDNode *N) {
4724   if (N->getOpcode() != ISD::BUILD_VECTOR)
4725     return false;
4726
4727   // Check for any non-constant elements.
4728   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4729     switch (N->getOperand(i).getNode()->getOpcode()) {
4730     case ISD::UNDEF:
4731     case ISD::ConstantFP:
4732     case ISD::Constant:
4733       break;
4734     default:
4735       return false;
4736     }
4737
4738   // Vectors of all-zeros and all-ones are materialized with special
4739   // instructions rather than being loaded.
4740   return !ISD::isBuildVectorAllZeros(N) &&
4741          !ISD::isBuildVectorAllOnes(N);
4742 }
4743
4744 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4745 /// match movlp{s|d}. The lower half elements should come from lower half of
4746 /// V1 (and in order), and the upper half elements should come from the upper
4747 /// half of V2 (and in order). And since V1 will become the source of the
4748 /// MOVLP, it must be either a vector load or a scalar load to vector.
4749 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4750                                ArrayRef<int> Mask, MVT VT) {
4751   if (!VT.is128BitVector())
4752     return false;
4753
4754   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4755     return false;
4756   // Is V2 is a vector load, don't do this transformation. We will try to use
4757   // load folding shufps op.
4758   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4759     return false;
4760
4761   unsigned NumElems = VT.getVectorNumElements();
4762
4763   if (NumElems != 2 && NumElems != 4)
4764     return false;
4765   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4766     if (!isUndefOrEqual(Mask[i], i))
4767       return false;
4768   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4769     if (!isUndefOrEqual(Mask[i], i+NumElems))
4770       return false;
4771   return true;
4772 }
4773
4774 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4775 /// all the same.
4776 static bool isSplatVector(SDNode *N) {
4777   if (N->getOpcode() != ISD::BUILD_VECTOR)
4778     return false;
4779
4780   SDValue SplatValue = N->getOperand(0);
4781   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4782     if (N->getOperand(i) != SplatValue)
4783       return false;
4784   return true;
4785 }
4786
4787 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4788 /// to an zero vector.
4789 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4790 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4791   SDValue V1 = N->getOperand(0);
4792   SDValue V2 = N->getOperand(1);
4793   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4794   for (unsigned i = 0; i != NumElems; ++i) {
4795     int Idx = N->getMaskElt(i);
4796     if (Idx >= (int)NumElems) {
4797       unsigned Opc = V2.getOpcode();
4798       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4799         continue;
4800       if (Opc != ISD::BUILD_VECTOR ||
4801           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4802         return false;
4803     } else if (Idx >= 0) {
4804       unsigned Opc = V1.getOpcode();
4805       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4806         continue;
4807       if (Opc != ISD::BUILD_VECTOR ||
4808           !X86::isZeroNode(V1.getOperand(Idx)))
4809         return false;
4810     }
4811   }
4812   return true;
4813 }
4814
4815 /// getZeroVector - Returns a vector of specified type with all zero elements.
4816 ///
4817 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4818                              SelectionDAG &DAG, SDLoc dl) {
4819   assert(VT.isVector() && "Expected a vector type");
4820
4821   // Always build SSE zero vectors as <4 x i32> bitcasted
4822   // to their dest type. This ensures they get CSE'd.
4823   SDValue Vec;
4824   if (VT.is128BitVector()) {  // SSE
4825     if (Subtarget->hasSSE2()) {  // SSE2
4826       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4827       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4828     } else { // SSE1
4829       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4830       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4831     }
4832   } else if (VT.is256BitVector()) { // AVX
4833     if (Subtarget->hasInt256()) { // AVX2
4834       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4835       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4836       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4837                         array_lengthof(Ops));
4838     } else {
4839       // 256-bit logic and arithmetic instructions in AVX are all
4840       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4841       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4842       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4843       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4844                         array_lengthof(Ops));
4845     }
4846   } else if (VT.is512BitVector()) { // AVX-512
4847       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4848       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4849                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4850       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4851   } else if (VT.getScalarType() == MVT::i1) {
4852     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4853     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4854     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4855                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4856     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4857                        Ops, VT.getVectorNumElements());
4858   } else
4859     llvm_unreachable("Unexpected vector type");
4860
4861   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4862 }
4863
4864 /// getOnesVector - Returns a vector of specified type with all bits set.
4865 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4866 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4867 /// Then bitcast to their original type, ensuring they get CSE'd.
4868 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4869                              SDLoc dl) {
4870   assert(VT.isVector() && "Expected a vector type");
4871
4872   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4873   SDValue Vec;
4874   if (VT.is256BitVector()) {
4875     if (HasInt256) { // AVX2
4876       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4877       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4878                         array_lengthof(Ops));
4879     } else { // AVX
4880       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4881       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4882     }
4883   } else if (VT.is128BitVector()) {
4884     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4885   } else
4886     llvm_unreachable("Unexpected vector type");
4887
4888   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4889 }
4890
4891 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4892 /// that point to V2 points to its first element.
4893 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4894   for (unsigned i = 0; i != NumElems; ++i) {
4895     if (Mask[i] > (int)NumElems) {
4896       Mask[i] = NumElems;
4897     }
4898   }
4899 }
4900
4901 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4902 /// operation of specified width.
4903 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4904                        SDValue V2) {
4905   unsigned NumElems = VT.getVectorNumElements();
4906   SmallVector<int, 8> Mask;
4907   Mask.push_back(NumElems);
4908   for (unsigned i = 1; i != NumElems; ++i)
4909     Mask.push_back(i);
4910   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4911 }
4912
4913 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4914 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4915                           SDValue V2) {
4916   unsigned NumElems = VT.getVectorNumElements();
4917   SmallVector<int, 8> Mask;
4918   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4919     Mask.push_back(i);
4920     Mask.push_back(i + NumElems);
4921   }
4922   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4923 }
4924
4925 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4926 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4927                           SDValue V2) {
4928   unsigned NumElems = VT.getVectorNumElements();
4929   SmallVector<int, 8> Mask;
4930   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4931     Mask.push_back(i + Half);
4932     Mask.push_back(i + NumElems + Half);
4933   }
4934   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4935 }
4936
4937 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4938 // a generic shuffle instruction because the target has no such instructions.
4939 // Generate shuffles which repeat i16 and i8 several times until they can be
4940 // represented by v4f32 and then be manipulated by target suported shuffles.
4941 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4942   MVT VT = V.getSimpleValueType();
4943   int NumElems = VT.getVectorNumElements();
4944   SDLoc dl(V);
4945
4946   while (NumElems > 4) {
4947     if (EltNo < NumElems/2) {
4948       V = getUnpackl(DAG, dl, VT, V, V);
4949     } else {
4950       V = getUnpackh(DAG, dl, VT, V, V);
4951       EltNo -= NumElems/2;
4952     }
4953     NumElems >>= 1;
4954   }
4955   return V;
4956 }
4957
4958 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4959 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4960   MVT VT = V.getSimpleValueType();
4961   SDLoc dl(V);
4962
4963   if (VT.is128BitVector()) {
4964     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4965     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4966     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4967                              &SplatMask[0]);
4968   } else if (VT.is256BitVector()) {
4969     // To use VPERMILPS to splat scalars, the second half of indicies must
4970     // refer to the higher part, which is a duplication of the lower one,
4971     // because VPERMILPS can only handle in-lane permutations.
4972     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4973                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4974
4975     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4976     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4977                              &SplatMask[0]);
4978   } else
4979     llvm_unreachable("Vector size not supported");
4980
4981   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4982 }
4983
4984 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4985 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4986   MVT SrcVT = SV->getSimpleValueType(0);
4987   SDValue V1 = SV->getOperand(0);
4988   SDLoc dl(SV);
4989
4990   int EltNo = SV->getSplatIndex();
4991   int NumElems = SrcVT.getVectorNumElements();
4992   bool Is256BitVec = SrcVT.is256BitVector();
4993
4994   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4995          "Unknown how to promote splat for type");
4996
4997   // Extract the 128-bit part containing the splat element and update
4998   // the splat element index when it refers to the higher register.
4999   if (Is256BitVec) {
5000     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5001     if (EltNo >= NumElems/2)
5002       EltNo -= NumElems/2;
5003   }
5004
5005   // All i16 and i8 vector types can't be used directly by a generic shuffle
5006   // instruction because the target has no such instruction. Generate shuffles
5007   // which repeat i16 and i8 several times until they fit in i32, and then can
5008   // be manipulated by target suported shuffles.
5009   MVT EltVT = SrcVT.getVectorElementType();
5010   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5011     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5012
5013   // Recreate the 256-bit vector and place the same 128-bit vector
5014   // into the low and high part. This is necessary because we want
5015   // to use VPERM* to shuffle the vectors
5016   if (Is256BitVec) {
5017     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5018   }
5019
5020   return getLegalSplat(DAG, V1, EltNo);
5021 }
5022
5023 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5024 /// vector of zero or undef vector.  This produces a shuffle where the low
5025 /// element of V2 is swizzled into the zero/undef vector, landing at element
5026 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5027 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5028                                            bool IsZero,
5029                                            const X86Subtarget *Subtarget,
5030                                            SelectionDAG &DAG) {
5031   MVT VT = V2.getSimpleValueType();
5032   SDValue V1 = IsZero
5033     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5034   unsigned NumElems = VT.getVectorNumElements();
5035   SmallVector<int, 16> MaskVec;
5036   for (unsigned i = 0; i != NumElems; ++i)
5037     // If this is the insertion idx, put the low elt of V2 here.
5038     MaskVec.push_back(i == Idx ? NumElems : i);
5039   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5040 }
5041
5042 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5043 /// target specific opcode. Returns true if the Mask could be calculated.
5044 /// Sets IsUnary to true if only uses one source.
5045 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5046                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5047   unsigned NumElems = VT.getVectorNumElements();
5048   SDValue ImmN;
5049
5050   IsUnary = false;
5051   switch(N->getOpcode()) {
5052   case X86ISD::SHUFP:
5053     ImmN = N->getOperand(N->getNumOperands()-1);
5054     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5055     break;
5056   case X86ISD::UNPCKH:
5057     DecodeUNPCKHMask(VT, Mask);
5058     break;
5059   case X86ISD::UNPCKL:
5060     DecodeUNPCKLMask(VT, Mask);
5061     break;
5062   case X86ISD::MOVHLPS:
5063     DecodeMOVHLPSMask(NumElems, Mask);
5064     break;
5065   case X86ISD::MOVLHPS:
5066     DecodeMOVLHPSMask(NumElems, Mask);
5067     break;
5068   case X86ISD::PALIGNR:
5069     ImmN = N->getOperand(N->getNumOperands()-1);
5070     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5071     break;
5072   case X86ISD::PSHUFD:
5073   case X86ISD::VPERMILP:
5074     ImmN = N->getOperand(N->getNumOperands()-1);
5075     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5076     IsUnary = true;
5077     break;
5078   case X86ISD::PSHUFHW:
5079     ImmN = N->getOperand(N->getNumOperands()-1);
5080     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5081     IsUnary = true;
5082     break;
5083   case X86ISD::PSHUFLW:
5084     ImmN = N->getOperand(N->getNumOperands()-1);
5085     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5086     IsUnary = true;
5087     break;
5088   case X86ISD::VPERMI:
5089     ImmN = N->getOperand(N->getNumOperands()-1);
5090     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5091     IsUnary = true;
5092     break;
5093   case X86ISD::MOVSS:
5094   case X86ISD::MOVSD: {
5095     // The index 0 always comes from the first element of the second source,
5096     // this is why MOVSS and MOVSD are used in the first place. The other
5097     // elements come from the other positions of the first source vector
5098     Mask.push_back(NumElems);
5099     for (unsigned i = 1; i != NumElems; ++i) {
5100       Mask.push_back(i);
5101     }
5102     break;
5103   }
5104   case X86ISD::VPERM2X128:
5105     ImmN = N->getOperand(N->getNumOperands()-1);
5106     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5107     if (Mask.empty()) return false;
5108     break;
5109   case X86ISD::MOVDDUP:
5110   case X86ISD::MOVLHPD:
5111   case X86ISD::MOVLPD:
5112   case X86ISD::MOVLPS:
5113   case X86ISD::MOVSHDUP:
5114   case X86ISD::MOVSLDUP:
5115     // Not yet implemented
5116     return false;
5117   default: llvm_unreachable("unknown target shuffle node");
5118   }
5119
5120   return true;
5121 }
5122
5123 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5124 /// element of the result of the vector shuffle.
5125 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5126                                    unsigned Depth) {
5127   if (Depth == 6)
5128     return SDValue();  // Limit search depth.
5129
5130   SDValue V = SDValue(N, 0);
5131   EVT VT = V.getValueType();
5132   unsigned Opcode = V.getOpcode();
5133
5134   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5135   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5136     int Elt = SV->getMaskElt(Index);
5137
5138     if (Elt < 0)
5139       return DAG.getUNDEF(VT.getVectorElementType());
5140
5141     unsigned NumElems = VT.getVectorNumElements();
5142     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5143                                          : SV->getOperand(1);
5144     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5145   }
5146
5147   // Recurse into target specific vector shuffles to find scalars.
5148   if (isTargetShuffle(Opcode)) {
5149     MVT ShufVT = V.getSimpleValueType();
5150     unsigned NumElems = ShufVT.getVectorNumElements();
5151     SmallVector<int, 16> ShuffleMask;
5152     bool IsUnary;
5153
5154     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5155       return SDValue();
5156
5157     int Elt = ShuffleMask[Index];
5158     if (Elt < 0)
5159       return DAG.getUNDEF(ShufVT.getVectorElementType());
5160
5161     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5162                                          : N->getOperand(1);
5163     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5164                                Depth+1);
5165   }
5166
5167   // Actual nodes that may contain scalar elements
5168   if (Opcode == ISD::BITCAST) {
5169     V = V.getOperand(0);
5170     EVT SrcVT = V.getValueType();
5171     unsigned NumElems = VT.getVectorNumElements();
5172
5173     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5174       return SDValue();
5175   }
5176
5177   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5178     return (Index == 0) ? V.getOperand(0)
5179                         : DAG.getUNDEF(VT.getVectorElementType());
5180
5181   if (V.getOpcode() == ISD::BUILD_VECTOR)
5182     return V.getOperand(Index);
5183
5184   return SDValue();
5185 }
5186
5187 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5188 /// shuffle operation which come from a consecutively from a zero. The
5189 /// search can start in two different directions, from left or right.
5190 /// We count undefs as zeros until PreferredNum is reached.
5191 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5192                                          unsigned NumElems, bool ZerosFromLeft,
5193                                          SelectionDAG &DAG,
5194                                          unsigned PreferredNum = -1U) {
5195   unsigned NumZeros = 0;
5196   for (unsigned i = 0; i != NumElems; ++i) {
5197     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5198     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5199     if (!Elt.getNode())
5200       break;
5201
5202     if (X86::isZeroNode(Elt))
5203       ++NumZeros;
5204     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5205       NumZeros = std::min(NumZeros + 1, PreferredNum);
5206     else
5207       break;
5208   }
5209
5210   return NumZeros;
5211 }
5212
5213 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5214 /// correspond consecutively to elements from one of the vector operands,
5215 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5216 static
5217 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5218                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5219                               unsigned NumElems, unsigned &OpNum) {
5220   bool SeenV1 = false;
5221   bool SeenV2 = false;
5222
5223   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5224     int Idx = SVOp->getMaskElt(i);
5225     // Ignore undef indicies
5226     if (Idx < 0)
5227       continue;
5228
5229     if (Idx < (int)NumElems)
5230       SeenV1 = true;
5231     else
5232       SeenV2 = true;
5233
5234     // Only accept consecutive elements from the same vector
5235     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5236       return false;
5237   }
5238
5239   OpNum = SeenV1 ? 0 : 1;
5240   return true;
5241 }
5242
5243 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5244 /// logical left shift of a vector.
5245 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5246                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5247   unsigned NumElems =
5248     SVOp->getSimpleValueType(0).getVectorNumElements();
5249   unsigned NumZeros = getNumOfConsecutiveZeros(
5250       SVOp, NumElems, false /* check zeros from right */, DAG,
5251       SVOp->getMaskElt(0));
5252   unsigned OpSrc;
5253
5254   if (!NumZeros)
5255     return false;
5256
5257   // Considering the elements in the mask that are not consecutive zeros,
5258   // check if they consecutively come from only one of the source vectors.
5259   //
5260   //               V1 = {X, A, B, C}     0
5261   //                         \  \  \    /
5262   //   vector_shuffle V1, V2 <1, 2, 3, X>
5263   //
5264   if (!isShuffleMaskConsecutive(SVOp,
5265             0,                   // Mask Start Index
5266             NumElems-NumZeros,   // Mask End Index(exclusive)
5267             NumZeros,            // Where to start looking in the src vector
5268             NumElems,            // Number of elements in vector
5269             OpSrc))              // Which source operand ?
5270     return false;
5271
5272   isLeft = false;
5273   ShAmt = NumZeros;
5274   ShVal = SVOp->getOperand(OpSrc);
5275   return true;
5276 }
5277
5278 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5279 /// logical left shift of a vector.
5280 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5281                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5282   unsigned NumElems =
5283     SVOp->getSimpleValueType(0).getVectorNumElements();
5284   unsigned NumZeros = getNumOfConsecutiveZeros(
5285       SVOp, NumElems, true /* check zeros from left */, DAG,
5286       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5287   unsigned OpSrc;
5288
5289   if (!NumZeros)
5290     return false;
5291
5292   // Considering the elements in the mask that are not consecutive zeros,
5293   // check if they consecutively come from only one of the source vectors.
5294   //
5295   //                           0    { A, B, X, X } = V2
5296   //                          / \    /  /
5297   //   vector_shuffle V1, V2 <X, X, 4, 5>
5298   //
5299   if (!isShuffleMaskConsecutive(SVOp,
5300             NumZeros,     // Mask Start Index
5301             NumElems,     // Mask End Index(exclusive)
5302             0,            // Where to start looking in the src vector
5303             NumElems,     // Number of elements in vector
5304             OpSrc))       // Which source operand ?
5305     return false;
5306
5307   isLeft = true;
5308   ShAmt = NumZeros;
5309   ShVal = SVOp->getOperand(OpSrc);
5310   return true;
5311 }
5312
5313 /// isVectorShift - Returns true if the shuffle can be implemented as a
5314 /// logical left or right shift of a vector.
5315 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5316                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5317   // Although the logic below support any bitwidth size, there are no
5318   // shift instructions which handle more than 128-bit vectors.
5319   if (!SVOp->getSimpleValueType(0).is128BitVector())
5320     return false;
5321
5322   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5323       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5324     return true;
5325
5326   return false;
5327 }
5328
5329 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5330 ///
5331 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5332                                        unsigned NumNonZero, unsigned NumZero,
5333                                        SelectionDAG &DAG,
5334                                        const X86Subtarget* Subtarget,
5335                                        const TargetLowering &TLI) {
5336   if (NumNonZero > 8)
5337     return SDValue();
5338
5339   SDLoc dl(Op);
5340   SDValue V;
5341   bool First = true;
5342   for (unsigned i = 0; i < 16; ++i) {
5343     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5344     if (ThisIsNonZero && First) {
5345       if (NumZero)
5346         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5347       else
5348         V = DAG.getUNDEF(MVT::v8i16);
5349       First = false;
5350     }
5351
5352     if ((i & 1) != 0) {
5353       SDValue ThisElt, LastElt;
5354       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5355       if (LastIsNonZero) {
5356         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5357                               MVT::i16, Op.getOperand(i-1));
5358       }
5359       if (ThisIsNonZero) {
5360         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5361         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5362                               ThisElt, DAG.getConstant(8, MVT::i8));
5363         if (LastIsNonZero)
5364           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5365       } else
5366         ThisElt = LastElt;
5367
5368       if (ThisElt.getNode())
5369         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5370                         DAG.getIntPtrConstant(i/2));
5371     }
5372   }
5373
5374   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5375 }
5376
5377 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5378 ///
5379 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5380                                      unsigned NumNonZero, unsigned NumZero,
5381                                      SelectionDAG &DAG,
5382                                      const X86Subtarget* Subtarget,
5383                                      const TargetLowering &TLI) {
5384   if (NumNonZero > 4)
5385     return SDValue();
5386
5387   SDLoc dl(Op);
5388   SDValue V;
5389   bool First = true;
5390   for (unsigned i = 0; i < 8; ++i) {
5391     bool isNonZero = (NonZeros & (1 << i)) != 0;
5392     if (isNonZero) {
5393       if (First) {
5394         if (NumZero)
5395           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5396         else
5397           V = DAG.getUNDEF(MVT::v8i16);
5398         First = false;
5399       }
5400       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5401                       MVT::v8i16, V, Op.getOperand(i),
5402                       DAG.getIntPtrConstant(i));
5403     }
5404   }
5405
5406   return V;
5407 }
5408
5409 /// getVShift - Return a vector logical shift node.
5410 ///
5411 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5412                          unsigned NumBits, SelectionDAG &DAG,
5413                          const TargetLowering &TLI, SDLoc dl) {
5414   assert(VT.is128BitVector() && "Unknown type for VShift");
5415   EVT ShVT = MVT::v2i64;
5416   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5417   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5418   return DAG.getNode(ISD::BITCAST, dl, VT,
5419                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5420                              DAG.getConstant(NumBits,
5421                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5422 }
5423
5424 static SDValue
5425 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5426
5427   // Check if the scalar load can be widened into a vector load. And if
5428   // the address is "base + cst" see if the cst can be "absorbed" into
5429   // the shuffle mask.
5430   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5431     SDValue Ptr = LD->getBasePtr();
5432     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5433       return SDValue();
5434     EVT PVT = LD->getValueType(0);
5435     if (PVT != MVT::i32 && PVT != MVT::f32)
5436       return SDValue();
5437
5438     int FI = -1;
5439     int64_t Offset = 0;
5440     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5441       FI = FINode->getIndex();
5442       Offset = 0;
5443     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5444                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5445       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5446       Offset = Ptr.getConstantOperandVal(1);
5447       Ptr = Ptr.getOperand(0);
5448     } else {
5449       return SDValue();
5450     }
5451
5452     // FIXME: 256-bit vector instructions don't require a strict alignment,
5453     // improve this code to support it better.
5454     unsigned RequiredAlign = VT.getSizeInBits()/8;
5455     SDValue Chain = LD->getChain();
5456     // Make sure the stack object alignment is at least 16 or 32.
5457     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5458     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5459       if (MFI->isFixedObjectIndex(FI)) {
5460         // Can't change the alignment. FIXME: It's possible to compute
5461         // the exact stack offset and reference FI + adjust offset instead.
5462         // If someone *really* cares about this. That's the way to implement it.
5463         return SDValue();
5464       } else {
5465         MFI->setObjectAlignment(FI, RequiredAlign);
5466       }
5467     }
5468
5469     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5470     // Ptr + (Offset & ~15).
5471     if (Offset < 0)
5472       return SDValue();
5473     if ((Offset % RequiredAlign) & 3)
5474       return SDValue();
5475     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5476     if (StartOffset)
5477       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5478                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5479
5480     int EltNo = (Offset - StartOffset) >> 2;
5481     unsigned NumElems = VT.getVectorNumElements();
5482
5483     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5484     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5485                              LD->getPointerInfo().getWithOffset(StartOffset),
5486                              false, false, false, 0);
5487
5488     SmallVector<int, 8> Mask;
5489     for (unsigned i = 0; i != NumElems; ++i)
5490       Mask.push_back(EltNo);
5491
5492     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5493   }
5494
5495   return SDValue();
5496 }
5497
5498 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5499 /// vector of type 'VT', see if the elements can be replaced by a single large
5500 /// load which has the same value as a build_vector whose operands are 'elts'.
5501 ///
5502 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5503 ///
5504 /// FIXME: we'd also like to handle the case where the last elements are zero
5505 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5506 /// There's even a handy isZeroNode for that purpose.
5507 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5508                                         SDLoc &DL, SelectionDAG &DAG,
5509                                         bool isAfterLegalize) {
5510   EVT EltVT = VT.getVectorElementType();
5511   unsigned NumElems = Elts.size();
5512
5513   LoadSDNode *LDBase = nullptr;
5514   unsigned LastLoadedElt = -1U;
5515
5516   // For each element in the initializer, see if we've found a load or an undef.
5517   // If we don't find an initial load element, or later load elements are
5518   // non-consecutive, bail out.
5519   for (unsigned i = 0; i < NumElems; ++i) {
5520     SDValue Elt = Elts[i];
5521
5522     if (!Elt.getNode() ||
5523         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5524       return SDValue();
5525     if (!LDBase) {
5526       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5527         return SDValue();
5528       LDBase = cast<LoadSDNode>(Elt.getNode());
5529       LastLoadedElt = i;
5530       continue;
5531     }
5532     if (Elt.getOpcode() == ISD::UNDEF)
5533       continue;
5534
5535     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5536     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5537       return SDValue();
5538     LastLoadedElt = i;
5539   }
5540
5541   // If we have found an entire vector of loads and undefs, then return a large
5542   // load of the entire vector width starting at the base pointer.  If we found
5543   // consecutive loads for the low half, generate a vzext_load node.
5544   if (LastLoadedElt == NumElems - 1) {
5545
5546     if (isAfterLegalize &&
5547         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5548       return SDValue();
5549
5550     SDValue NewLd = SDValue();
5551
5552     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5553       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5554                           LDBase->getPointerInfo(),
5555                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5556                           LDBase->isInvariant(), 0);
5557     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5558                         LDBase->getPointerInfo(),
5559                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5560                         LDBase->isInvariant(), LDBase->getAlignment());
5561
5562     if (LDBase->hasAnyUseOfValue(1)) {
5563       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5564                                      SDValue(LDBase, 1),
5565                                      SDValue(NewLd.getNode(), 1));
5566       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5567       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5568                              SDValue(NewLd.getNode(), 1));
5569     }
5570
5571     return NewLd;
5572   }
5573   if (NumElems == 4 && LastLoadedElt == 1 &&
5574       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5575     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5576     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5577     SDValue ResNode =
5578         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5579                                 array_lengthof(Ops), MVT::i64,
5580                                 LDBase->getPointerInfo(),
5581                                 LDBase->getAlignment(),
5582                                 false/*isVolatile*/, true/*ReadMem*/,
5583                                 false/*WriteMem*/);
5584
5585     // Make sure the newly-created LOAD is in the same position as LDBase in
5586     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5587     // update uses of LDBase's output chain to use the TokenFactor.
5588     if (LDBase->hasAnyUseOfValue(1)) {
5589       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5590                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5591       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5592       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5593                              SDValue(ResNode.getNode(), 1));
5594     }
5595
5596     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5597   }
5598   return SDValue();
5599 }
5600
5601 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5602 /// to generate a splat value for the following cases:
5603 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5604 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5605 /// a scalar load, or a constant.
5606 /// The VBROADCAST node is returned when a pattern is found,
5607 /// or SDValue() otherwise.
5608 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5609                                     SelectionDAG &DAG) {
5610   if (!Subtarget->hasFp256())
5611     return SDValue();
5612
5613   MVT VT = Op.getSimpleValueType();
5614   SDLoc dl(Op);
5615
5616   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5617          "Unsupported vector type for broadcast.");
5618
5619   SDValue Ld;
5620   bool ConstSplatVal;
5621
5622   switch (Op.getOpcode()) {
5623     default:
5624       // Unknown pattern found.
5625       return SDValue();
5626
5627     case ISD::BUILD_VECTOR: {
5628       // The BUILD_VECTOR node must be a splat.
5629       if (!isSplatVector(Op.getNode()))
5630         return SDValue();
5631
5632       Ld = Op.getOperand(0);
5633       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5634                      Ld.getOpcode() == ISD::ConstantFP);
5635
5636       // The suspected load node has several users. Make sure that all
5637       // of its users are from the BUILD_VECTOR node.
5638       // Constants may have multiple users.
5639       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5640         return SDValue();
5641       break;
5642     }
5643
5644     case ISD::VECTOR_SHUFFLE: {
5645       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5646
5647       // Shuffles must have a splat mask where the first element is
5648       // broadcasted.
5649       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5650         return SDValue();
5651
5652       SDValue Sc = Op.getOperand(0);
5653       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5654           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5655
5656         if (!Subtarget->hasInt256())
5657           return SDValue();
5658
5659         // Use the register form of the broadcast instruction available on AVX2.
5660         if (VT.getSizeInBits() >= 256)
5661           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5662         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5663       }
5664
5665       Ld = Sc.getOperand(0);
5666       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5667                        Ld.getOpcode() == ISD::ConstantFP);
5668
5669       // The scalar_to_vector node and the suspected
5670       // load node must have exactly one user.
5671       // Constants may have multiple users.
5672
5673       // AVX-512 has register version of the broadcast
5674       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5675         Ld.getValueType().getSizeInBits() >= 32;
5676       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5677           !hasRegVer))
5678         return SDValue();
5679       break;
5680     }
5681   }
5682
5683   bool IsGE256 = (VT.getSizeInBits() >= 256);
5684
5685   // Handle the broadcasting a single constant scalar from the constant pool
5686   // into a vector. On Sandybridge it is still better to load a constant vector
5687   // from the constant pool and not to broadcast it from a scalar.
5688   if (ConstSplatVal && Subtarget->hasInt256()) {
5689     EVT CVT = Ld.getValueType();
5690     assert(!CVT.isVector() && "Must not broadcast a vector type");
5691     unsigned ScalarSize = CVT.getSizeInBits();
5692
5693     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5694       const Constant *C = nullptr;
5695       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5696         C = CI->getConstantIntValue();
5697       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5698         C = CF->getConstantFPValue();
5699
5700       assert(C && "Invalid constant type");
5701
5702       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5703       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5704       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5705       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5706                        MachinePointerInfo::getConstantPool(),
5707                        false, false, false, Alignment);
5708
5709       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5710     }
5711   }
5712
5713   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5714   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5715
5716   // Handle AVX2 in-register broadcasts.
5717   if (!IsLoad && Subtarget->hasInt256() &&
5718       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5719     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5720
5721   // The scalar source must be a normal load.
5722   if (!IsLoad)
5723     return SDValue();
5724
5725   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5726     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5727
5728   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5729   // double since there is no vbroadcastsd xmm
5730   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5731     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5732       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5733   }
5734
5735   // Unsupported broadcast.
5736   return SDValue();
5737 }
5738
5739 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5740 /// underlying vector and index.
5741 ///
5742 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5743 /// index.
5744 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5745                                          SDValue ExtIdx) {
5746   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5747   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5748     return Idx;
5749
5750   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5751   // lowered this:
5752   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5753   // to:
5754   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5755   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5756   //                           undef)
5757   //                       Constant<0>)
5758   // In this case the vector is the extract_subvector expression and the index
5759   // is 2, as specified by the shuffle.
5760   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5761   SDValue ShuffleVec = SVOp->getOperand(0);
5762   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5763   assert(ShuffleVecVT.getVectorElementType() ==
5764          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5765
5766   int ShuffleIdx = SVOp->getMaskElt(Idx);
5767   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5768     ExtractedFromVec = ShuffleVec;
5769     return ShuffleIdx;
5770   }
5771   return Idx;
5772 }
5773
5774 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5775   MVT VT = Op.getSimpleValueType();
5776
5777   // Skip if insert_vec_elt is not supported.
5778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5779   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5780     return SDValue();
5781
5782   SDLoc DL(Op);
5783   unsigned NumElems = Op.getNumOperands();
5784
5785   SDValue VecIn1;
5786   SDValue VecIn2;
5787   SmallVector<unsigned, 4> InsertIndices;
5788   SmallVector<int, 8> Mask(NumElems, -1);
5789
5790   for (unsigned i = 0; i != NumElems; ++i) {
5791     unsigned Opc = Op.getOperand(i).getOpcode();
5792
5793     if (Opc == ISD::UNDEF)
5794       continue;
5795
5796     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5797       // Quit if more than 1 elements need inserting.
5798       if (InsertIndices.size() > 1)
5799         return SDValue();
5800
5801       InsertIndices.push_back(i);
5802       continue;
5803     }
5804
5805     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5806     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5807     // Quit if non-constant index.
5808     if (!isa<ConstantSDNode>(ExtIdx))
5809       return SDValue();
5810     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5811
5812     // Quit if extracted from vector of different type.
5813     if (ExtractedFromVec.getValueType() != VT)
5814       return SDValue();
5815
5816     if (!VecIn1.getNode())
5817       VecIn1 = ExtractedFromVec;
5818     else if (VecIn1 != ExtractedFromVec) {
5819       if (!VecIn2.getNode())
5820         VecIn2 = ExtractedFromVec;
5821       else if (VecIn2 != ExtractedFromVec)
5822         // Quit if more than 2 vectors to shuffle
5823         return SDValue();
5824     }
5825
5826     if (ExtractedFromVec == VecIn1)
5827       Mask[i] = Idx;
5828     else if (ExtractedFromVec == VecIn2)
5829       Mask[i] = Idx + NumElems;
5830   }
5831
5832   if (!VecIn1.getNode())
5833     return SDValue();
5834
5835   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5836   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5837   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5838     unsigned Idx = InsertIndices[i];
5839     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5840                      DAG.getIntPtrConstant(Idx));
5841   }
5842
5843   return NV;
5844 }
5845
5846 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5847 SDValue
5848 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5849
5850   MVT VT = Op.getSimpleValueType();
5851   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5852          "Unexpected type in LowerBUILD_VECTORvXi1!");
5853
5854   SDLoc dl(Op);
5855   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5856     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5857     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5858                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5859     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5860                        Ops, VT.getVectorNumElements());
5861   }
5862
5863   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5864     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5865     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5866                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5867     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5868                        Ops, VT.getVectorNumElements());
5869   }
5870
5871   bool AllContants = true;
5872   uint64_t Immediate = 0;
5873   int NonConstIdx = -1;
5874   bool IsSplat = true;
5875   unsigned NumNonConsts = 0;
5876   unsigned NumConsts = 0;
5877   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5878     SDValue In = Op.getOperand(idx);
5879     if (In.getOpcode() == ISD::UNDEF)
5880       continue;
5881     if (!isa<ConstantSDNode>(In)) {
5882       AllContants = false;
5883       NonConstIdx = idx;
5884       NumNonConsts++;
5885     }
5886     else {
5887       NumConsts++;
5888       if (cast<ConstantSDNode>(In)->getZExtValue())
5889       Immediate |= (1ULL << idx);
5890     }
5891     if (In != Op.getOperand(0))
5892       IsSplat = false;
5893   }
5894
5895   if (AllContants) {
5896     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5897       DAG.getConstant(Immediate, MVT::i16));
5898     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5899                        DAG.getIntPtrConstant(0));
5900   }
5901
5902   if (NumNonConsts == 1 && NonConstIdx != 0) {
5903     SDValue DstVec;
5904     if (NumConsts) {
5905       SDValue VecAsImm = DAG.getConstant(Immediate,
5906                                          MVT::getIntegerVT(VT.getSizeInBits()));
5907       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5908     }
5909     else 
5910       DstVec = DAG.getUNDEF(VT);
5911     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5912                        Op.getOperand(NonConstIdx),
5913                        DAG.getIntPtrConstant(NonConstIdx));
5914   }
5915   if (!IsSplat && (NonConstIdx != 0))
5916     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5917   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5918   SDValue Select;
5919   if (IsSplat)
5920     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5921                           DAG.getConstant(-1, SelectVT),
5922                           DAG.getConstant(0, SelectVT));
5923   else
5924     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5925                          DAG.getConstant((Immediate | 1), SelectVT),
5926                          DAG.getConstant(Immediate, SelectVT));
5927   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5928 }
5929
5930 SDValue
5931 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5932   SDLoc dl(Op);
5933
5934   MVT VT = Op.getSimpleValueType();
5935   MVT ExtVT = VT.getVectorElementType();
5936   unsigned NumElems = Op.getNumOperands();
5937
5938   // Generate vectors for predicate vectors.
5939   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5940     return LowerBUILD_VECTORvXi1(Op, DAG);
5941
5942   // Vectors containing all zeros can be matched by pxor and xorps later
5943   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5944     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5945     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5946     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5947       return Op;
5948
5949     return getZeroVector(VT, Subtarget, DAG, dl);
5950   }
5951
5952   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5953   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5954   // vpcmpeqd on 256-bit vectors.
5955   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5956     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5957       return Op;
5958
5959     if (!VT.is512BitVector())
5960       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5961   }
5962
5963   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5964   if (Broadcast.getNode())
5965     return Broadcast;
5966
5967   unsigned EVTBits = ExtVT.getSizeInBits();
5968
5969   unsigned NumZero  = 0;
5970   unsigned NumNonZero = 0;
5971   unsigned NonZeros = 0;
5972   bool IsAllConstants = true;
5973   SmallSet<SDValue, 8> Values;
5974   for (unsigned i = 0; i < NumElems; ++i) {
5975     SDValue Elt = Op.getOperand(i);
5976     if (Elt.getOpcode() == ISD::UNDEF)
5977       continue;
5978     Values.insert(Elt);
5979     if (Elt.getOpcode() != ISD::Constant &&
5980         Elt.getOpcode() != ISD::ConstantFP)
5981       IsAllConstants = false;
5982     if (X86::isZeroNode(Elt))
5983       NumZero++;
5984     else {
5985       NonZeros |= (1 << i);
5986       NumNonZero++;
5987     }
5988   }
5989
5990   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5991   if (NumNonZero == 0)
5992     return DAG.getUNDEF(VT);
5993
5994   // Special case for single non-zero, non-undef, element.
5995   if (NumNonZero == 1) {
5996     unsigned Idx = countTrailingZeros(NonZeros);
5997     SDValue Item = Op.getOperand(Idx);
5998
5999     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6000     // the value are obviously zero, truncate the value to i32 and do the
6001     // insertion that way.  Only do this if the value is non-constant or if the
6002     // value is a constant being inserted into element 0.  It is cheaper to do
6003     // a constant pool load than it is to do a movd + shuffle.
6004     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6005         (!IsAllConstants || Idx == 0)) {
6006       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6007         // Handle SSE only.
6008         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6009         EVT VecVT = MVT::v4i32;
6010         unsigned VecElts = 4;
6011
6012         // Truncate the value (which may itself be a constant) to i32, and
6013         // convert it to a vector with movd (S2V+shuffle to zero extend).
6014         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6015         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6016         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6017
6018         // Now we have our 32-bit value zero extended in the low element of
6019         // a vector.  If Idx != 0, swizzle it into place.
6020         if (Idx != 0) {
6021           SmallVector<int, 4> Mask;
6022           Mask.push_back(Idx);
6023           for (unsigned i = 1; i != VecElts; ++i)
6024             Mask.push_back(i);
6025           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6026                                       &Mask[0]);
6027         }
6028         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6029       }
6030     }
6031
6032     // If we have a constant or non-constant insertion into the low element of
6033     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6034     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6035     // depending on what the source datatype is.
6036     if (Idx == 0) {
6037       if (NumZero == 0)
6038         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6039
6040       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6041           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6042         if (VT.is256BitVector() || VT.is512BitVector()) {
6043           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6044           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6045                              Item, DAG.getIntPtrConstant(0));
6046         }
6047         assert(VT.is128BitVector() && "Expected an SSE value type!");
6048         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6049         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6050         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6051       }
6052
6053       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6054         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6055         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6056         if (VT.is256BitVector()) {
6057           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6058           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6059         } else {
6060           assert(VT.is128BitVector() && "Expected an SSE value type!");
6061           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6062         }
6063         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6064       }
6065     }
6066
6067     // Is it a vector logical left shift?
6068     if (NumElems == 2 && Idx == 1 &&
6069         X86::isZeroNode(Op.getOperand(0)) &&
6070         !X86::isZeroNode(Op.getOperand(1))) {
6071       unsigned NumBits = VT.getSizeInBits();
6072       return getVShift(true, VT,
6073                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6074                                    VT, Op.getOperand(1)),
6075                        NumBits/2, DAG, *this, dl);
6076     }
6077
6078     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6079       return SDValue();
6080
6081     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6082     // is a non-constant being inserted into an element other than the low one,
6083     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6084     // movd/movss) to move this into the low element, then shuffle it into
6085     // place.
6086     if (EVTBits == 32) {
6087       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6088
6089       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6090       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6091       SmallVector<int, 8> MaskVec;
6092       for (unsigned i = 0; i != NumElems; ++i)
6093         MaskVec.push_back(i == Idx ? 0 : 1);
6094       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6095     }
6096   }
6097
6098   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6099   if (Values.size() == 1) {
6100     if (EVTBits == 32) {
6101       // Instead of a shuffle like this:
6102       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6103       // Check if it's possible to issue this instead.
6104       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6105       unsigned Idx = countTrailingZeros(NonZeros);
6106       SDValue Item = Op.getOperand(Idx);
6107       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6108         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6109     }
6110     return SDValue();
6111   }
6112
6113   // A vector full of immediates; various special cases are already
6114   // handled, so this is best done with a single constant-pool load.
6115   if (IsAllConstants)
6116     return SDValue();
6117
6118   // For AVX-length vectors, build the individual 128-bit pieces and use
6119   // shuffles to put them in place.
6120   if (VT.is256BitVector() || VT.is512BitVector()) {
6121     SmallVector<SDValue, 64> V;
6122     for (unsigned i = 0; i != NumElems; ++i)
6123       V.push_back(Op.getOperand(i));
6124
6125     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6126
6127     // Build both the lower and upper subvector.
6128     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6129     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6130                                 NumElems/2);
6131
6132     // Recreate the wider vector with the lower and upper part.
6133     if (VT.is256BitVector())
6134       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6135     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6136   }
6137
6138   // Let legalizer expand 2-wide build_vectors.
6139   if (EVTBits == 64) {
6140     if (NumNonZero == 1) {
6141       // One half is zero or undef.
6142       unsigned Idx = countTrailingZeros(NonZeros);
6143       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6144                                  Op.getOperand(Idx));
6145       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6146     }
6147     return SDValue();
6148   }
6149
6150   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6151   if (EVTBits == 8 && NumElems == 16) {
6152     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6153                                         Subtarget, *this);
6154     if (V.getNode()) return V;
6155   }
6156
6157   if (EVTBits == 16 && NumElems == 8) {
6158     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6159                                       Subtarget, *this);
6160     if (V.getNode()) return V;
6161   }
6162
6163   // If element VT is == 32 bits, turn it into a number of shuffles.
6164   SmallVector<SDValue, 8> V(NumElems);
6165   if (NumElems == 4 && NumZero > 0) {
6166     for (unsigned i = 0; i < 4; ++i) {
6167       bool isZero = !(NonZeros & (1 << i));
6168       if (isZero)
6169         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6170       else
6171         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6172     }
6173
6174     for (unsigned i = 0; i < 2; ++i) {
6175       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6176         default: break;
6177         case 0:
6178           V[i] = V[i*2];  // Must be a zero vector.
6179           break;
6180         case 1:
6181           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6182           break;
6183         case 2:
6184           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6185           break;
6186         case 3:
6187           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6188           break;
6189       }
6190     }
6191
6192     bool Reverse1 = (NonZeros & 0x3) == 2;
6193     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6194     int MaskVec[] = {
6195       Reverse1 ? 1 : 0,
6196       Reverse1 ? 0 : 1,
6197       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6198       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6199     };
6200     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6201   }
6202
6203   if (Values.size() > 1 && VT.is128BitVector()) {
6204     // Check for a build vector of consecutive loads.
6205     for (unsigned i = 0; i < NumElems; ++i)
6206       V[i] = Op.getOperand(i);
6207
6208     // Check for elements which are consecutive loads.
6209     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6210     if (LD.getNode())
6211       return LD;
6212
6213     // Check for a build vector from mostly shuffle plus few inserting.
6214     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6215     if (Sh.getNode())
6216       return Sh;
6217
6218     // For SSE 4.1, use insertps to put the high elements into the low element.
6219     if (getSubtarget()->hasSSE41()) {
6220       SDValue Result;
6221       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6222         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6223       else
6224         Result = DAG.getUNDEF(VT);
6225
6226       for (unsigned i = 1; i < NumElems; ++i) {
6227         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6228         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6229                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6230       }
6231       return Result;
6232     }
6233
6234     // Otherwise, expand into a number of unpckl*, start by extending each of
6235     // our (non-undef) elements to the full vector width with the element in the
6236     // bottom slot of the vector (which generates no code for SSE).
6237     for (unsigned i = 0; i < NumElems; ++i) {
6238       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6239         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6240       else
6241         V[i] = DAG.getUNDEF(VT);
6242     }
6243
6244     // Next, we iteratively mix elements, e.g. for v4f32:
6245     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6246     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6247     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6248     unsigned EltStride = NumElems >> 1;
6249     while (EltStride != 0) {
6250       for (unsigned i = 0; i < EltStride; ++i) {
6251         // If V[i+EltStride] is undef and this is the first round of mixing,
6252         // then it is safe to just drop this shuffle: V[i] is already in the
6253         // right place, the one element (since it's the first round) being
6254         // inserted as undef can be dropped.  This isn't safe for successive
6255         // rounds because they will permute elements within both vectors.
6256         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6257             EltStride == NumElems/2)
6258           continue;
6259
6260         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6261       }
6262       EltStride >>= 1;
6263     }
6264     return V[0];
6265   }
6266   return SDValue();
6267 }
6268
6269 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6270 // to create 256-bit vectors from two other 128-bit ones.
6271 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6272   SDLoc dl(Op);
6273   MVT ResVT = Op.getSimpleValueType();
6274
6275   assert((ResVT.is256BitVector() ||
6276           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6277
6278   SDValue V1 = Op.getOperand(0);
6279   SDValue V2 = Op.getOperand(1);
6280   unsigned NumElems = ResVT.getVectorNumElements();
6281   if(ResVT.is256BitVector())
6282     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6283
6284   if (Op.getNumOperands() == 4) {
6285     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6286                                 ResVT.getVectorNumElements()/2);
6287     SDValue V3 = Op.getOperand(2);
6288     SDValue V4 = Op.getOperand(3);
6289     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6290       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6291   }
6292   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6293 }
6294
6295 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6296   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6297   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6298          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6299           Op.getNumOperands() == 4)));
6300
6301   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6302   // from two other 128-bit ones.
6303
6304   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6305   return LowerAVXCONCAT_VECTORS(Op, DAG);
6306 }
6307
6308 // Try to lower a shuffle node into a simple blend instruction.
6309 static SDValue
6310 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6311                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6312   SDValue V1 = SVOp->getOperand(0);
6313   SDValue V2 = SVOp->getOperand(1);
6314   SDLoc dl(SVOp);
6315   MVT VT = SVOp->getSimpleValueType(0);
6316   MVT EltVT = VT.getVectorElementType();
6317   unsigned NumElems = VT.getVectorNumElements();
6318
6319   // There is no blend with immediate in AVX-512.
6320   if (VT.is512BitVector())
6321     return SDValue();
6322
6323   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6324     return SDValue();
6325   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6326     return SDValue();
6327
6328   // Check the mask for BLEND and build the value.
6329   unsigned MaskValue = 0;
6330   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6331   unsigned NumLanes = (NumElems-1)/8 + 1;
6332   unsigned NumElemsInLane = NumElems / NumLanes;
6333
6334   // Blend for v16i16 should be symetric for the both lanes.
6335   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6336
6337     int SndLaneEltIdx = (NumLanes == 2) ?
6338       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6339     int EltIdx = SVOp->getMaskElt(i);
6340
6341     if ((EltIdx < 0 || EltIdx == (int)i) &&
6342         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6343       continue;
6344
6345     if (((unsigned)EltIdx == (i + NumElems)) &&
6346         (SndLaneEltIdx < 0 ||
6347          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6348       MaskValue |= (1<<i);
6349     else
6350       return SDValue();
6351   }
6352
6353   // Convert i32 vectors to floating point if it is not AVX2.
6354   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6355   MVT BlendVT = VT;
6356   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6357     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6358                                NumElems);
6359     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6360     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6361   }
6362
6363   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6364                             DAG.getConstant(MaskValue, MVT::i32));
6365   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6366 }
6367
6368 /// In vector type \p VT, return true if the element at index \p InputIdx
6369 /// falls on a different 128-bit lane than \p OutputIdx.
6370 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6371                                      unsigned OutputIdx) {
6372   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6373   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6374 }
6375
6376 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6377 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6378 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6379 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6380 /// zero.
6381 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6382                          SelectionDAG &DAG) {
6383   MVT VT = V1.getSimpleValueType();
6384   assert(VT.is128BitVector() || VT.is256BitVector());
6385
6386   MVT EltVT = VT.getVectorElementType();
6387   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6388   unsigned NumElts = VT.getVectorNumElements();
6389
6390   SmallVector<SDValue, 32> PshufbMask;
6391   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6392     int InputIdx = MaskVals[OutputIdx];
6393     unsigned InputByteIdx;
6394
6395     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6396       InputByteIdx = 0x80;
6397     else {
6398       // Cross lane is not allowed.
6399       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6400         return SDValue();
6401       InputByteIdx = InputIdx * EltSizeInBytes;
6402       // Index is an byte offset within the 128-bit lane.
6403       InputByteIdx &= 0xf;
6404     }
6405
6406     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6407       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6408       if (InputByteIdx != 0x80)
6409         ++InputByteIdx;
6410     }
6411   }
6412
6413   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6414   if (ShufVT != VT)
6415     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6416   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6417                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6418                                  PshufbMask.data(), PshufbMask.size()));
6419 }
6420
6421 // v8i16 shuffles - Prefer shuffles in the following order:
6422 // 1. [all]   pshuflw, pshufhw, optional move
6423 // 2. [ssse3] 1 x pshufb
6424 // 3. [ssse3] 2 x pshufb + 1 x por
6425 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6426 static SDValue
6427 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6428                          SelectionDAG &DAG) {
6429   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6430   SDValue V1 = SVOp->getOperand(0);
6431   SDValue V2 = SVOp->getOperand(1);
6432   SDLoc dl(SVOp);
6433   SmallVector<int, 8> MaskVals;
6434
6435   // Determine if more than 1 of the words in each of the low and high quadwords
6436   // of the result come from the same quadword of one of the two inputs.  Undef
6437   // mask values count as coming from any quadword, for better codegen.
6438   //
6439   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6440   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6441   unsigned LoQuad[] = { 0, 0, 0, 0 };
6442   unsigned HiQuad[] = { 0, 0, 0, 0 };
6443   // Indices of quads used.
6444   std::bitset<4> InputQuads;
6445   for (unsigned i = 0; i < 8; ++i) {
6446     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6447     int EltIdx = SVOp->getMaskElt(i);
6448     MaskVals.push_back(EltIdx);
6449     if (EltIdx < 0) {
6450       ++Quad[0];
6451       ++Quad[1];
6452       ++Quad[2];
6453       ++Quad[3];
6454       continue;
6455     }
6456     ++Quad[EltIdx / 4];
6457     InputQuads.set(EltIdx / 4);
6458   }
6459
6460   int BestLoQuad = -1;
6461   unsigned MaxQuad = 1;
6462   for (unsigned i = 0; i < 4; ++i) {
6463     if (LoQuad[i] > MaxQuad) {
6464       BestLoQuad = i;
6465       MaxQuad = LoQuad[i];
6466     }
6467   }
6468
6469   int BestHiQuad = -1;
6470   MaxQuad = 1;
6471   for (unsigned i = 0; i < 4; ++i) {
6472     if (HiQuad[i] > MaxQuad) {
6473       BestHiQuad = i;
6474       MaxQuad = HiQuad[i];
6475     }
6476   }
6477
6478   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6479   // of the two input vectors, shuffle them into one input vector so only a
6480   // single pshufb instruction is necessary. If there are more than 2 input
6481   // quads, disable the next transformation since it does not help SSSE3.
6482   bool V1Used = InputQuads[0] || InputQuads[1];
6483   bool V2Used = InputQuads[2] || InputQuads[3];
6484   if (Subtarget->hasSSSE3()) {
6485     if (InputQuads.count() == 2 && V1Used && V2Used) {
6486       BestLoQuad = InputQuads[0] ? 0 : 1;
6487       BestHiQuad = InputQuads[2] ? 2 : 3;
6488     }
6489     if (InputQuads.count() > 2) {
6490       BestLoQuad = -1;
6491       BestHiQuad = -1;
6492     }
6493   }
6494
6495   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6496   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6497   // words from all 4 input quadwords.
6498   SDValue NewV;
6499   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6500     int MaskV[] = {
6501       BestLoQuad < 0 ? 0 : BestLoQuad,
6502       BestHiQuad < 0 ? 1 : BestHiQuad
6503     };
6504     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6505                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6506                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6507     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6508
6509     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6510     // source words for the shuffle, to aid later transformations.
6511     bool AllWordsInNewV = true;
6512     bool InOrder[2] = { true, true };
6513     for (unsigned i = 0; i != 8; ++i) {
6514       int idx = MaskVals[i];
6515       if (idx != (int)i)
6516         InOrder[i/4] = false;
6517       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6518         continue;
6519       AllWordsInNewV = false;
6520       break;
6521     }
6522
6523     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6524     if (AllWordsInNewV) {
6525       for (int i = 0; i != 8; ++i) {
6526         int idx = MaskVals[i];
6527         if (idx < 0)
6528           continue;
6529         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6530         if ((idx != i) && idx < 4)
6531           pshufhw = false;
6532         if ((idx != i) && idx > 3)
6533           pshuflw = false;
6534       }
6535       V1 = NewV;
6536       V2Used = false;
6537       BestLoQuad = 0;
6538       BestHiQuad = 1;
6539     }
6540
6541     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6542     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6543     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6544       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6545       unsigned TargetMask = 0;
6546       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6547                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6548       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6549       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6550                              getShufflePSHUFLWImmediate(SVOp);
6551       V1 = NewV.getOperand(0);
6552       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6553     }
6554   }
6555
6556   // Promote splats to a larger type which usually leads to more efficient code.
6557   // FIXME: Is this true if pshufb is available?
6558   if (SVOp->isSplat())
6559     return PromoteSplat(SVOp, DAG);
6560
6561   // If we have SSSE3, and all words of the result are from 1 input vector,
6562   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6563   // is present, fall back to case 4.
6564   if (Subtarget->hasSSSE3()) {
6565     SmallVector<SDValue,16> pshufbMask;
6566
6567     // If we have elements from both input vectors, set the high bit of the
6568     // shuffle mask element to zero out elements that come from V2 in the V1
6569     // mask, and elements that come from V1 in the V2 mask, so that the two
6570     // results can be OR'd together.
6571     bool TwoInputs = V1Used && V2Used;
6572     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6573     if (!TwoInputs)
6574       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6575
6576     // Calculate the shuffle mask for the second input, shuffle it, and
6577     // OR it with the first shuffled input.
6578     CommuteVectorShuffleMask(MaskVals, 8);
6579     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6580     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6581     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6582   }
6583
6584   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6585   // and update MaskVals with new element order.
6586   std::bitset<8> InOrder;
6587   if (BestLoQuad >= 0) {
6588     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6589     for (int i = 0; i != 4; ++i) {
6590       int idx = MaskVals[i];
6591       if (idx < 0) {
6592         InOrder.set(i);
6593       } else if ((idx / 4) == BestLoQuad) {
6594         MaskV[i] = idx & 3;
6595         InOrder.set(i);
6596       }
6597     }
6598     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6599                                 &MaskV[0]);
6600
6601     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6602       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6603       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6604                                   NewV.getOperand(0),
6605                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6606     }
6607   }
6608
6609   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6610   // and update MaskVals with the new element order.
6611   if (BestHiQuad >= 0) {
6612     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6613     for (unsigned i = 4; i != 8; ++i) {
6614       int idx = MaskVals[i];
6615       if (idx < 0) {
6616         InOrder.set(i);
6617       } else if ((idx / 4) == BestHiQuad) {
6618         MaskV[i] = (idx & 3) + 4;
6619         InOrder.set(i);
6620       }
6621     }
6622     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6623                                 &MaskV[0]);
6624
6625     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6626       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6627       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6628                                   NewV.getOperand(0),
6629                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6630     }
6631   }
6632
6633   // In case BestHi & BestLo were both -1, which means each quadword has a word
6634   // from each of the four input quadwords, calculate the InOrder bitvector now
6635   // before falling through to the insert/extract cleanup.
6636   if (BestLoQuad == -1 && BestHiQuad == -1) {
6637     NewV = V1;
6638     for (int i = 0; i != 8; ++i)
6639       if (MaskVals[i] < 0 || MaskVals[i] == i)
6640         InOrder.set(i);
6641   }
6642
6643   // The other elements are put in the right place using pextrw and pinsrw.
6644   for (unsigned i = 0; i != 8; ++i) {
6645     if (InOrder[i])
6646       continue;
6647     int EltIdx = MaskVals[i];
6648     if (EltIdx < 0)
6649       continue;
6650     SDValue ExtOp = (EltIdx < 8) ?
6651       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6652                   DAG.getIntPtrConstant(EltIdx)) :
6653       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6654                   DAG.getIntPtrConstant(EltIdx - 8));
6655     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6656                        DAG.getIntPtrConstant(i));
6657   }
6658   return NewV;
6659 }
6660
6661 /// \brief v16i16 shuffles
6662 ///
6663 /// FIXME: We only support generation of a single pshufb currently.  We can
6664 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6665 /// well (e.g 2 x pshufb + 1 x por).
6666 static SDValue
6667 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6668   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6669   SDValue V1 = SVOp->getOperand(0);
6670   SDValue V2 = SVOp->getOperand(1);
6671   SDLoc dl(SVOp);
6672
6673   if (V2.getOpcode() != ISD::UNDEF)
6674     return SDValue();
6675
6676   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6677   return getPSHUFB(MaskVals, V1, dl, DAG);
6678 }
6679
6680 // v16i8 shuffles - Prefer shuffles in the following order:
6681 // 1. [ssse3] 1 x pshufb
6682 // 2. [ssse3] 2 x pshufb + 1 x por
6683 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6684 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6685                                         const X86Subtarget* Subtarget,
6686                                         SelectionDAG &DAG) {
6687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6688   SDValue V1 = SVOp->getOperand(0);
6689   SDValue V2 = SVOp->getOperand(1);
6690   SDLoc dl(SVOp);
6691   ArrayRef<int> MaskVals = SVOp->getMask();
6692
6693   // Promote splats to a larger type which usually leads to more efficient code.
6694   // FIXME: Is this true if pshufb is available?
6695   if (SVOp->isSplat())
6696     return PromoteSplat(SVOp, DAG);
6697
6698   // If we have SSSE3, case 1 is generated when all result bytes come from
6699   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6700   // present, fall back to case 3.
6701
6702   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6703   if (Subtarget->hasSSSE3()) {
6704     SmallVector<SDValue,16> pshufbMask;
6705
6706     // If all result elements are from one input vector, then only translate
6707     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6708     //
6709     // Otherwise, we have elements from both input vectors, and must zero out
6710     // elements that come from V2 in the first mask, and V1 in the second mask
6711     // so that we can OR them together.
6712     for (unsigned i = 0; i != 16; ++i) {
6713       int EltIdx = MaskVals[i];
6714       if (EltIdx < 0 || EltIdx >= 16)
6715         EltIdx = 0x80;
6716       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6717     }
6718     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6719                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6720                                  MVT::v16i8, &pshufbMask[0], 16));
6721
6722     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6723     // the 2nd operand if it's undefined or zero.
6724     if (V2.getOpcode() == ISD::UNDEF ||
6725         ISD::isBuildVectorAllZeros(V2.getNode()))
6726       return V1;
6727
6728     // Calculate the shuffle mask for the second input, shuffle it, and
6729     // OR it with the first shuffled input.
6730     pshufbMask.clear();
6731     for (unsigned i = 0; i != 16; ++i) {
6732       int EltIdx = MaskVals[i];
6733       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6734       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6735     }
6736     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6737                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6738                                  MVT::v16i8, &pshufbMask[0], 16));
6739     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6740   }
6741
6742   // No SSSE3 - Calculate in place words and then fix all out of place words
6743   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6744   // the 16 different words that comprise the two doublequadword input vectors.
6745   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6746   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6747   SDValue NewV = V1;
6748   for (int i = 0; i != 8; ++i) {
6749     int Elt0 = MaskVals[i*2];
6750     int Elt1 = MaskVals[i*2+1];
6751
6752     // This word of the result is all undef, skip it.
6753     if (Elt0 < 0 && Elt1 < 0)
6754       continue;
6755
6756     // This word of the result is already in the correct place, skip it.
6757     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6758       continue;
6759
6760     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6761     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6762     SDValue InsElt;
6763
6764     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6765     // using a single extract together, load it and store it.
6766     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6767       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6768                            DAG.getIntPtrConstant(Elt1 / 2));
6769       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6770                         DAG.getIntPtrConstant(i));
6771       continue;
6772     }
6773
6774     // If Elt1 is defined, extract it from the appropriate source.  If the
6775     // source byte is not also odd, shift the extracted word left 8 bits
6776     // otherwise clear the bottom 8 bits if we need to do an or.
6777     if (Elt1 >= 0) {
6778       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6779                            DAG.getIntPtrConstant(Elt1 / 2));
6780       if ((Elt1 & 1) == 0)
6781         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6782                              DAG.getConstant(8,
6783                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6784       else if (Elt0 >= 0)
6785         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6786                              DAG.getConstant(0xFF00, MVT::i16));
6787     }
6788     // If Elt0 is defined, extract it from the appropriate source.  If the
6789     // source byte is not also even, shift the extracted word right 8 bits. If
6790     // Elt1 was also defined, OR the extracted values together before
6791     // inserting them in the result.
6792     if (Elt0 >= 0) {
6793       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6794                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6795       if ((Elt0 & 1) != 0)
6796         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6797                               DAG.getConstant(8,
6798                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6799       else if (Elt1 >= 0)
6800         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6801                              DAG.getConstant(0x00FF, MVT::i16));
6802       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6803                          : InsElt0;
6804     }
6805     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6806                        DAG.getIntPtrConstant(i));
6807   }
6808   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6809 }
6810
6811 // v32i8 shuffles - Translate to VPSHUFB if possible.
6812 static
6813 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6814                                  const X86Subtarget *Subtarget,
6815                                  SelectionDAG &DAG) {
6816   MVT VT = SVOp->getSimpleValueType(0);
6817   SDValue V1 = SVOp->getOperand(0);
6818   SDValue V2 = SVOp->getOperand(1);
6819   SDLoc dl(SVOp);
6820   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6821
6822   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6823   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6824   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6825
6826   // VPSHUFB may be generated if
6827   // (1) one of input vector is undefined or zeroinitializer.
6828   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6829   // And (2) the mask indexes don't cross the 128-bit lane.
6830   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6831       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6832     return SDValue();
6833
6834   if (V1IsAllZero && !V2IsAllZero) {
6835     CommuteVectorShuffleMask(MaskVals, 32);
6836     V1 = V2;
6837   }
6838   return getPSHUFB(MaskVals, V1, dl, DAG);
6839 }
6840
6841 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6842 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6843 /// done when every pair / quad of shuffle mask elements point to elements in
6844 /// the right sequence. e.g.
6845 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6846 static
6847 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6848                                  SelectionDAG &DAG) {
6849   MVT VT = SVOp->getSimpleValueType(0);
6850   SDLoc dl(SVOp);
6851   unsigned NumElems = VT.getVectorNumElements();
6852   MVT NewVT;
6853   unsigned Scale;
6854   switch (VT.SimpleTy) {
6855   default: llvm_unreachable("Unexpected!");
6856   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6857   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6858   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6859   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6860   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6861   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6862   }
6863
6864   SmallVector<int, 8> MaskVec;
6865   for (unsigned i = 0; i != NumElems; i += Scale) {
6866     int StartIdx = -1;
6867     for (unsigned j = 0; j != Scale; ++j) {
6868       int EltIdx = SVOp->getMaskElt(i+j);
6869       if (EltIdx < 0)
6870         continue;
6871       if (StartIdx < 0)
6872         StartIdx = (EltIdx / Scale);
6873       if (EltIdx != (int)(StartIdx*Scale + j))
6874         return SDValue();
6875     }
6876     MaskVec.push_back(StartIdx);
6877   }
6878
6879   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6880   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6881   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6882 }
6883
6884 /// getVZextMovL - Return a zero-extending vector move low node.
6885 ///
6886 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6887                             SDValue SrcOp, SelectionDAG &DAG,
6888                             const X86Subtarget *Subtarget, SDLoc dl) {
6889   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6890     LoadSDNode *LD = nullptr;
6891     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6892       LD = dyn_cast<LoadSDNode>(SrcOp);
6893     if (!LD) {
6894       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6895       // instead.
6896       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6897       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6898           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6899           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6900           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6901         // PR2108
6902         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6903         return DAG.getNode(ISD::BITCAST, dl, VT,
6904                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6905                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6906                                                    OpVT,
6907                                                    SrcOp.getOperand(0)
6908                                                           .getOperand(0))));
6909       }
6910     }
6911   }
6912
6913   return DAG.getNode(ISD::BITCAST, dl, VT,
6914                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6915                                  DAG.getNode(ISD::BITCAST, dl,
6916                                              OpVT, SrcOp)));
6917 }
6918
6919 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6920 /// which could not be matched by any known target speficic shuffle
6921 static SDValue
6922 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6923
6924   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6925   if (NewOp.getNode())
6926     return NewOp;
6927
6928   MVT VT = SVOp->getSimpleValueType(0);
6929
6930   unsigned NumElems = VT.getVectorNumElements();
6931   unsigned NumLaneElems = NumElems / 2;
6932
6933   SDLoc dl(SVOp);
6934   MVT EltVT = VT.getVectorElementType();
6935   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6936   SDValue Output[2];
6937
6938   SmallVector<int, 16> Mask;
6939   for (unsigned l = 0; l < 2; ++l) {
6940     // Build a shuffle mask for the output, discovering on the fly which
6941     // input vectors to use as shuffle operands (recorded in InputUsed).
6942     // If building a suitable shuffle vector proves too hard, then bail
6943     // out with UseBuildVector set.
6944     bool UseBuildVector = false;
6945     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6946     unsigned LaneStart = l * NumLaneElems;
6947     for (unsigned i = 0; i != NumLaneElems; ++i) {
6948       // The mask element.  This indexes into the input.
6949       int Idx = SVOp->getMaskElt(i+LaneStart);
6950       if (Idx < 0) {
6951         // the mask element does not index into any input vector.
6952         Mask.push_back(-1);
6953         continue;
6954       }
6955
6956       // The input vector this mask element indexes into.
6957       int Input = Idx / NumLaneElems;
6958
6959       // Turn the index into an offset from the start of the input vector.
6960       Idx -= Input * NumLaneElems;
6961
6962       // Find or create a shuffle vector operand to hold this input.
6963       unsigned OpNo;
6964       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6965         if (InputUsed[OpNo] == Input)
6966           // This input vector is already an operand.
6967           break;
6968         if (InputUsed[OpNo] < 0) {
6969           // Create a new operand for this input vector.
6970           InputUsed[OpNo] = Input;
6971           break;
6972         }
6973       }
6974
6975       if (OpNo >= array_lengthof(InputUsed)) {
6976         // More than two input vectors used!  Give up on trying to create a
6977         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6978         UseBuildVector = true;
6979         break;
6980       }
6981
6982       // Add the mask index for the new shuffle vector.
6983       Mask.push_back(Idx + OpNo * NumLaneElems);
6984     }
6985
6986     if (UseBuildVector) {
6987       SmallVector<SDValue, 16> SVOps;
6988       for (unsigned i = 0; i != NumLaneElems; ++i) {
6989         // The mask element.  This indexes into the input.
6990         int Idx = SVOp->getMaskElt(i+LaneStart);
6991         if (Idx < 0) {
6992           SVOps.push_back(DAG.getUNDEF(EltVT));
6993           continue;
6994         }
6995
6996         // The input vector this mask element indexes into.
6997         int Input = Idx / NumElems;
6998
6999         // Turn the index into an offset from the start of the input vector.
7000         Idx -= Input * NumElems;
7001
7002         // Extract the vector element by hand.
7003         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7004                                     SVOp->getOperand(Input),
7005                                     DAG.getIntPtrConstant(Idx)));
7006       }
7007
7008       // Construct the output using a BUILD_VECTOR.
7009       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
7010                               SVOps.size());
7011     } else if (InputUsed[0] < 0) {
7012       // No input vectors were used! The result is undefined.
7013       Output[l] = DAG.getUNDEF(NVT);
7014     } else {
7015       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7016                                         (InputUsed[0] % 2) * NumLaneElems,
7017                                         DAG, dl);
7018       // If only one input was used, use an undefined vector for the other.
7019       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7020         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7021                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7022       // At least one input vector was used. Create a new shuffle vector.
7023       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7024     }
7025
7026     Mask.clear();
7027   }
7028
7029   // Concatenate the result back
7030   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7031 }
7032
7033 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7034 /// 4 elements, and match them with several different shuffle types.
7035 static SDValue
7036 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7037   SDValue V1 = SVOp->getOperand(0);
7038   SDValue V2 = SVOp->getOperand(1);
7039   SDLoc dl(SVOp);
7040   MVT VT = SVOp->getSimpleValueType(0);
7041
7042   assert(VT.is128BitVector() && "Unsupported vector size");
7043
7044   std::pair<int, int> Locs[4];
7045   int Mask1[] = { -1, -1, -1, -1 };
7046   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7047
7048   unsigned NumHi = 0;
7049   unsigned NumLo = 0;
7050   for (unsigned i = 0; i != 4; ++i) {
7051     int Idx = PermMask[i];
7052     if (Idx < 0) {
7053       Locs[i] = std::make_pair(-1, -1);
7054     } else {
7055       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7056       if (Idx < 4) {
7057         Locs[i] = std::make_pair(0, NumLo);
7058         Mask1[NumLo] = Idx;
7059         NumLo++;
7060       } else {
7061         Locs[i] = std::make_pair(1, NumHi);
7062         if (2+NumHi < 4)
7063           Mask1[2+NumHi] = Idx;
7064         NumHi++;
7065       }
7066     }
7067   }
7068
7069   if (NumLo <= 2 && NumHi <= 2) {
7070     // If no more than two elements come from either vector. This can be
7071     // implemented with two shuffles. First shuffle gather the elements.
7072     // The second shuffle, which takes the first shuffle as both of its
7073     // vector operands, put the elements into the right order.
7074     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7075
7076     int Mask2[] = { -1, -1, -1, -1 };
7077
7078     for (unsigned i = 0; i != 4; ++i)
7079       if (Locs[i].first != -1) {
7080         unsigned Idx = (i < 2) ? 0 : 4;
7081         Idx += Locs[i].first * 2 + Locs[i].second;
7082         Mask2[i] = Idx;
7083       }
7084
7085     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7086   }
7087
7088   if (NumLo == 3 || NumHi == 3) {
7089     // Otherwise, we must have three elements from one vector, call it X, and
7090     // one element from the other, call it Y.  First, use a shufps to build an
7091     // intermediate vector with the one element from Y and the element from X
7092     // that will be in the same half in the final destination (the indexes don't
7093     // matter). Then, use a shufps to build the final vector, taking the half
7094     // containing the element from Y from the intermediate, and the other half
7095     // from X.
7096     if (NumHi == 3) {
7097       // Normalize it so the 3 elements come from V1.
7098       CommuteVectorShuffleMask(PermMask, 4);
7099       std::swap(V1, V2);
7100     }
7101
7102     // Find the element from V2.
7103     unsigned HiIndex;
7104     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7105       int Val = PermMask[HiIndex];
7106       if (Val < 0)
7107         continue;
7108       if (Val >= 4)
7109         break;
7110     }
7111
7112     Mask1[0] = PermMask[HiIndex];
7113     Mask1[1] = -1;
7114     Mask1[2] = PermMask[HiIndex^1];
7115     Mask1[3] = -1;
7116     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7117
7118     if (HiIndex >= 2) {
7119       Mask1[0] = PermMask[0];
7120       Mask1[1] = PermMask[1];
7121       Mask1[2] = HiIndex & 1 ? 6 : 4;
7122       Mask1[3] = HiIndex & 1 ? 4 : 6;
7123       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7124     }
7125
7126     Mask1[0] = HiIndex & 1 ? 2 : 0;
7127     Mask1[1] = HiIndex & 1 ? 0 : 2;
7128     Mask1[2] = PermMask[2];
7129     Mask1[3] = PermMask[3];
7130     if (Mask1[2] >= 0)
7131       Mask1[2] += 4;
7132     if (Mask1[3] >= 0)
7133       Mask1[3] += 4;
7134     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7135   }
7136
7137   // Break it into (shuffle shuffle_hi, shuffle_lo).
7138   int LoMask[] = { -1, -1, -1, -1 };
7139   int HiMask[] = { -1, -1, -1, -1 };
7140
7141   int *MaskPtr = LoMask;
7142   unsigned MaskIdx = 0;
7143   unsigned LoIdx = 0;
7144   unsigned HiIdx = 2;
7145   for (unsigned i = 0; i != 4; ++i) {
7146     if (i == 2) {
7147       MaskPtr = HiMask;
7148       MaskIdx = 1;
7149       LoIdx = 0;
7150       HiIdx = 2;
7151     }
7152     int Idx = PermMask[i];
7153     if (Idx < 0) {
7154       Locs[i] = std::make_pair(-1, -1);
7155     } else if (Idx < 4) {
7156       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7157       MaskPtr[LoIdx] = Idx;
7158       LoIdx++;
7159     } else {
7160       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7161       MaskPtr[HiIdx] = Idx;
7162       HiIdx++;
7163     }
7164   }
7165
7166   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7167   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7168   int MaskOps[] = { -1, -1, -1, -1 };
7169   for (unsigned i = 0; i != 4; ++i)
7170     if (Locs[i].first != -1)
7171       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7172   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7173 }
7174
7175 static bool MayFoldVectorLoad(SDValue V) {
7176   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7177     V = V.getOperand(0);
7178
7179   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7180     V = V.getOperand(0);
7181   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7182       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7183     // BUILD_VECTOR (load), undef
7184     V = V.getOperand(0);
7185
7186   return MayFoldLoad(V);
7187 }
7188
7189 static
7190 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7191   MVT VT = Op.getSimpleValueType();
7192
7193   // Canonizalize to v2f64.
7194   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7195   return DAG.getNode(ISD::BITCAST, dl, VT,
7196                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7197                                           V1, DAG));
7198 }
7199
7200 static
7201 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7202                         bool HasSSE2) {
7203   SDValue V1 = Op.getOperand(0);
7204   SDValue V2 = Op.getOperand(1);
7205   MVT VT = Op.getSimpleValueType();
7206
7207   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7208
7209   if (HasSSE2 && VT == MVT::v2f64)
7210     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7211
7212   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7213   return DAG.getNode(ISD::BITCAST, dl, VT,
7214                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7215                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7216                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7217 }
7218
7219 static
7220 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7221   SDValue V1 = Op.getOperand(0);
7222   SDValue V2 = Op.getOperand(1);
7223   MVT VT = Op.getSimpleValueType();
7224
7225   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7226          "unsupported shuffle type");
7227
7228   if (V2.getOpcode() == ISD::UNDEF)
7229     V2 = V1;
7230
7231   // v4i32 or v4f32
7232   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7233 }
7234
7235 static
7236 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7237   SDValue V1 = Op.getOperand(0);
7238   SDValue V2 = Op.getOperand(1);
7239   MVT VT = Op.getSimpleValueType();
7240   unsigned NumElems = VT.getVectorNumElements();
7241
7242   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7243   // operand of these instructions is only memory, so check if there's a
7244   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7245   // same masks.
7246   bool CanFoldLoad = false;
7247
7248   // Trivial case, when V2 comes from a load.
7249   if (MayFoldVectorLoad(V2))
7250     CanFoldLoad = true;
7251
7252   // When V1 is a load, it can be folded later into a store in isel, example:
7253   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7254   //    turns into:
7255   //  (MOVLPSmr addr:$src1, VR128:$src2)
7256   // So, recognize this potential and also use MOVLPS or MOVLPD
7257   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7258     CanFoldLoad = true;
7259
7260   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7261   if (CanFoldLoad) {
7262     if (HasSSE2 && NumElems == 2)
7263       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7264
7265     if (NumElems == 4)
7266       // If we don't care about the second element, proceed to use movss.
7267       if (SVOp->getMaskElt(1) != -1)
7268         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7269   }
7270
7271   // movl and movlp will both match v2i64, but v2i64 is never matched by
7272   // movl earlier because we make it strict to avoid messing with the movlp load
7273   // folding logic (see the code above getMOVLP call). Match it here then,
7274   // this is horrible, but will stay like this until we move all shuffle
7275   // matching to x86 specific nodes. Note that for the 1st condition all
7276   // types are matched with movsd.
7277   if (HasSSE2) {
7278     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7279     // as to remove this logic from here, as much as possible
7280     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7281       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7282     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7283   }
7284
7285   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7286
7287   // Invert the operand order and use SHUFPS to match it.
7288   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7289                               getShuffleSHUFImmediate(SVOp), DAG);
7290 }
7291
7292 // It is only safe to call this function if isINSERTPSMask is true for
7293 // this shufflevector mask.
7294 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7295                            SelectionDAG &DAG) {
7296   // Generate an insertps instruction when inserting an f32 from memory onto a
7297   // v4f32 or when copying a member from one v4f32 to another.
7298   // We also use it for transferring i32 from one register to another,
7299   // since it simply copies the same bits.
7300   // If we're transfering an i32 from memory to a specific element in a
7301   // register, we output a generic DAG that will match the PINSRD
7302   // instruction.
7303   // TODO: Optimize for AVX cases too (VINSERTPS)
7304   MVT VT = SVOp->getSimpleValueType(0);
7305   MVT EVT = VT.getVectorElementType();
7306   SDValue V1 = SVOp->getOperand(0);
7307   SDValue V2 = SVOp->getOperand(1);
7308   auto Mask = SVOp->getMask();
7309   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7310          "unsupported vector type for insertps/pinsrd");
7311
7312   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7313                              [](const int &i) { return i < 4; });
7314
7315   SDValue From;
7316   SDValue To;
7317   unsigned DestIndex;
7318   if (FromV1 == 1) {
7319     From = V1;
7320     To = V2;
7321     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7322                              [](const int &i) { return i < 4; }) -
7323                 Mask.begin();
7324   } else {
7325     From = V2;
7326     To = V1;
7327     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7328                              [](const int &i) { return i >= 4; }) -
7329                 Mask.begin();
7330   }
7331
7332   if (MayFoldLoad(From)) {
7333     // Trivial case, when From comes from a load and is only used by the
7334     // shuffle. Make it use insertps from the vector that we need from that
7335     // load.
7336     SDValue Addr = From.getOperand(1);
7337     SDValue NewAddr =
7338         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7339                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7340                                     Addr.getSimpleValueType()));
7341
7342     LoadSDNode *Load = cast<LoadSDNode>(From);
7343     SDValue NewLoad =
7344         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7345                     DAG.getMachineFunction().getMachineMemOperand(
7346                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7347
7348     if (EVT == MVT::f32) {
7349       // Create this as a scalar to vector to match the instruction pattern.
7350       SDValue LoadScalarToVector =
7351           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7352       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7353       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7354                          InsertpsMask);
7355     } else { // EVT == MVT::i32
7356       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7357       // instruction, to match the PINSRD instruction, which loads an i32 to a
7358       // certain vector element.
7359       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7360                          DAG.getConstant(DestIndex, MVT::i32));
7361     }
7362   }
7363
7364   // Vector-element-to-vector
7365   unsigned SrcIndex = Mask[DestIndex] % 4;
7366   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7367   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7368 }
7369
7370 // Reduce a vector shuffle to zext.
7371 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7372                                     SelectionDAG &DAG) {
7373   // PMOVZX is only available from SSE41.
7374   if (!Subtarget->hasSSE41())
7375     return SDValue();
7376
7377   MVT VT = Op.getSimpleValueType();
7378
7379   // Only AVX2 support 256-bit vector integer extending.
7380   if (!Subtarget->hasInt256() && VT.is256BitVector())
7381     return SDValue();
7382
7383   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7384   SDLoc DL(Op);
7385   SDValue V1 = Op.getOperand(0);
7386   SDValue V2 = Op.getOperand(1);
7387   unsigned NumElems = VT.getVectorNumElements();
7388
7389   // Extending is an unary operation and the element type of the source vector
7390   // won't be equal to or larger than i64.
7391   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7392       VT.getVectorElementType() == MVT::i64)
7393     return SDValue();
7394
7395   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7396   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7397   while ((1U << Shift) < NumElems) {
7398     if (SVOp->getMaskElt(1U << Shift) == 1)
7399       break;
7400     Shift += 1;
7401     // The maximal ratio is 8, i.e. from i8 to i64.
7402     if (Shift > 3)
7403       return SDValue();
7404   }
7405
7406   // Check the shuffle mask.
7407   unsigned Mask = (1U << Shift) - 1;
7408   for (unsigned i = 0; i != NumElems; ++i) {
7409     int EltIdx = SVOp->getMaskElt(i);
7410     if ((i & Mask) != 0 && EltIdx != -1)
7411       return SDValue();
7412     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7413       return SDValue();
7414   }
7415
7416   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7417   MVT NeVT = MVT::getIntegerVT(NBits);
7418   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7419
7420   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7421     return SDValue();
7422
7423   // Simplify the operand as it's prepared to be fed into shuffle.
7424   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7425   if (V1.getOpcode() == ISD::BITCAST &&
7426       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7427       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7428       V1.getOperand(0).getOperand(0)
7429         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7430     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7431     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7432     ConstantSDNode *CIdx =
7433       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7434     // If it's foldable, i.e. normal load with single use, we will let code
7435     // selection to fold it. Otherwise, we will short the conversion sequence.
7436     if (CIdx && CIdx->getZExtValue() == 0 &&
7437         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7438       MVT FullVT = V.getSimpleValueType();
7439       MVT V1VT = V1.getSimpleValueType();
7440       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7441         // The "ext_vec_elt" node is wider than the result node.
7442         // In this case we should extract subvector from V.
7443         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7444         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7445         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7446                                         FullVT.getVectorNumElements()/Ratio);
7447         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7448                         DAG.getIntPtrConstant(0));
7449       }
7450       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7451     }
7452   }
7453
7454   return DAG.getNode(ISD::BITCAST, DL, VT,
7455                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7456 }
7457
7458 static SDValue
7459 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7460                        SelectionDAG &DAG) {
7461   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7462   MVT VT = Op.getSimpleValueType();
7463   SDLoc dl(Op);
7464   SDValue V1 = Op.getOperand(0);
7465   SDValue V2 = Op.getOperand(1);
7466
7467   if (isZeroShuffle(SVOp))
7468     return getZeroVector(VT, Subtarget, DAG, dl);
7469
7470   // Handle splat operations
7471   if (SVOp->isSplat()) {
7472     // Use vbroadcast whenever the splat comes from a foldable load
7473     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7474     if (Broadcast.getNode())
7475       return Broadcast;
7476   }
7477
7478   // Check integer expanding shuffles.
7479   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7480   if (NewOp.getNode())
7481     return NewOp;
7482
7483   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7484   // do it!
7485   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7486       VT == MVT::v16i16 || VT == MVT::v32i8) {
7487     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7488     if (NewOp.getNode())
7489       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7490   } else if ((VT == MVT::v4i32 ||
7491              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7492     // FIXME: Figure out a cleaner way to do this.
7493     // Try to make use of movq to zero out the top part.
7494     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7495       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7496       if (NewOp.getNode()) {
7497         MVT NewVT = NewOp.getSimpleValueType();
7498         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7499                                NewVT, true, false))
7500           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7501                               DAG, Subtarget, dl);
7502       }
7503     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7504       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7505       if (NewOp.getNode()) {
7506         MVT NewVT = NewOp.getSimpleValueType();
7507         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7508           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7509                               DAG, Subtarget, dl);
7510       }
7511     }
7512   }
7513   return SDValue();
7514 }
7515
7516 SDValue
7517 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7518   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7519   SDValue V1 = Op.getOperand(0);
7520   SDValue V2 = Op.getOperand(1);
7521   MVT VT = Op.getSimpleValueType();
7522   SDLoc dl(Op);
7523   unsigned NumElems = VT.getVectorNumElements();
7524   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7525   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7526   bool V1IsSplat = false;
7527   bool V2IsSplat = false;
7528   bool HasSSE2 = Subtarget->hasSSE2();
7529   bool HasFp256    = Subtarget->hasFp256();
7530   bool HasInt256   = Subtarget->hasInt256();
7531   MachineFunction &MF = DAG.getMachineFunction();
7532   bool OptForSize = MF.getFunction()->getAttributes().
7533     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7534
7535   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7536
7537   if (V1IsUndef && V2IsUndef)
7538     return DAG.getUNDEF(VT);
7539
7540   // When we create a shuffle node we put the UNDEF node to second operand,
7541   // but in some cases the first operand may be transformed to UNDEF.
7542   // In this case we should just commute the node.
7543   if (V1IsUndef)
7544     return CommuteVectorShuffle(SVOp, DAG);
7545
7546   // Vector shuffle lowering takes 3 steps:
7547   //
7548   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7549   //    narrowing and commutation of operands should be handled.
7550   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7551   //    shuffle nodes.
7552   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7553   //    so the shuffle can be broken into other shuffles and the legalizer can
7554   //    try the lowering again.
7555   //
7556   // The general idea is that no vector_shuffle operation should be left to
7557   // be matched during isel, all of them must be converted to a target specific
7558   // node here.
7559
7560   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7561   // narrowing and commutation of operands should be handled. The actual code
7562   // doesn't include all of those, work in progress...
7563   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7564   if (NewOp.getNode())
7565     return NewOp;
7566
7567   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7568
7569   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7570   // unpckh_undef). Only use pshufd if speed is more important than size.
7571   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7572     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7573   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7574     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7575
7576   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7577       V2IsUndef && MayFoldVectorLoad(V1))
7578     return getMOVDDup(Op, dl, V1, DAG);
7579
7580   if (isMOVHLPS_v_undef_Mask(M, VT))
7581     return getMOVHighToLow(Op, dl, DAG);
7582
7583   // Use to match splats
7584   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7585       (VT == MVT::v2f64 || VT == MVT::v2i64))
7586     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7587
7588   if (isPSHUFDMask(M, VT)) {
7589     // The actual implementation will match the mask in the if above and then
7590     // during isel it can match several different instructions, not only pshufd
7591     // as its name says, sad but true, emulate the behavior for now...
7592     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7593       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7594
7595     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7596
7597     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7598       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7599
7600     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7601       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7602                                   DAG);
7603
7604     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7605                                 TargetMask, DAG);
7606   }
7607
7608   if (isPALIGNRMask(M, VT, Subtarget))
7609     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7610                                 getShufflePALIGNRImmediate(SVOp),
7611                                 DAG);
7612
7613   // Check if this can be converted into a logical shift.
7614   bool isLeft = false;
7615   unsigned ShAmt = 0;
7616   SDValue ShVal;
7617   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7618   if (isShift && ShVal.hasOneUse()) {
7619     // If the shifted value has multiple uses, it may be cheaper to use
7620     // v_set0 + movlhps or movhlps, etc.
7621     MVT EltVT = VT.getVectorElementType();
7622     ShAmt *= EltVT.getSizeInBits();
7623     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7624   }
7625
7626   if (isMOVLMask(M, VT)) {
7627     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7628       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7629     if (!isMOVLPMask(M, VT)) {
7630       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7631         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7632
7633       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7634         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7635     }
7636   }
7637
7638   // FIXME: fold these into legal mask.
7639   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7640     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7641
7642   if (isMOVHLPSMask(M, VT))
7643     return getMOVHighToLow(Op, dl, DAG);
7644
7645   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7646     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7647
7648   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7649     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7650
7651   if (isMOVLPMask(M, VT))
7652     return getMOVLP(Op, dl, DAG, HasSSE2);
7653
7654   if (ShouldXformToMOVHLPS(M, VT) ||
7655       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7656     return CommuteVectorShuffle(SVOp, DAG);
7657
7658   if (isShift) {
7659     // No better options. Use a vshldq / vsrldq.
7660     MVT EltVT = VT.getVectorElementType();
7661     ShAmt *= EltVT.getSizeInBits();
7662     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7663   }
7664
7665   bool Commuted = false;
7666   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7667   // 1,1,1,1 -> v8i16 though.
7668   V1IsSplat = isSplatVector(V1.getNode());
7669   V2IsSplat = isSplatVector(V2.getNode());
7670
7671   // Canonicalize the splat or undef, if present, to be on the RHS.
7672   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7673     CommuteVectorShuffleMask(M, NumElems);
7674     std::swap(V1, V2);
7675     std::swap(V1IsSplat, V2IsSplat);
7676     Commuted = true;
7677   }
7678
7679   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7680     // Shuffling low element of v1 into undef, just return v1.
7681     if (V2IsUndef)
7682       return V1;
7683     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7684     // the instruction selector will not match, so get a canonical MOVL with
7685     // swapped operands to undo the commute.
7686     return getMOVL(DAG, dl, VT, V2, V1);
7687   }
7688
7689   if (isUNPCKLMask(M, VT, HasInt256))
7690     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7691
7692   if (isUNPCKHMask(M, VT, HasInt256))
7693     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7694
7695   if (V2IsSplat) {
7696     // Normalize mask so all entries that point to V2 points to its first
7697     // element then try to match unpck{h|l} again. If match, return a
7698     // new vector_shuffle with the corrected mask.p
7699     SmallVector<int, 8> NewMask(M.begin(), M.end());
7700     NormalizeMask(NewMask, NumElems);
7701     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7702       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7703     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7704       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7705   }
7706
7707   if (Commuted) {
7708     // Commute is back and try unpck* again.
7709     // FIXME: this seems wrong.
7710     CommuteVectorShuffleMask(M, NumElems);
7711     std::swap(V1, V2);
7712     std::swap(V1IsSplat, V2IsSplat);
7713
7714     if (isUNPCKLMask(M, VT, HasInt256))
7715       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7716
7717     if (isUNPCKHMask(M, VT, HasInt256))
7718       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7719   }
7720
7721   // Normalize the node to match x86 shuffle ops if needed
7722   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7723     return CommuteVectorShuffle(SVOp, DAG);
7724
7725   // The checks below are all present in isShuffleMaskLegal, but they are
7726   // inlined here right now to enable us to directly emit target specific
7727   // nodes, and remove one by one until they don't return Op anymore.
7728
7729   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7730       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7731     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7732       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7733   }
7734
7735   if (isPSHUFHWMask(M, VT, HasInt256))
7736     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7737                                 getShufflePSHUFHWImmediate(SVOp),
7738                                 DAG);
7739
7740   if (isPSHUFLWMask(M, VT, HasInt256))
7741     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7742                                 getShufflePSHUFLWImmediate(SVOp),
7743                                 DAG);
7744
7745   if (isSHUFPMask(M, VT))
7746     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7747                                 getShuffleSHUFImmediate(SVOp), DAG);
7748
7749   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7750     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7751   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7752     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7753
7754   //===--------------------------------------------------------------------===//
7755   // Generate target specific nodes for 128 or 256-bit shuffles only
7756   // supported in the AVX instruction set.
7757   //
7758
7759   // Handle VMOVDDUPY permutations
7760   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7761     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7762
7763   // Handle VPERMILPS/D* permutations
7764   if (isVPERMILPMask(M, VT)) {
7765     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7766       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7767                                   getShuffleSHUFImmediate(SVOp), DAG);
7768     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7769                                 getShuffleSHUFImmediate(SVOp), DAG);
7770   }
7771
7772   // Handle VPERM2F128/VPERM2I128 permutations
7773   if (isVPERM2X128Mask(M, VT, HasFp256))
7774     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7775                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7776
7777   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7778   if (BlendOp.getNode())
7779     return BlendOp;
7780
7781   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7782     return getINSERTPS(SVOp, dl, DAG);
7783
7784   unsigned Imm8;
7785   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7786     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7787
7788   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7789       VT.is512BitVector()) {
7790     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7791     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7792     SmallVector<SDValue, 16> permclMask;
7793     for (unsigned i = 0; i != NumElems; ++i) {
7794       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7795     }
7796
7797     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7798                                 &permclMask[0], NumElems);
7799     if (V2IsUndef)
7800       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7801       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7802                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7803     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7804                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7805   }
7806
7807   //===--------------------------------------------------------------------===//
7808   // Since no target specific shuffle was selected for this generic one,
7809   // lower it into other known shuffles. FIXME: this isn't true yet, but
7810   // this is the plan.
7811   //
7812
7813   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7814   if (VT == MVT::v8i16) {
7815     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7816     if (NewOp.getNode())
7817       return NewOp;
7818   }
7819
7820   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7821     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7822     if (NewOp.getNode())
7823       return NewOp;
7824   }
7825
7826   if (VT == MVT::v16i8) {
7827     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7828     if (NewOp.getNode())
7829       return NewOp;
7830   }
7831
7832   if (VT == MVT::v32i8) {
7833     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7834     if (NewOp.getNode())
7835       return NewOp;
7836   }
7837
7838   // Handle all 128-bit wide vectors with 4 elements, and match them with
7839   // several different shuffle types.
7840   if (NumElems == 4 && VT.is128BitVector())
7841     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7842
7843   // Handle general 256-bit shuffles
7844   if (VT.is256BitVector())
7845     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7846
7847   return SDValue();
7848 }
7849
7850 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7851   MVT VT = Op.getSimpleValueType();
7852   SDLoc dl(Op);
7853
7854   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7855     return SDValue();
7856
7857   if (VT.getSizeInBits() == 8) {
7858     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7859                                   Op.getOperand(0), Op.getOperand(1));
7860     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7861                                   DAG.getValueType(VT));
7862     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7863   }
7864
7865   if (VT.getSizeInBits() == 16) {
7866     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7867     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7868     if (Idx == 0)
7869       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7870                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7871                                      DAG.getNode(ISD::BITCAST, dl,
7872                                                  MVT::v4i32,
7873                                                  Op.getOperand(0)),
7874                                      Op.getOperand(1)));
7875     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7876                                   Op.getOperand(0), Op.getOperand(1));
7877     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7878                                   DAG.getValueType(VT));
7879     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7880   }
7881
7882   if (VT == MVT::f32) {
7883     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7884     // the result back to FR32 register. It's only worth matching if the
7885     // result has a single use which is a store or a bitcast to i32.  And in
7886     // the case of a store, it's not worth it if the index is a constant 0,
7887     // because a MOVSSmr can be used instead, which is smaller and faster.
7888     if (!Op.hasOneUse())
7889       return SDValue();
7890     SDNode *User = *Op.getNode()->use_begin();
7891     if ((User->getOpcode() != ISD::STORE ||
7892          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7893           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7894         (User->getOpcode() != ISD::BITCAST ||
7895          User->getValueType(0) != MVT::i32))
7896       return SDValue();
7897     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7898                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7899                                               Op.getOperand(0)),
7900                                               Op.getOperand(1));
7901     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7902   }
7903
7904   if (VT == MVT::i32 || VT == MVT::i64) {
7905     // ExtractPS/pextrq works with constant index.
7906     if (isa<ConstantSDNode>(Op.getOperand(1)))
7907       return Op;
7908   }
7909   return SDValue();
7910 }
7911
7912 /// Extract one bit from mask vector, like v16i1 or v8i1.
7913 /// AVX-512 feature.
7914 SDValue
7915 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7916   SDValue Vec = Op.getOperand(0);
7917   SDLoc dl(Vec);
7918   MVT VecVT = Vec.getSimpleValueType();
7919   SDValue Idx = Op.getOperand(1);
7920   MVT EltVT = Op.getSimpleValueType();
7921
7922   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7923
7924   // variable index can't be handled in mask registers,
7925   // extend vector to VR512
7926   if (!isa<ConstantSDNode>(Idx)) {
7927     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7928     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7929     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7930                               ExtVT.getVectorElementType(), Ext, Idx);
7931     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7932   }
7933
7934   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7935   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7936   unsigned MaxSift = rc->getSize()*8 - 1;
7937   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7938                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7939   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7940                     DAG.getConstant(MaxSift, MVT::i8));
7941   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7942                        DAG.getIntPtrConstant(0));
7943 }
7944
7945 SDValue
7946 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7947                                            SelectionDAG &DAG) const {
7948   SDLoc dl(Op);
7949   SDValue Vec = Op.getOperand(0);
7950   MVT VecVT = Vec.getSimpleValueType();
7951   SDValue Idx = Op.getOperand(1);
7952
7953   if (Op.getSimpleValueType() == MVT::i1)
7954     return ExtractBitFromMaskVector(Op, DAG);
7955
7956   if (!isa<ConstantSDNode>(Idx)) {
7957     if (VecVT.is512BitVector() ||
7958         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7959          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7960
7961       MVT MaskEltVT =
7962         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7963       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7964                                     MaskEltVT.getSizeInBits());
7965
7966       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7967       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7968                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7969                                 Idx, DAG.getConstant(0, getPointerTy()));
7970       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7971       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7972                         Perm, DAG.getConstant(0, getPointerTy()));
7973     }
7974     return SDValue();
7975   }
7976
7977   // If this is a 256-bit vector result, first extract the 128-bit vector and
7978   // then extract the element from the 128-bit vector.
7979   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7980
7981     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7982     // Get the 128-bit vector.
7983     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7984     MVT EltVT = VecVT.getVectorElementType();
7985
7986     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7987
7988     //if (IdxVal >= NumElems/2)
7989     //  IdxVal -= NumElems/2;
7990     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7991     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7992                        DAG.getConstant(IdxVal, MVT::i32));
7993   }
7994
7995   assert(VecVT.is128BitVector() && "Unexpected vector length");
7996
7997   if (Subtarget->hasSSE41()) {
7998     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7999     if (Res.getNode())
8000       return Res;
8001   }
8002
8003   MVT VT = Op.getSimpleValueType();
8004   // TODO: handle v16i8.
8005   if (VT.getSizeInBits() == 16) {
8006     SDValue Vec = Op.getOperand(0);
8007     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8008     if (Idx == 0)
8009       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8010                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8011                                      DAG.getNode(ISD::BITCAST, dl,
8012                                                  MVT::v4i32, Vec),
8013                                      Op.getOperand(1)));
8014     // Transform it so it match pextrw which produces a 32-bit result.
8015     MVT EltVT = MVT::i32;
8016     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8017                                   Op.getOperand(0), Op.getOperand(1));
8018     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8019                                   DAG.getValueType(VT));
8020     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8021   }
8022
8023   if (VT.getSizeInBits() == 32) {
8024     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8025     if (Idx == 0)
8026       return Op;
8027
8028     // SHUFPS the element to the lowest double word, then movss.
8029     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8030     MVT VVT = Op.getOperand(0).getSimpleValueType();
8031     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8032                                        DAG.getUNDEF(VVT), Mask);
8033     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8034                        DAG.getIntPtrConstant(0));
8035   }
8036
8037   if (VT.getSizeInBits() == 64) {
8038     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8039     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8040     //        to match extract_elt for f64.
8041     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8042     if (Idx == 0)
8043       return Op;
8044
8045     // UNPCKHPD the element to the lowest double word, then movsd.
8046     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8047     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8048     int Mask[2] = { 1, -1 };
8049     MVT VVT = Op.getOperand(0).getSimpleValueType();
8050     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8051                                        DAG.getUNDEF(VVT), Mask);
8052     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8053                        DAG.getIntPtrConstant(0));
8054   }
8055
8056   return SDValue();
8057 }
8058
8059 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8060   MVT VT = Op.getSimpleValueType();
8061   MVT EltVT = VT.getVectorElementType();
8062   SDLoc dl(Op);
8063
8064   SDValue N0 = Op.getOperand(0);
8065   SDValue N1 = Op.getOperand(1);
8066   SDValue N2 = Op.getOperand(2);
8067
8068   if (!VT.is128BitVector())
8069     return SDValue();
8070
8071   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8072       isa<ConstantSDNode>(N2)) {
8073     unsigned Opc;
8074     if (VT == MVT::v8i16)
8075       Opc = X86ISD::PINSRW;
8076     else if (VT == MVT::v16i8)
8077       Opc = X86ISD::PINSRB;
8078     else
8079       Opc = X86ISD::PINSRB;
8080
8081     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8082     // argument.
8083     if (N1.getValueType() != MVT::i32)
8084       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8085     if (N2.getValueType() != MVT::i32)
8086       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8087     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8088   }
8089
8090   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8091     // Bits [7:6] of the constant are the source select.  This will always be
8092     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8093     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8094     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8095     // Bits [5:4] of the constant are the destination select.  This is the
8096     //  value of the incoming immediate.
8097     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8098     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8099     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8100     // Create this as a scalar to vector..
8101     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8102     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8103   }
8104
8105   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8106     // PINSR* works with constant index.
8107     return Op;
8108   }
8109   return SDValue();
8110 }
8111
8112 /// Insert one bit to mask vector, like v16i1 or v8i1.
8113 /// AVX-512 feature.
8114 SDValue 
8115 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8116   SDLoc dl(Op);
8117   SDValue Vec = Op.getOperand(0);
8118   SDValue Elt = Op.getOperand(1);
8119   SDValue Idx = Op.getOperand(2);
8120   MVT VecVT = Vec.getSimpleValueType();
8121
8122   if (!isa<ConstantSDNode>(Idx)) {
8123     // Non constant index. Extend source and destination,
8124     // insert element and then truncate the result.
8125     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8126     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8127     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8128       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8129       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8130     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8131   }
8132
8133   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8134   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8135   if (Vec.getOpcode() == ISD::UNDEF)
8136     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8137                        DAG.getConstant(IdxVal, MVT::i8));
8138   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8139   unsigned MaxSift = rc->getSize()*8 - 1;
8140   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8141                     DAG.getConstant(MaxSift, MVT::i8));
8142   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8143                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8144   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8145 }
8146 SDValue
8147 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8148   MVT VT = Op.getSimpleValueType();
8149   MVT EltVT = VT.getVectorElementType();
8150   
8151   if (EltVT == MVT::i1)
8152     return InsertBitToMaskVector(Op, DAG);
8153
8154   SDLoc dl(Op);
8155   SDValue N0 = Op.getOperand(0);
8156   SDValue N1 = Op.getOperand(1);
8157   SDValue N2 = Op.getOperand(2);
8158
8159   // If this is a 256-bit vector result, first extract the 128-bit vector,
8160   // insert the element into the extracted half and then place it back.
8161   if (VT.is256BitVector() || VT.is512BitVector()) {
8162     if (!isa<ConstantSDNode>(N2))
8163       return SDValue();
8164
8165     // Get the desired 128-bit vector half.
8166     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8167     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8168
8169     // Insert the element into the desired half.
8170     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8171     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8172
8173     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8174                     DAG.getConstant(IdxIn128, MVT::i32));
8175
8176     // Insert the changed part back to the 256-bit vector
8177     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8178   }
8179
8180   if (Subtarget->hasSSE41())
8181     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8182
8183   if (EltVT == MVT::i8)
8184     return SDValue();
8185
8186   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8187     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8188     // as its second argument.
8189     if (N1.getValueType() != MVT::i32)
8190       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8191     if (N2.getValueType() != MVT::i32)
8192       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8193     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8194   }
8195   return SDValue();
8196 }
8197
8198 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8199   SDLoc dl(Op);
8200   MVT OpVT = Op.getSimpleValueType();
8201
8202   // If this is a 256-bit vector result, first insert into a 128-bit
8203   // vector and then insert into the 256-bit vector.
8204   if (!OpVT.is128BitVector()) {
8205     // Insert into a 128-bit vector.
8206     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8207     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8208                                  OpVT.getVectorNumElements() / SizeFactor);
8209
8210     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8211
8212     // Insert the 128-bit vector.
8213     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8214   }
8215
8216   if (OpVT == MVT::v1i64 &&
8217       Op.getOperand(0).getValueType() == MVT::i64)
8218     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8219
8220   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8221   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8222   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8223                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8224 }
8225
8226 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8227 // a simple subregister reference or explicit instructions to grab
8228 // upper bits of a vector.
8229 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8230                                       SelectionDAG &DAG) {
8231   SDLoc dl(Op);
8232   SDValue In =  Op.getOperand(0);
8233   SDValue Idx = Op.getOperand(1);
8234   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8235   MVT ResVT   = Op.getSimpleValueType();
8236   MVT InVT    = In.getSimpleValueType();
8237
8238   if (Subtarget->hasFp256()) {
8239     if (ResVT.is128BitVector() &&
8240         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8241         isa<ConstantSDNode>(Idx)) {
8242       return Extract128BitVector(In, IdxVal, DAG, dl);
8243     }
8244     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8245         isa<ConstantSDNode>(Idx)) {
8246       return Extract256BitVector(In, IdxVal, DAG, dl);
8247     }
8248   }
8249   return SDValue();
8250 }
8251
8252 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8253 // simple superregister reference or explicit instructions to insert
8254 // the upper bits of a vector.
8255 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8256                                      SelectionDAG &DAG) {
8257   if (Subtarget->hasFp256()) {
8258     SDLoc dl(Op.getNode());
8259     SDValue Vec = Op.getNode()->getOperand(0);
8260     SDValue SubVec = Op.getNode()->getOperand(1);
8261     SDValue Idx = Op.getNode()->getOperand(2);
8262
8263     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8264          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8265         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8266         isa<ConstantSDNode>(Idx)) {
8267       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8268       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8269     }
8270
8271     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8272         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8273         isa<ConstantSDNode>(Idx)) {
8274       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8275       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8276     }
8277   }
8278   return SDValue();
8279 }
8280
8281 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8282 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8283 // one of the above mentioned nodes. It has to be wrapped because otherwise
8284 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8285 // be used to form addressing mode. These wrapped nodes will be selected
8286 // into MOV32ri.
8287 SDValue
8288 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8289   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8290
8291   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8292   // global base reg.
8293   unsigned char OpFlag = 0;
8294   unsigned WrapperKind = X86ISD::Wrapper;
8295   CodeModel::Model M = getTargetMachine().getCodeModel();
8296
8297   if (Subtarget->isPICStyleRIPRel() &&
8298       (M == CodeModel::Small || M == CodeModel::Kernel))
8299     WrapperKind = X86ISD::WrapperRIP;
8300   else if (Subtarget->isPICStyleGOT())
8301     OpFlag = X86II::MO_GOTOFF;
8302   else if (Subtarget->isPICStyleStubPIC())
8303     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8304
8305   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8306                                              CP->getAlignment(),
8307                                              CP->getOffset(), OpFlag);
8308   SDLoc DL(CP);
8309   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8310   // With PIC, the address is actually $g + Offset.
8311   if (OpFlag) {
8312     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8313                          DAG.getNode(X86ISD::GlobalBaseReg,
8314                                      SDLoc(), getPointerTy()),
8315                          Result);
8316   }
8317
8318   return Result;
8319 }
8320
8321 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8322   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8323
8324   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8325   // global base reg.
8326   unsigned char OpFlag = 0;
8327   unsigned WrapperKind = X86ISD::Wrapper;
8328   CodeModel::Model M = getTargetMachine().getCodeModel();
8329
8330   if (Subtarget->isPICStyleRIPRel() &&
8331       (M == CodeModel::Small || M == CodeModel::Kernel))
8332     WrapperKind = X86ISD::WrapperRIP;
8333   else if (Subtarget->isPICStyleGOT())
8334     OpFlag = X86II::MO_GOTOFF;
8335   else if (Subtarget->isPICStyleStubPIC())
8336     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8337
8338   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8339                                           OpFlag);
8340   SDLoc DL(JT);
8341   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8342
8343   // With PIC, the address is actually $g + Offset.
8344   if (OpFlag)
8345     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8346                          DAG.getNode(X86ISD::GlobalBaseReg,
8347                                      SDLoc(), getPointerTy()),
8348                          Result);
8349
8350   return Result;
8351 }
8352
8353 SDValue
8354 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8355   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8356
8357   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8358   // global base reg.
8359   unsigned char OpFlag = 0;
8360   unsigned WrapperKind = X86ISD::Wrapper;
8361   CodeModel::Model M = getTargetMachine().getCodeModel();
8362
8363   if (Subtarget->isPICStyleRIPRel() &&
8364       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8365     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8366       OpFlag = X86II::MO_GOTPCREL;
8367     WrapperKind = X86ISD::WrapperRIP;
8368   } else if (Subtarget->isPICStyleGOT()) {
8369     OpFlag = X86II::MO_GOT;
8370   } else if (Subtarget->isPICStyleStubPIC()) {
8371     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8372   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8373     OpFlag = X86II::MO_DARWIN_NONLAZY;
8374   }
8375
8376   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8377
8378   SDLoc DL(Op);
8379   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8380
8381   // With PIC, the address is actually $g + Offset.
8382   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8383       !Subtarget->is64Bit()) {
8384     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8385                          DAG.getNode(X86ISD::GlobalBaseReg,
8386                                      SDLoc(), getPointerTy()),
8387                          Result);
8388   }
8389
8390   // For symbols that require a load from a stub to get the address, emit the
8391   // load.
8392   if (isGlobalStubReference(OpFlag))
8393     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8394                          MachinePointerInfo::getGOT(), false, false, false, 0);
8395
8396   return Result;
8397 }
8398
8399 SDValue
8400 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8401   // Create the TargetBlockAddressAddress node.
8402   unsigned char OpFlags =
8403     Subtarget->ClassifyBlockAddressReference();
8404   CodeModel::Model M = getTargetMachine().getCodeModel();
8405   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8406   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8407   SDLoc dl(Op);
8408   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8409                                              OpFlags);
8410
8411   if (Subtarget->isPICStyleRIPRel() &&
8412       (M == CodeModel::Small || M == CodeModel::Kernel))
8413     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8414   else
8415     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8416
8417   // With PIC, the address is actually $g + Offset.
8418   if (isGlobalRelativeToPICBase(OpFlags)) {
8419     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8420                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8421                          Result);
8422   }
8423
8424   return Result;
8425 }
8426
8427 SDValue
8428 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8429                                       int64_t Offset, SelectionDAG &DAG) const {
8430   // Create the TargetGlobalAddress node, folding in the constant
8431   // offset if it is legal.
8432   unsigned char OpFlags =
8433     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8434   CodeModel::Model M = getTargetMachine().getCodeModel();
8435   SDValue Result;
8436   if (OpFlags == X86II::MO_NO_FLAG &&
8437       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8438     // A direct static reference to a global.
8439     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8440     Offset = 0;
8441   } else {
8442     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8443   }
8444
8445   if (Subtarget->isPICStyleRIPRel() &&
8446       (M == CodeModel::Small || M == CodeModel::Kernel))
8447     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8448   else
8449     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8450
8451   // With PIC, the address is actually $g + Offset.
8452   if (isGlobalRelativeToPICBase(OpFlags)) {
8453     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8454                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8455                          Result);
8456   }
8457
8458   // For globals that require a load from a stub to get the address, emit the
8459   // load.
8460   if (isGlobalStubReference(OpFlags))
8461     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8462                          MachinePointerInfo::getGOT(), false, false, false, 0);
8463
8464   // If there was a non-zero offset that we didn't fold, create an explicit
8465   // addition for it.
8466   if (Offset != 0)
8467     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8468                          DAG.getConstant(Offset, getPointerTy()));
8469
8470   return Result;
8471 }
8472
8473 SDValue
8474 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8475   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8476   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8477   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8478 }
8479
8480 static SDValue
8481 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8482            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8483            unsigned char OperandFlags, bool LocalDynamic = false) {
8484   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8485   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8486   SDLoc dl(GA);
8487   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8488                                            GA->getValueType(0),
8489                                            GA->getOffset(),
8490                                            OperandFlags);
8491
8492   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8493                                            : X86ISD::TLSADDR;
8494
8495   if (InFlag) {
8496     SDValue Ops[] = { Chain,  TGA, *InFlag };
8497     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8498   } else {
8499     SDValue Ops[]  = { Chain, TGA };
8500     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8501   }
8502
8503   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8504   MFI->setAdjustsStack(true);
8505
8506   SDValue Flag = Chain.getValue(1);
8507   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8508 }
8509
8510 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8511 static SDValue
8512 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8513                                 const EVT PtrVT) {
8514   SDValue InFlag;
8515   SDLoc dl(GA);  // ? function entry point might be better
8516   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8517                                    DAG.getNode(X86ISD::GlobalBaseReg,
8518                                                SDLoc(), PtrVT), InFlag);
8519   InFlag = Chain.getValue(1);
8520
8521   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8522 }
8523
8524 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8525 static SDValue
8526 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8527                                 const EVT PtrVT) {
8528   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8529                     X86::RAX, X86II::MO_TLSGD);
8530 }
8531
8532 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8533                                            SelectionDAG &DAG,
8534                                            const EVT PtrVT,
8535                                            bool is64Bit) {
8536   SDLoc dl(GA);
8537
8538   // Get the start address of the TLS block for this module.
8539   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8540       .getInfo<X86MachineFunctionInfo>();
8541   MFI->incNumLocalDynamicTLSAccesses();
8542
8543   SDValue Base;
8544   if (is64Bit) {
8545     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8546                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8547   } else {
8548     SDValue InFlag;
8549     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8550         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8551     InFlag = Chain.getValue(1);
8552     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8553                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8554   }
8555
8556   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8557   // of Base.
8558
8559   // Build x@dtpoff.
8560   unsigned char OperandFlags = X86II::MO_DTPOFF;
8561   unsigned WrapperKind = X86ISD::Wrapper;
8562   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8563                                            GA->getValueType(0),
8564                                            GA->getOffset(), OperandFlags);
8565   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8566
8567   // Add x@dtpoff with the base.
8568   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8569 }
8570
8571 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8572 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8573                                    const EVT PtrVT, TLSModel::Model model,
8574                                    bool is64Bit, bool isPIC) {
8575   SDLoc dl(GA);
8576
8577   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8578   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8579                                                          is64Bit ? 257 : 256));
8580
8581   SDValue ThreadPointer =
8582       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8583                   MachinePointerInfo(Ptr), false, false, false, 0);
8584
8585   unsigned char OperandFlags = 0;
8586   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8587   // initialexec.
8588   unsigned WrapperKind = X86ISD::Wrapper;
8589   if (model == TLSModel::LocalExec) {
8590     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8591   } else if (model == TLSModel::InitialExec) {
8592     if (is64Bit) {
8593       OperandFlags = X86II::MO_GOTTPOFF;
8594       WrapperKind = X86ISD::WrapperRIP;
8595     } else {
8596       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8597     }
8598   } else {
8599     llvm_unreachable("Unexpected model");
8600   }
8601
8602   // emit "addl x@ntpoff,%eax" (local exec)
8603   // or "addl x@indntpoff,%eax" (initial exec)
8604   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8605   SDValue TGA =
8606       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8607                                  GA->getOffset(), OperandFlags);
8608   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8609
8610   if (model == TLSModel::InitialExec) {
8611     if (isPIC && !is64Bit) {
8612       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8613                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8614                            Offset);
8615     }
8616
8617     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8618                          MachinePointerInfo::getGOT(), false, false, false, 0);
8619   }
8620
8621   // The address of the thread local variable is the add of the thread
8622   // pointer with the offset of the variable.
8623   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8624 }
8625
8626 SDValue
8627 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8628
8629   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8630   const GlobalValue *GV = GA->getGlobal();
8631
8632   if (Subtarget->isTargetELF()) {
8633     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8634
8635     switch (model) {
8636       case TLSModel::GeneralDynamic:
8637         if (Subtarget->is64Bit())
8638           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8639         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8640       case TLSModel::LocalDynamic:
8641         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8642                                            Subtarget->is64Bit());
8643       case TLSModel::InitialExec:
8644       case TLSModel::LocalExec:
8645         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8646                                    Subtarget->is64Bit(),
8647                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8648     }
8649     llvm_unreachable("Unknown TLS model.");
8650   }
8651
8652   if (Subtarget->isTargetDarwin()) {
8653     // Darwin only has one model of TLS.  Lower to that.
8654     unsigned char OpFlag = 0;
8655     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8656                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8657
8658     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8659     // global base reg.
8660     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8661                   !Subtarget->is64Bit();
8662     if (PIC32)
8663       OpFlag = X86II::MO_TLVP_PIC_BASE;
8664     else
8665       OpFlag = X86II::MO_TLVP;
8666     SDLoc DL(Op);
8667     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8668                                                 GA->getValueType(0),
8669                                                 GA->getOffset(), OpFlag);
8670     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8671
8672     // With PIC32, the address is actually $g + Offset.
8673     if (PIC32)
8674       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8675                            DAG.getNode(X86ISD::GlobalBaseReg,
8676                                        SDLoc(), getPointerTy()),
8677                            Offset);
8678
8679     // Lowering the machine isd will make sure everything is in the right
8680     // location.
8681     SDValue Chain = DAG.getEntryNode();
8682     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8683     SDValue Args[] = { Chain, Offset };
8684     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8685
8686     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8687     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8688     MFI->setAdjustsStack(true);
8689
8690     // And our return value (tls address) is in the standard call return value
8691     // location.
8692     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8693     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8694                               Chain.getValue(1));
8695   }
8696
8697   if (Subtarget->isTargetKnownWindowsMSVC() ||
8698       Subtarget->isTargetWindowsGNU()) {
8699     // Just use the implicit TLS architecture
8700     // Need to generate someting similar to:
8701     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8702     //                                  ; from TEB
8703     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8704     //   mov     rcx, qword [rdx+rcx*8]
8705     //   mov     eax, .tls$:tlsvar
8706     //   [rax+rcx] contains the address
8707     // Windows 64bit: gs:0x58
8708     // Windows 32bit: fs:__tls_array
8709
8710     // If GV is an alias then use the aliasee for determining
8711     // thread-localness.
8712     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8713       GV = GA->getAliasedGlobal();
8714     SDLoc dl(GA);
8715     SDValue Chain = DAG.getEntryNode();
8716
8717     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8718     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8719     // use its literal value of 0x2C.
8720     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8721                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8722                                                              256)
8723                                         : Type::getInt32PtrTy(*DAG.getContext(),
8724                                                               257));
8725
8726     SDValue TlsArray =
8727         Subtarget->is64Bit()
8728             ? DAG.getIntPtrConstant(0x58)
8729             : (Subtarget->isTargetWindowsGNU()
8730                    ? DAG.getIntPtrConstant(0x2C)
8731                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8732
8733     SDValue ThreadPointer =
8734         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8735                     MachinePointerInfo(Ptr), false, false, false, 0);
8736
8737     // Load the _tls_index variable
8738     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8739     if (Subtarget->is64Bit())
8740       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8741                            IDX, MachinePointerInfo(), MVT::i32,
8742                            false, false, 0);
8743     else
8744       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8745                         false, false, false, 0);
8746
8747     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8748                                     getPointerTy());
8749     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8750
8751     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8752     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8753                       false, false, false, 0);
8754
8755     // Get the offset of start of .tls section
8756     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8757                                              GA->getValueType(0),
8758                                              GA->getOffset(), X86II::MO_SECREL);
8759     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8760
8761     // The address of the thread local variable is the add of the thread
8762     // pointer with the offset of the variable.
8763     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8764   }
8765
8766   llvm_unreachable("TLS not implemented for this target.");
8767 }
8768
8769 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8770 /// and take a 2 x i32 value to shift plus a shift amount.
8771 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8772   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8773   MVT VT = Op.getSimpleValueType();
8774   unsigned VTBits = VT.getSizeInBits();
8775   SDLoc dl(Op);
8776   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8777   SDValue ShOpLo = Op.getOperand(0);
8778   SDValue ShOpHi = Op.getOperand(1);
8779   SDValue ShAmt  = Op.getOperand(2);
8780   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8781   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8782   // during isel.
8783   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8784                                   DAG.getConstant(VTBits - 1, MVT::i8));
8785   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8786                                      DAG.getConstant(VTBits - 1, MVT::i8))
8787                        : DAG.getConstant(0, VT);
8788
8789   SDValue Tmp2, Tmp3;
8790   if (Op.getOpcode() == ISD::SHL_PARTS) {
8791     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8792     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8793   } else {
8794     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8795     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8796   }
8797
8798   // If the shift amount is larger or equal than the width of a part we can't
8799   // rely on the results of shld/shrd. Insert a test and select the appropriate
8800   // values for large shift amounts.
8801   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8802                                 DAG.getConstant(VTBits, MVT::i8));
8803   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8804                              AndNode, DAG.getConstant(0, MVT::i8));
8805
8806   SDValue Hi, Lo;
8807   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8808   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8809   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8810
8811   if (Op.getOpcode() == ISD::SHL_PARTS) {
8812     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8813     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8814   } else {
8815     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8816     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8817   }
8818
8819   SDValue Ops[2] = { Lo, Hi };
8820   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8821 }
8822
8823 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8824                                            SelectionDAG &DAG) const {
8825   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8826
8827   if (SrcVT.isVector())
8828     return SDValue();
8829
8830   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8831          "Unknown SINT_TO_FP to lower!");
8832
8833   // These are really Legal; return the operand so the caller accepts it as
8834   // Legal.
8835   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8836     return Op;
8837   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8838       Subtarget->is64Bit()) {
8839     return Op;
8840   }
8841
8842   SDLoc dl(Op);
8843   unsigned Size = SrcVT.getSizeInBits()/8;
8844   MachineFunction &MF = DAG.getMachineFunction();
8845   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8846   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8847   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8848                                StackSlot,
8849                                MachinePointerInfo::getFixedStack(SSFI),
8850                                false, false, 0);
8851   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8852 }
8853
8854 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8855                                      SDValue StackSlot,
8856                                      SelectionDAG &DAG) const {
8857   // Build the FILD
8858   SDLoc DL(Op);
8859   SDVTList Tys;
8860   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8861   if (useSSE)
8862     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8863   else
8864     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8865
8866   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8867
8868   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8869   MachineMemOperand *MMO;
8870   if (FI) {
8871     int SSFI = FI->getIndex();
8872     MMO =
8873       DAG.getMachineFunction()
8874       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8875                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8876   } else {
8877     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8878     StackSlot = StackSlot.getOperand(1);
8879   }
8880   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8881   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8882                                            X86ISD::FILD, DL,
8883                                            Tys, Ops, array_lengthof(Ops),
8884                                            SrcVT, MMO);
8885
8886   if (useSSE) {
8887     Chain = Result.getValue(1);
8888     SDValue InFlag = Result.getValue(2);
8889
8890     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8891     // shouldn't be necessary except that RFP cannot be live across
8892     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8893     MachineFunction &MF = DAG.getMachineFunction();
8894     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8895     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8896     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8897     Tys = DAG.getVTList(MVT::Other);
8898     SDValue Ops[] = {
8899       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8900     };
8901     MachineMemOperand *MMO =
8902       DAG.getMachineFunction()
8903       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8904                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8905
8906     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8907                                     Ops, array_lengthof(Ops),
8908                                     Op.getValueType(), MMO);
8909     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8910                          MachinePointerInfo::getFixedStack(SSFI),
8911                          false, false, false, 0);
8912   }
8913
8914   return Result;
8915 }
8916
8917 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8918 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8919                                                SelectionDAG &DAG) const {
8920   // This algorithm is not obvious. Here it is what we're trying to output:
8921   /*
8922      movq       %rax,  %xmm0
8923      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8924      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8925      #ifdef __SSE3__
8926        haddpd   %xmm0, %xmm0
8927      #else
8928        pshufd   $0x4e, %xmm0, %xmm1
8929        addpd    %xmm1, %xmm0
8930      #endif
8931   */
8932
8933   SDLoc dl(Op);
8934   LLVMContext *Context = DAG.getContext();
8935
8936   // Build some magic constants.
8937   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8938   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8939   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8940
8941   SmallVector<Constant*,2> CV1;
8942   CV1.push_back(
8943     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8944                                       APInt(64, 0x4330000000000000ULL))));
8945   CV1.push_back(
8946     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8947                                       APInt(64, 0x4530000000000000ULL))));
8948   Constant *C1 = ConstantVector::get(CV1);
8949   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8950
8951   // Load the 64-bit value into an XMM register.
8952   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8953                             Op.getOperand(0));
8954   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8955                               MachinePointerInfo::getConstantPool(),
8956                               false, false, false, 16);
8957   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8958                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8959                               CLod0);
8960
8961   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8962                               MachinePointerInfo::getConstantPool(),
8963                               false, false, false, 16);
8964   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8965   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8966   SDValue Result;
8967
8968   if (Subtarget->hasSSE3()) {
8969     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8970     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8971   } else {
8972     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8973     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8974                                            S2F, 0x4E, DAG);
8975     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8976                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8977                          Sub);
8978   }
8979
8980   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8981                      DAG.getIntPtrConstant(0));
8982 }
8983
8984 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8985 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8986                                                SelectionDAG &DAG) const {
8987   SDLoc dl(Op);
8988   // FP constant to bias correct the final result.
8989   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8990                                    MVT::f64);
8991
8992   // Load the 32-bit value into an XMM register.
8993   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8994                              Op.getOperand(0));
8995
8996   // Zero out the upper parts of the register.
8997   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8998
8999   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9000                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9001                      DAG.getIntPtrConstant(0));
9002
9003   // Or the load with the bias.
9004   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9005                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9006                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9007                                                    MVT::v2f64, Load)),
9008                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9009                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9010                                                    MVT::v2f64, Bias)));
9011   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9012                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9013                    DAG.getIntPtrConstant(0));
9014
9015   // Subtract the bias.
9016   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9017
9018   // Handle final rounding.
9019   EVT DestVT = Op.getValueType();
9020
9021   if (DestVT.bitsLT(MVT::f64))
9022     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9023                        DAG.getIntPtrConstant(0));
9024   if (DestVT.bitsGT(MVT::f64))
9025     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9026
9027   // Handle final rounding.
9028   return Sub;
9029 }
9030
9031 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9032                                                SelectionDAG &DAG) const {
9033   SDValue N0 = Op.getOperand(0);
9034   MVT SVT = N0.getSimpleValueType();
9035   SDLoc dl(Op);
9036
9037   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9038           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9039          "Custom UINT_TO_FP is not supported!");
9040
9041   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9042   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9043                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9044 }
9045
9046 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9047                                            SelectionDAG &DAG) const {
9048   SDValue N0 = Op.getOperand(0);
9049   SDLoc dl(Op);
9050
9051   if (Op.getValueType().isVector())
9052     return lowerUINT_TO_FP_vec(Op, DAG);
9053
9054   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9055   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9056   // the optimization here.
9057   if (DAG.SignBitIsZero(N0))
9058     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9059
9060   MVT SrcVT = N0.getSimpleValueType();
9061   MVT DstVT = Op.getSimpleValueType();
9062   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9063     return LowerUINT_TO_FP_i64(Op, DAG);
9064   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9065     return LowerUINT_TO_FP_i32(Op, DAG);
9066   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9067     return SDValue();
9068
9069   // Make a 64-bit buffer, and use it to build an FILD.
9070   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9071   if (SrcVT == MVT::i32) {
9072     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9073     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9074                                      getPointerTy(), StackSlot, WordOff);
9075     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9076                                   StackSlot, MachinePointerInfo(),
9077                                   false, false, 0);
9078     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9079                                   OffsetSlot, MachinePointerInfo(),
9080                                   false, false, 0);
9081     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9082     return Fild;
9083   }
9084
9085   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9086   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9087                                StackSlot, MachinePointerInfo(),
9088                                false, false, 0);
9089   // For i64 source, we need to add the appropriate power of 2 if the input
9090   // was negative.  This is the same as the optimization in
9091   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9092   // we must be careful to do the computation in x87 extended precision, not
9093   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9094   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9095   MachineMemOperand *MMO =
9096     DAG.getMachineFunction()
9097     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9098                           MachineMemOperand::MOLoad, 8, 8);
9099
9100   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9101   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9102   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9103                                          array_lengthof(Ops), MVT::i64, MMO);
9104
9105   APInt FF(32, 0x5F800000ULL);
9106
9107   // Check whether the sign bit is set.
9108   SDValue SignSet = DAG.getSetCC(dl,
9109                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9110                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9111                                  ISD::SETLT);
9112
9113   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9114   SDValue FudgePtr = DAG.getConstantPool(
9115                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9116                                          getPointerTy());
9117
9118   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9119   SDValue Zero = DAG.getIntPtrConstant(0);
9120   SDValue Four = DAG.getIntPtrConstant(4);
9121   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9122                                Zero, Four);
9123   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9124
9125   // Load the value out, extending it from f32 to f80.
9126   // FIXME: Avoid the extend by constructing the right constant pool?
9127   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9128                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9129                                  MVT::f32, false, false, 4);
9130   // Extend everything to 80 bits to force it to be done on x87.
9131   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9132   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9133 }
9134
9135 std::pair<SDValue,SDValue>
9136 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9137                                     bool IsSigned, bool IsReplace) const {
9138   SDLoc DL(Op);
9139
9140   EVT DstTy = Op.getValueType();
9141
9142   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9143     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9144     DstTy = MVT::i64;
9145   }
9146
9147   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9148          DstTy.getSimpleVT() >= MVT::i16 &&
9149          "Unknown FP_TO_INT to lower!");
9150
9151   // These are really Legal.
9152   if (DstTy == MVT::i32 &&
9153       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9154     return std::make_pair(SDValue(), SDValue());
9155   if (Subtarget->is64Bit() &&
9156       DstTy == MVT::i64 &&
9157       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9158     return std::make_pair(SDValue(), SDValue());
9159
9160   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9161   // stack slot, or into the FTOL runtime function.
9162   MachineFunction &MF = DAG.getMachineFunction();
9163   unsigned MemSize = DstTy.getSizeInBits()/8;
9164   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9165   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9166
9167   unsigned Opc;
9168   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9169     Opc = X86ISD::WIN_FTOL;
9170   else
9171     switch (DstTy.getSimpleVT().SimpleTy) {
9172     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9173     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9174     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9175     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9176     }
9177
9178   SDValue Chain = DAG.getEntryNode();
9179   SDValue Value = Op.getOperand(0);
9180   EVT TheVT = Op.getOperand(0).getValueType();
9181   // FIXME This causes a redundant load/store if the SSE-class value is already
9182   // in memory, such as if it is on the callstack.
9183   if (isScalarFPTypeInSSEReg(TheVT)) {
9184     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9185     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9186                          MachinePointerInfo::getFixedStack(SSFI),
9187                          false, false, 0);
9188     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9189     SDValue Ops[] = {
9190       Chain, StackSlot, DAG.getValueType(TheVT)
9191     };
9192
9193     MachineMemOperand *MMO =
9194       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9195                               MachineMemOperand::MOLoad, MemSize, MemSize);
9196     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9197                                     array_lengthof(Ops), DstTy, MMO);
9198     Chain = Value.getValue(1);
9199     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9200     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9201   }
9202
9203   MachineMemOperand *MMO =
9204     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9205                             MachineMemOperand::MOStore, MemSize, MemSize);
9206
9207   if (Opc != X86ISD::WIN_FTOL) {
9208     // Build the FP_TO_INT*_IN_MEM
9209     SDValue Ops[] = { Chain, Value, StackSlot };
9210     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9211                                            Ops, array_lengthof(Ops), DstTy,
9212                                            MMO);
9213     return std::make_pair(FIST, StackSlot);
9214   } else {
9215     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9216       DAG.getVTList(MVT::Other, MVT::Glue),
9217       Chain, Value);
9218     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9219       MVT::i32, ftol.getValue(1));
9220     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9221       MVT::i32, eax.getValue(2));
9222     SDValue Ops[] = { eax, edx };
9223     SDValue pair = IsReplace
9224       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9225       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9226     return std::make_pair(pair, SDValue());
9227   }
9228 }
9229
9230 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9231                               const X86Subtarget *Subtarget) {
9232   MVT VT = Op->getSimpleValueType(0);
9233   SDValue In = Op->getOperand(0);
9234   MVT InVT = In.getSimpleValueType();
9235   SDLoc dl(Op);
9236
9237   // Optimize vectors in AVX mode:
9238   //
9239   //   v8i16 -> v8i32
9240   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9241   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9242   //   Concat upper and lower parts.
9243   //
9244   //   v4i32 -> v4i64
9245   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9246   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9247   //   Concat upper and lower parts.
9248   //
9249
9250   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9251       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9252       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9253     return SDValue();
9254
9255   if (Subtarget->hasInt256())
9256     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9257
9258   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9259   SDValue Undef = DAG.getUNDEF(InVT);
9260   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9261   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9262   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9263
9264   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9265                              VT.getVectorNumElements()/2);
9266
9267   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9268   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9269
9270   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9271 }
9272
9273 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9274                                         SelectionDAG &DAG) {
9275   MVT VT = Op->getSimpleValueType(0);
9276   SDValue In = Op->getOperand(0);
9277   MVT InVT = In.getSimpleValueType();
9278   SDLoc DL(Op);
9279   unsigned int NumElts = VT.getVectorNumElements();
9280   if (NumElts != 8 && NumElts != 16)
9281     return SDValue();
9282
9283   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9284     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9285
9286   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9287   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9288   // Now we have only mask extension
9289   assert(InVT.getVectorElementType() == MVT::i1);
9290   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9291   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9292   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9293   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9294   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9295                            MachinePointerInfo::getConstantPool(),
9296                            false, false, false, Alignment);
9297
9298   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9299   if (VT.is512BitVector())
9300     return Brcst;
9301   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9302 }
9303
9304 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9305                                SelectionDAG &DAG) {
9306   if (Subtarget->hasFp256()) {
9307     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9308     if (Res.getNode())
9309       return Res;
9310   }
9311
9312   return SDValue();
9313 }
9314
9315 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9316                                 SelectionDAG &DAG) {
9317   SDLoc DL(Op);
9318   MVT VT = Op.getSimpleValueType();
9319   SDValue In = Op.getOperand(0);
9320   MVT SVT = In.getSimpleValueType();
9321
9322   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9323     return LowerZERO_EXTEND_AVX512(Op, DAG);
9324
9325   if (Subtarget->hasFp256()) {
9326     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9327     if (Res.getNode())
9328       return Res;
9329   }
9330
9331   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9332          VT.getVectorNumElements() != SVT.getVectorNumElements());
9333   return SDValue();
9334 }
9335
9336 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9337   SDLoc DL(Op);
9338   MVT VT = Op.getSimpleValueType();
9339   SDValue In = Op.getOperand(0);
9340   MVT InVT = In.getSimpleValueType();
9341
9342   if (VT == MVT::i1) {
9343     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9344            "Invalid scalar TRUNCATE operation");
9345     if (InVT == MVT::i32)
9346       return SDValue();
9347     if (InVT.getSizeInBits() == 64)
9348       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9349     else if (InVT.getSizeInBits() < 32)
9350       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9351     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9352   }
9353   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9354          "Invalid TRUNCATE operation");
9355
9356   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9357     if (VT.getVectorElementType().getSizeInBits() >=8)
9358       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9359
9360     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9361     unsigned NumElts = InVT.getVectorNumElements();
9362     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9363     if (InVT.getSizeInBits() < 512) {
9364       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9365       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9366       InVT = ExtVT;
9367     }
9368     
9369     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9370     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9371     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9372     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9373     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9374                            MachinePointerInfo::getConstantPool(),
9375                            false, false, false, Alignment);
9376     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9377     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9378     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9379   }
9380
9381   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9382     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9383     if (Subtarget->hasInt256()) {
9384       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9385       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9386       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9387                                 ShufMask);
9388       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9389                          DAG.getIntPtrConstant(0));
9390     }
9391
9392     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9393                                DAG.getIntPtrConstant(0));
9394     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9395                                DAG.getIntPtrConstant(2));
9396     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9397     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9398     static const int ShufMask[] = {0, 2, 4, 6};
9399     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9400   }
9401
9402   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9403     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9404     if (Subtarget->hasInt256()) {
9405       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9406
9407       SmallVector<SDValue,32> pshufbMask;
9408       for (unsigned i = 0; i < 2; ++i) {
9409         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9410         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9411         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9412         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9413         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9414         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9415         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9416         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9417         for (unsigned j = 0; j < 8; ++j)
9418           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9419       }
9420       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9421                                &pshufbMask[0], 32);
9422       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9423       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9424
9425       static const int ShufMask[] = {0,  2,  -1,  -1};
9426       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9427                                 &ShufMask[0]);
9428       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9429                        DAG.getIntPtrConstant(0));
9430       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9431     }
9432
9433     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9434                                DAG.getIntPtrConstant(0));
9435
9436     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9437                                DAG.getIntPtrConstant(4));
9438
9439     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9440     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9441
9442     // The PSHUFB mask:
9443     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9444                                    -1, -1, -1, -1, -1, -1, -1, -1};
9445
9446     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9447     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9448     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9449
9450     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9451     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9452
9453     // The MOVLHPS Mask:
9454     static const int ShufMask2[] = {0, 1, 4, 5};
9455     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9456     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9457   }
9458
9459   // Handle truncation of V256 to V128 using shuffles.
9460   if (!VT.is128BitVector() || !InVT.is256BitVector())
9461     return SDValue();
9462
9463   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9464
9465   unsigned NumElems = VT.getVectorNumElements();
9466   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9467
9468   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9469   // Prepare truncation shuffle mask
9470   for (unsigned i = 0; i != NumElems; ++i)
9471     MaskVec[i] = i * 2;
9472   SDValue V = DAG.getVectorShuffle(NVT, DL,
9473                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9474                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9475   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9476                      DAG.getIntPtrConstant(0));
9477 }
9478
9479 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9480                                            SelectionDAG &DAG) const {
9481   assert(!Op.getSimpleValueType().isVector());
9482
9483   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9484     /*IsSigned=*/ true, /*IsReplace=*/ false);
9485   SDValue FIST = Vals.first, StackSlot = Vals.second;
9486   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9487   if (!FIST.getNode()) return Op;
9488
9489   if (StackSlot.getNode())
9490     // Load the result.
9491     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9492                        FIST, StackSlot, MachinePointerInfo(),
9493                        false, false, false, 0);
9494
9495   // The node is the result.
9496   return FIST;
9497 }
9498
9499 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9500                                            SelectionDAG &DAG) const {
9501   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9502     /*IsSigned=*/ false, /*IsReplace=*/ false);
9503   SDValue FIST = Vals.first, StackSlot = Vals.second;
9504   assert(FIST.getNode() && "Unexpected failure");
9505
9506   if (StackSlot.getNode())
9507     // Load the result.
9508     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9509                        FIST, StackSlot, MachinePointerInfo(),
9510                        false, false, false, 0);
9511
9512   // The node is the result.
9513   return FIST;
9514 }
9515
9516 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9517   SDLoc DL(Op);
9518   MVT VT = Op.getSimpleValueType();
9519   SDValue In = Op.getOperand(0);
9520   MVT SVT = In.getSimpleValueType();
9521
9522   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9523
9524   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9525                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9526                                  In, DAG.getUNDEF(SVT)));
9527 }
9528
9529 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9530   LLVMContext *Context = DAG.getContext();
9531   SDLoc dl(Op);
9532   MVT VT = Op.getSimpleValueType();
9533   MVT EltVT = VT;
9534   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9535   if (VT.isVector()) {
9536     EltVT = VT.getVectorElementType();
9537     NumElts = VT.getVectorNumElements();
9538   }
9539   Constant *C;
9540   if (EltVT == MVT::f64)
9541     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9542                                           APInt(64, ~(1ULL << 63))));
9543   else
9544     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9545                                           APInt(32, ~(1U << 31))));
9546   C = ConstantVector::getSplat(NumElts, C);
9547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9548   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9549   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9550   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9551                              MachinePointerInfo::getConstantPool(),
9552                              false, false, false, Alignment);
9553   if (VT.isVector()) {
9554     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9555     return DAG.getNode(ISD::BITCAST, dl, VT,
9556                        DAG.getNode(ISD::AND, dl, ANDVT,
9557                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9558                                                Op.getOperand(0)),
9559                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9560   }
9561   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9562 }
9563
9564 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9565   LLVMContext *Context = DAG.getContext();
9566   SDLoc dl(Op);
9567   MVT VT = Op.getSimpleValueType();
9568   MVT EltVT = VT;
9569   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9570   if (VT.isVector()) {
9571     EltVT = VT.getVectorElementType();
9572     NumElts = VT.getVectorNumElements();
9573   }
9574   Constant *C;
9575   if (EltVT == MVT::f64)
9576     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9577                                           APInt(64, 1ULL << 63)));
9578   else
9579     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9580                                           APInt(32, 1U << 31)));
9581   C = ConstantVector::getSplat(NumElts, C);
9582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9583   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9584   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9585   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9586                              MachinePointerInfo::getConstantPool(),
9587                              false, false, false, Alignment);
9588   if (VT.isVector()) {
9589     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9590     return DAG.getNode(ISD::BITCAST, dl, VT,
9591                        DAG.getNode(ISD::XOR, dl, XORVT,
9592                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9593                                                Op.getOperand(0)),
9594                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9595   }
9596
9597   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9598 }
9599
9600 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9602   LLVMContext *Context = DAG.getContext();
9603   SDValue Op0 = Op.getOperand(0);
9604   SDValue Op1 = Op.getOperand(1);
9605   SDLoc dl(Op);
9606   MVT VT = Op.getSimpleValueType();
9607   MVT SrcVT = Op1.getSimpleValueType();
9608
9609   // If second operand is smaller, extend it first.
9610   if (SrcVT.bitsLT(VT)) {
9611     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9612     SrcVT = VT;
9613   }
9614   // And if it is bigger, shrink it first.
9615   if (SrcVT.bitsGT(VT)) {
9616     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9617     SrcVT = VT;
9618   }
9619
9620   // At this point the operands and the result should have the same
9621   // type, and that won't be f80 since that is not custom lowered.
9622
9623   // First get the sign bit of second operand.
9624   SmallVector<Constant*,4> CV;
9625   if (SrcVT == MVT::f64) {
9626     const fltSemantics &Sem = APFloat::IEEEdouble;
9627     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9628     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9629   } else {
9630     const fltSemantics &Sem = APFloat::IEEEsingle;
9631     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9632     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9633     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9634     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9635   }
9636   Constant *C = ConstantVector::get(CV);
9637   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9638   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9639                               MachinePointerInfo::getConstantPool(),
9640                               false, false, false, 16);
9641   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9642
9643   // Shift sign bit right or left if the two operands have different types.
9644   if (SrcVT.bitsGT(VT)) {
9645     // Op0 is MVT::f32, Op1 is MVT::f64.
9646     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9647     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9648                           DAG.getConstant(32, MVT::i32));
9649     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9650     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9651                           DAG.getIntPtrConstant(0));
9652   }
9653
9654   // Clear first operand sign bit.
9655   CV.clear();
9656   if (VT == MVT::f64) {
9657     const fltSemantics &Sem = APFloat::IEEEdouble;
9658     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9659                                                    APInt(64, ~(1ULL << 63)))));
9660     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9661   } else {
9662     const fltSemantics &Sem = APFloat::IEEEsingle;
9663     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9664                                                    APInt(32, ~(1U << 31)))));
9665     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9666     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9667     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9668   }
9669   C = ConstantVector::get(CV);
9670   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9671   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9672                               MachinePointerInfo::getConstantPool(),
9673                               false, false, false, 16);
9674   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9675
9676   // Or the value with the sign bit.
9677   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9678 }
9679
9680 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9681   SDValue N0 = Op.getOperand(0);
9682   SDLoc dl(Op);
9683   MVT VT = Op.getSimpleValueType();
9684
9685   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9686   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9687                                   DAG.getConstant(1, VT));
9688   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9689 }
9690
9691 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9692 //
9693 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9694                                       SelectionDAG &DAG) {
9695   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9696
9697   if (!Subtarget->hasSSE41())
9698     return SDValue();
9699
9700   if (!Op->hasOneUse())
9701     return SDValue();
9702
9703   SDNode *N = Op.getNode();
9704   SDLoc DL(N);
9705
9706   SmallVector<SDValue, 8> Opnds;
9707   DenseMap<SDValue, unsigned> VecInMap;
9708   SmallVector<SDValue, 8> VecIns;
9709   EVT VT = MVT::Other;
9710
9711   // Recognize a special case where a vector is casted into wide integer to
9712   // test all 0s.
9713   Opnds.push_back(N->getOperand(0));
9714   Opnds.push_back(N->getOperand(1));
9715
9716   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9717     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9718     // BFS traverse all OR'd operands.
9719     if (I->getOpcode() == ISD::OR) {
9720       Opnds.push_back(I->getOperand(0));
9721       Opnds.push_back(I->getOperand(1));
9722       // Re-evaluate the number of nodes to be traversed.
9723       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9724       continue;
9725     }
9726
9727     // Quit if a non-EXTRACT_VECTOR_ELT
9728     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9729       return SDValue();
9730
9731     // Quit if without a constant index.
9732     SDValue Idx = I->getOperand(1);
9733     if (!isa<ConstantSDNode>(Idx))
9734       return SDValue();
9735
9736     SDValue ExtractedFromVec = I->getOperand(0);
9737     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9738     if (M == VecInMap.end()) {
9739       VT = ExtractedFromVec.getValueType();
9740       // Quit if not 128/256-bit vector.
9741       if (!VT.is128BitVector() && !VT.is256BitVector())
9742         return SDValue();
9743       // Quit if not the same type.
9744       if (VecInMap.begin() != VecInMap.end() &&
9745           VT != VecInMap.begin()->first.getValueType())
9746         return SDValue();
9747       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9748       VecIns.push_back(ExtractedFromVec);
9749     }
9750     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9751   }
9752
9753   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9754          "Not extracted from 128-/256-bit vector.");
9755
9756   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9757
9758   for (DenseMap<SDValue, unsigned>::const_iterator
9759         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9760     // Quit if not all elements are used.
9761     if (I->second != FullMask)
9762       return SDValue();
9763   }
9764
9765   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9766
9767   // Cast all vectors into TestVT for PTEST.
9768   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9769     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9770
9771   // If more than one full vectors are evaluated, OR them first before PTEST.
9772   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9773     // Each iteration will OR 2 nodes and append the result until there is only
9774     // 1 node left, i.e. the final OR'd value of all vectors.
9775     SDValue LHS = VecIns[Slot];
9776     SDValue RHS = VecIns[Slot + 1];
9777     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9778   }
9779
9780   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9781                      VecIns.back(), VecIns.back());
9782 }
9783
9784 /// \brief return true if \c Op has a use that doesn't just read flags.
9785 static bool hasNonFlagsUse(SDValue Op) {
9786   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9787        ++UI) {
9788     SDNode *User = *UI;
9789     unsigned UOpNo = UI.getOperandNo();
9790     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9791       // Look pass truncate.
9792       UOpNo = User->use_begin().getOperandNo();
9793       User = *User->use_begin();
9794     }
9795
9796     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9797         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9798       return true;
9799   }
9800   return false;
9801 }
9802
9803 /// Emit nodes that will be selected as "test Op0,Op0", or something
9804 /// equivalent.
9805 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9806                                     SelectionDAG &DAG) const {
9807   if (Op.getValueType() == MVT::i1)
9808     // KORTEST instruction should be selected
9809     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9810                        DAG.getConstant(0, Op.getValueType()));
9811
9812   // CF and OF aren't always set the way we want. Determine which
9813   // of these we need.
9814   bool NeedCF = false;
9815   bool NeedOF = false;
9816   switch (X86CC) {
9817   default: break;
9818   case X86::COND_A: case X86::COND_AE:
9819   case X86::COND_B: case X86::COND_BE:
9820     NeedCF = true;
9821     break;
9822   case X86::COND_G: case X86::COND_GE:
9823   case X86::COND_L: case X86::COND_LE:
9824   case X86::COND_O: case X86::COND_NO:
9825     NeedOF = true;
9826     break;
9827   }
9828   // See if we can use the EFLAGS value from the operand instead of
9829   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9830   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9831   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9832     // Emit a CMP with 0, which is the TEST pattern.
9833     //if (Op.getValueType() == MVT::i1)
9834     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9835     //                     DAG.getConstant(0, MVT::i1));
9836     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9837                        DAG.getConstant(0, Op.getValueType()));
9838   }
9839   unsigned Opcode = 0;
9840   unsigned NumOperands = 0;
9841
9842   // Truncate operations may prevent the merge of the SETCC instruction
9843   // and the arithmetic instruction before it. Attempt to truncate the operands
9844   // of the arithmetic instruction and use a reduced bit-width instruction.
9845   bool NeedTruncation = false;
9846   SDValue ArithOp = Op;
9847   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9848     SDValue Arith = Op->getOperand(0);
9849     // Both the trunc and the arithmetic op need to have one user each.
9850     if (Arith->hasOneUse())
9851       switch (Arith.getOpcode()) {
9852         default: break;
9853         case ISD::ADD:
9854         case ISD::SUB:
9855         case ISD::AND:
9856         case ISD::OR:
9857         case ISD::XOR: {
9858           NeedTruncation = true;
9859           ArithOp = Arith;
9860         }
9861       }
9862   }
9863
9864   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9865   // which may be the result of a CAST.  We use the variable 'Op', which is the
9866   // non-casted variable when we check for possible users.
9867   switch (ArithOp.getOpcode()) {
9868   case ISD::ADD:
9869     // Due to an isel shortcoming, be conservative if this add is likely to be
9870     // selected as part of a load-modify-store instruction. When the root node
9871     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9872     // uses of other nodes in the match, such as the ADD in this case. This
9873     // leads to the ADD being left around and reselected, with the result being
9874     // two adds in the output.  Alas, even if none our users are stores, that
9875     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9876     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9877     // climbing the DAG back to the root, and it doesn't seem to be worth the
9878     // effort.
9879     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9880          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9881       if (UI->getOpcode() != ISD::CopyToReg &&
9882           UI->getOpcode() != ISD::SETCC &&
9883           UI->getOpcode() != ISD::STORE)
9884         goto default_case;
9885
9886     if (ConstantSDNode *C =
9887         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9888       // An add of one will be selected as an INC.
9889       if (C->getAPIntValue() == 1) {
9890         Opcode = X86ISD::INC;
9891         NumOperands = 1;
9892         break;
9893       }
9894
9895       // An add of negative one (subtract of one) will be selected as a DEC.
9896       if (C->getAPIntValue().isAllOnesValue()) {
9897         Opcode = X86ISD::DEC;
9898         NumOperands = 1;
9899         break;
9900       }
9901     }
9902
9903     // Otherwise use a regular EFLAGS-setting add.
9904     Opcode = X86ISD::ADD;
9905     NumOperands = 2;
9906     break;
9907   case ISD::SHL:
9908   case ISD::SRL:
9909     // If we have a constant logical shift that's only used in a comparison
9910     // against zero turn it into an equivalent AND. This allows turning it into
9911     // a TEST instruction later.
9912     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9913         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9914       EVT VT = Op.getValueType();
9915       unsigned BitWidth = VT.getSizeInBits();
9916       unsigned ShAmt = Op->getConstantOperandVal(1);
9917       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9918         break;
9919       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9920                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9921                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9922       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9923         break;
9924       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9925                                 DAG.getConstant(Mask, VT));
9926       DAG.ReplaceAllUsesWith(Op, New);
9927       Op = New;
9928     }
9929     break;
9930
9931   case ISD::AND:
9932     // If the primary and result isn't used, don't bother using X86ISD::AND,
9933     // because a TEST instruction will be better.
9934     if (!hasNonFlagsUse(Op))
9935       break;
9936     // FALL THROUGH
9937   case ISD::SUB:
9938   case ISD::OR:
9939   case ISD::XOR:
9940     // Due to the ISEL shortcoming noted above, be conservative if this op is
9941     // likely to be selected as part of a load-modify-store instruction.
9942     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9943            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9944       if (UI->getOpcode() == ISD::STORE)
9945         goto default_case;
9946
9947     // Otherwise use a regular EFLAGS-setting instruction.
9948     switch (ArithOp.getOpcode()) {
9949     default: llvm_unreachable("unexpected operator!");
9950     case ISD::SUB: Opcode = X86ISD::SUB; break;
9951     case ISD::XOR: Opcode = X86ISD::XOR; break;
9952     case ISD::AND: Opcode = X86ISD::AND; break;
9953     case ISD::OR: {
9954       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9955         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9956         if (EFLAGS.getNode())
9957           return EFLAGS;
9958       }
9959       Opcode = X86ISD::OR;
9960       break;
9961     }
9962     }
9963
9964     NumOperands = 2;
9965     break;
9966   case X86ISD::ADD:
9967   case X86ISD::SUB:
9968   case X86ISD::INC:
9969   case X86ISD::DEC:
9970   case X86ISD::OR:
9971   case X86ISD::XOR:
9972   case X86ISD::AND:
9973     return SDValue(Op.getNode(), 1);
9974   default:
9975   default_case:
9976     break;
9977   }
9978
9979   // If we found that truncation is beneficial, perform the truncation and
9980   // update 'Op'.
9981   if (NeedTruncation) {
9982     EVT VT = Op.getValueType();
9983     SDValue WideVal = Op->getOperand(0);
9984     EVT WideVT = WideVal.getValueType();
9985     unsigned ConvertedOp = 0;
9986     // Use a target machine opcode to prevent further DAGCombine
9987     // optimizations that may separate the arithmetic operations
9988     // from the setcc node.
9989     switch (WideVal.getOpcode()) {
9990       default: break;
9991       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9992       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9993       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9994       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9995       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9996     }
9997
9998     if (ConvertedOp) {
9999       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10000       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10001         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10002         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10003         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10004       }
10005     }
10006   }
10007
10008   if (Opcode == 0)
10009     // Emit a CMP with 0, which is the TEST pattern.
10010     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10011                        DAG.getConstant(0, Op.getValueType()));
10012
10013   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10014   SmallVector<SDValue, 4> Ops;
10015   for (unsigned i = 0; i != NumOperands; ++i)
10016     Ops.push_back(Op.getOperand(i));
10017
10018   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
10019   DAG.ReplaceAllUsesWith(Op, New);
10020   return SDValue(New.getNode(), 1);
10021 }
10022
10023 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10024 /// equivalent.
10025 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10026                                    SDLoc dl, SelectionDAG &DAG) const {
10027   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10028     if (C->getAPIntValue() == 0)
10029       return EmitTest(Op0, X86CC, dl, DAG);
10030
10031      if (Op0.getValueType() == MVT::i1)
10032        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10033   }
10034  
10035   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10036        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10037     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10038     // This avoids subregister aliasing issues. Keep the smaller reference 
10039     // if we're optimizing for size, however, as that'll allow better folding 
10040     // of memory operations.
10041     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10042         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10043              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10044         !Subtarget->isAtom()) {
10045       unsigned ExtendOp =
10046           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10047       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10048       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10049     }
10050     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10051     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10052     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10053                               Op0, Op1);
10054     return SDValue(Sub.getNode(), 1);
10055   }
10056   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10057 }
10058
10059 /// Convert a comparison if required by the subtarget.
10060 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10061                                                  SelectionDAG &DAG) const {
10062   // If the subtarget does not support the FUCOMI instruction, floating-point
10063   // comparisons have to be converted.
10064   if (Subtarget->hasCMov() ||
10065       Cmp.getOpcode() != X86ISD::CMP ||
10066       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10067       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10068     return Cmp;
10069
10070   // The instruction selector will select an FUCOM instruction instead of
10071   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10072   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10073   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10074   SDLoc dl(Cmp);
10075   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10076   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10077   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10078                             DAG.getConstant(8, MVT::i8));
10079   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10080   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10081 }
10082
10083 static bool isAllOnes(SDValue V) {
10084   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10085   return C && C->isAllOnesValue();
10086 }
10087
10088 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10089 /// if it's possible.
10090 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10091                                      SDLoc dl, SelectionDAG &DAG) const {
10092   SDValue Op0 = And.getOperand(0);
10093   SDValue Op1 = And.getOperand(1);
10094   if (Op0.getOpcode() == ISD::TRUNCATE)
10095     Op0 = Op0.getOperand(0);
10096   if (Op1.getOpcode() == ISD::TRUNCATE)
10097     Op1 = Op1.getOperand(0);
10098
10099   SDValue LHS, RHS;
10100   if (Op1.getOpcode() == ISD::SHL)
10101     std::swap(Op0, Op1);
10102   if (Op0.getOpcode() == ISD::SHL) {
10103     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10104       if (And00C->getZExtValue() == 1) {
10105         // If we looked past a truncate, check that it's only truncating away
10106         // known zeros.
10107         unsigned BitWidth = Op0.getValueSizeInBits();
10108         unsigned AndBitWidth = And.getValueSizeInBits();
10109         if (BitWidth > AndBitWidth) {
10110           APInt Zeros, Ones;
10111           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10112           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10113             return SDValue();
10114         }
10115         LHS = Op1;
10116         RHS = Op0.getOperand(1);
10117       }
10118   } else if (Op1.getOpcode() == ISD::Constant) {
10119     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10120     uint64_t AndRHSVal = AndRHS->getZExtValue();
10121     SDValue AndLHS = Op0;
10122
10123     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10124       LHS = AndLHS.getOperand(0);
10125       RHS = AndLHS.getOperand(1);
10126     }
10127
10128     // Use BT if the immediate can't be encoded in a TEST instruction.
10129     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10130       LHS = AndLHS;
10131       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10132     }
10133   }
10134
10135   if (LHS.getNode()) {
10136     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10137     // instruction.  Since the shift amount is in-range-or-undefined, we know
10138     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10139     // the encoding for the i16 version is larger than the i32 version.
10140     // Also promote i16 to i32 for performance / code size reason.
10141     if (LHS.getValueType() == MVT::i8 ||
10142         LHS.getValueType() == MVT::i16)
10143       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10144
10145     // If the operand types disagree, extend the shift amount to match.  Since
10146     // BT ignores high bits (like shifts) we can use anyextend.
10147     if (LHS.getValueType() != RHS.getValueType())
10148       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10149
10150     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10151     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10152     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10153                        DAG.getConstant(Cond, MVT::i8), BT);
10154   }
10155
10156   return SDValue();
10157 }
10158
10159 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10160 /// mask CMPs.
10161 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10162                               SDValue &Op1) {
10163   unsigned SSECC;
10164   bool Swap = false;
10165
10166   // SSE Condition code mapping:
10167   //  0 - EQ
10168   //  1 - LT
10169   //  2 - LE
10170   //  3 - UNORD
10171   //  4 - NEQ
10172   //  5 - NLT
10173   //  6 - NLE
10174   //  7 - ORD
10175   switch (SetCCOpcode) {
10176   default: llvm_unreachable("Unexpected SETCC condition");
10177   case ISD::SETOEQ:
10178   case ISD::SETEQ:  SSECC = 0; break;
10179   case ISD::SETOGT:
10180   case ISD::SETGT:  Swap = true; // Fallthrough
10181   case ISD::SETLT:
10182   case ISD::SETOLT: SSECC = 1; break;
10183   case ISD::SETOGE:
10184   case ISD::SETGE:  Swap = true; // Fallthrough
10185   case ISD::SETLE:
10186   case ISD::SETOLE: SSECC = 2; break;
10187   case ISD::SETUO:  SSECC = 3; break;
10188   case ISD::SETUNE:
10189   case ISD::SETNE:  SSECC = 4; break;
10190   case ISD::SETULE: Swap = true; // Fallthrough
10191   case ISD::SETUGE: SSECC = 5; break;
10192   case ISD::SETULT: Swap = true; // Fallthrough
10193   case ISD::SETUGT: SSECC = 6; break;
10194   case ISD::SETO:   SSECC = 7; break;
10195   case ISD::SETUEQ:
10196   case ISD::SETONE: SSECC = 8; break;
10197   }
10198   if (Swap)
10199     std::swap(Op0, Op1);
10200
10201   return SSECC;
10202 }
10203
10204 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10205 // ones, and then concatenate the result back.
10206 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10207   MVT VT = Op.getSimpleValueType();
10208
10209   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10210          "Unsupported value type for operation");
10211
10212   unsigned NumElems = VT.getVectorNumElements();
10213   SDLoc dl(Op);
10214   SDValue CC = Op.getOperand(2);
10215
10216   // Extract the LHS vectors
10217   SDValue LHS = Op.getOperand(0);
10218   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10219   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10220
10221   // Extract the RHS vectors
10222   SDValue RHS = Op.getOperand(1);
10223   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10224   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10225
10226   // Issue the operation on the smaller types and concatenate the result back
10227   MVT EltVT = VT.getVectorElementType();
10228   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10229   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10230                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10231                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10232 }
10233
10234 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10235                                      const X86Subtarget *Subtarget) {
10236   SDValue Op0 = Op.getOperand(0);
10237   SDValue Op1 = Op.getOperand(1);
10238   SDValue CC = Op.getOperand(2);
10239   MVT VT = Op.getSimpleValueType();
10240   SDLoc dl(Op);
10241
10242   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10243          Op.getValueType().getScalarType() == MVT::i1 &&
10244          "Cannot set masked compare for this operation");
10245
10246   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10247   unsigned  Opc = 0;
10248   bool Unsigned = false;
10249   bool Swap = false;
10250   unsigned SSECC;
10251   switch (SetCCOpcode) {
10252   default: llvm_unreachable("Unexpected SETCC condition");
10253   case ISD::SETNE:  SSECC = 4; break;
10254   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10255   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10256   case ISD::SETLT:  Swap = true; //fall-through
10257   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10258   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10259   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10260   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10261   case ISD::SETULE: Unsigned = true; //fall-through
10262   case ISD::SETLE:  SSECC = 2; break;
10263   }
10264
10265   if (Swap)
10266     std::swap(Op0, Op1);
10267   if (Opc)
10268     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10269   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10270   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10271                      DAG.getConstant(SSECC, MVT::i8));
10272 }
10273
10274 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10275 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10276 /// return an empty value.
10277 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10278 {
10279   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10280   if (!BV)
10281     return SDValue();
10282
10283   MVT VT = Op1.getSimpleValueType();
10284   MVT EVT = VT.getVectorElementType();
10285   unsigned n = VT.getVectorNumElements();
10286   SmallVector<SDValue, 8> ULTOp1;
10287
10288   for (unsigned i = 0; i < n; ++i) {
10289     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10290     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10291       return SDValue();
10292
10293     // Avoid underflow.
10294     APInt Val = Elt->getAPIntValue();
10295     if (Val == 0)
10296       return SDValue();
10297
10298     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10299   }
10300
10301   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10302 }
10303
10304 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10305                            SelectionDAG &DAG) {
10306   SDValue Op0 = Op.getOperand(0);
10307   SDValue Op1 = Op.getOperand(1);
10308   SDValue CC = Op.getOperand(2);
10309   MVT VT = Op.getSimpleValueType();
10310   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10311   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10312   SDLoc dl(Op);
10313
10314   if (isFP) {
10315 #ifndef NDEBUG
10316     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10317     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10318 #endif
10319
10320     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10321     unsigned Opc = X86ISD::CMPP;
10322     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10323       assert(VT.getVectorNumElements() <= 16);
10324       Opc = X86ISD::CMPM;
10325     }
10326     // In the two special cases we can't handle, emit two comparisons.
10327     if (SSECC == 8) {
10328       unsigned CC0, CC1;
10329       unsigned CombineOpc;
10330       if (SetCCOpcode == ISD::SETUEQ) {
10331         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10332       } else {
10333         assert(SetCCOpcode == ISD::SETONE);
10334         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10335       }
10336
10337       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10338                                  DAG.getConstant(CC0, MVT::i8));
10339       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10340                                  DAG.getConstant(CC1, MVT::i8));
10341       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10342     }
10343     // Handle all other FP comparisons here.
10344     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10345                        DAG.getConstant(SSECC, MVT::i8));
10346   }
10347
10348   // Break 256-bit integer vector compare into smaller ones.
10349   if (VT.is256BitVector() && !Subtarget->hasInt256())
10350     return Lower256IntVSETCC(Op, DAG);
10351
10352   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10353   EVT OpVT = Op1.getValueType();
10354   if (Subtarget->hasAVX512()) {
10355     if (Op1.getValueType().is512BitVector() ||
10356         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10357       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10358
10359     // In AVX-512 architecture setcc returns mask with i1 elements,
10360     // But there is no compare instruction for i8 and i16 elements.
10361     // We are not talking about 512-bit operands in this case, these
10362     // types are illegal.
10363     if (MaskResult &&
10364         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10365          OpVT.getVectorElementType().getSizeInBits() >= 8))
10366       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10367                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10368   }
10369
10370   // We are handling one of the integer comparisons here.  Since SSE only has
10371   // GT and EQ comparisons for integer, swapping operands and multiple
10372   // operations may be required for some comparisons.
10373   unsigned Opc;
10374   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10375   bool Subus = false;
10376
10377   switch (SetCCOpcode) {
10378   default: llvm_unreachable("Unexpected SETCC condition");
10379   case ISD::SETNE:  Invert = true;
10380   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10381   case ISD::SETLT:  Swap = true;
10382   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10383   case ISD::SETGE:  Swap = true;
10384   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10385                     Invert = true; break;
10386   case ISD::SETULT: Swap = true;
10387   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10388                     FlipSigns = true; break;
10389   case ISD::SETUGE: Swap = true;
10390   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10391                     FlipSigns = true; Invert = true; break;
10392   }
10393
10394   // Special case: Use min/max operations for SETULE/SETUGE
10395   MVT VET = VT.getVectorElementType();
10396   bool hasMinMax =
10397        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10398     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10399
10400   if (hasMinMax) {
10401     switch (SetCCOpcode) {
10402     default: break;
10403     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10404     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10405     }
10406
10407     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10408   }
10409
10410   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10411   if (!MinMax && hasSubus) {
10412     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10413     // Op0 u<= Op1:
10414     //   t = psubus Op0, Op1
10415     //   pcmpeq t, <0..0>
10416     switch (SetCCOpcode) {
10417     default: break;
10418     case ISD::SETULT: {
10419       // If the comparison is against a constant we can turn this into a
10420       // setule.  With psubus, setule does not require a swap.  This is
10421       // beneficial because the constant in the register is no longer
10422       // destructed as the destination so it can be hoisted out of a loop.
10423       // Only do this pre-AVX since vpcmp* is no longer destructive.
10424       if (Subtarget->hasAVX())
10425         break;
10426       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10427       if (ULEOp1.getNode()) {
10428         Op1 = ULEOp1;
10429         Subus = true; Invert = false; Swap = false;
10430       }
10431       break;
10432     }
10433     // Psubus is better than flip-sign because it requires no inversion.
10434     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10435     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10436     }
10437
10438     if (Subus) {
10439       Opc = X86ISD::SUBUS;
10440       FlipSigns = false;
10441     }
10442   }
10443
10444   if (Swap)
10445     std::swap(Op0, Op1);
10446
10447   // Check that the operation in question is available (most are plain SSE2,
10448   // but PCMPGTQ and PCMPEQQ have different requirements).
10449   if (VT == MVT::v2i64) {
10450     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10451       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10452
10453       // First cast everything to the right type.
10454       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10455       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10456
10457       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10458       // bits of the inputs before performing those operations. The lower
10459       // compare is always unsigned.
10460       SDValue SB;
10461       if (FlipSigns) {
10462         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10463       } else {
10464         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10465         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10466         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10467                          Sign, Zero, Sign, Zero);
10468       }
10469       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10470       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10471
10472       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10473       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10474       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10475
10476       // Create masks for only the low parts/high parts of the 64 bit integers.
10477       static const int MaskHi[] = { 1, 1, 3, 3 };
10478       static const int MaskLo[] = { 0, 0, 2, 2 };
10479       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10480       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10481       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10482
10483       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10484       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10485
10486       if (Invert)
10487         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10488
10489       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10490     }
10491
10492     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10493       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10494       // pcmpeqd + pshufd + pand.
10495       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10496
10497       // First cast everything to the right type.
10498       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10499       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10500
10501       // Do the compare.
10502       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10503
10504       // Make sure the lower and upper halves are both all-ones.
10505       static const int Mask[] = { 1, 0, 3, 2 };
10506       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10507       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10508
10509       if (Invert)
10510         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10511
10512       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10513     }
10514   }
10515
10516   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10517   // bits of the inputs before performing those operations.
10518   if (FlipSigns) {
10519     EVT EltVT = VT.getVectorElementType();
10520     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10521     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10522     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10523   }
10524
10525   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10526
10527   // If the logical-not of the result is required, perform that now.
10528   if (Invert)
10529     Result = DAG.getNOT(dl, Result, VT);
10530
10531   if (MinMax)
10532     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10533
10534   if (Subus)
10535     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10536                          getZeroVector(VT, Subtarget, DAG, dl));
10537
10538   return Result;
10539 }
10540
10541 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10542
10543   MVT VT = Op.getSimpleValueType();
10544
10545   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10546
10547   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10548          && "SetCC type must be 8-bit or 1-bit integer");
10549   SDValue Op0 = Op.getOperand(0);
10550   SDValue Op1 = Op.getOperand(1);
10551   SDLoc dl(Op);
10552   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10553
10554   // Optimize to BT if possible.
10555   // Lower (X & (1 << N)) == 0 to BT(X, N).
10556   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10557   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10558   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10559       Op1.getOpcode() == ISD::Constant &&
10560       cast<ConstantSDNode>(Op1)->isNullValue() &&
10561       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10562     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10563     if (NewSetCC.getNode())
10564       return NewSetCC;
10565   }
10566
10567   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10568   // these.
10569   if (Op1.getOpcode() == ISD::Constant &&
10570       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10571        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10572       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10573
10574     // If the input is a setcc, then reuse the input setcc or use a new one with
10575     // the inverted condition.
10576     if (Op0.getOpcode() == X86ISD::SETCC) {
10577       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10578       bool Invert = (CC == ISD::SETNE) ^
10579         cast<ConstantSDNode>(Op1)->isNullValue();
10580       if (!Invert)
10581         return Op0;
10582
10583       CCode = X86::GetOppositeBranchCondition(CCode);
10584       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10585                                   DAG.getConstant(CCode, MVT::i8),
10586                                   Op0.getOperand(1));
10587       if (VT == MVT::i1)
10588         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10589       return SetCC;
10590     }
10591   }
10592   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10593       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10594       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10595
10596     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10597     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10598   }
10599
10600   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10601   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10602   if (X86CC == X86::COND_INVALID)
10603     return SDValue();
10604
10605   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10606   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10607   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10608                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10609   if (VT == MVT::i1)
10610     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10611   return SetCC;
10612 }
10613
10614 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10615 static bool isX86LogicalCmp(SDValue Op) {
10616   unsigned Opc = Op.getNode()->getOpcode();
10617   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10618       Opc == X86ISD::SAHF)
10619     return true;
10620   if (Op.getResNo() == 1 &&
10621       (Opc == X86ISD::ADD ||
10622        Opc == X86ISD::SUB ||
10623        Opc == X86ISD::ADC ||
10624        Opc == X86ISD::SBB ||
10625        Opc == X86ISD::SMUL ||
10626        Opc == X86ISD::UMUL ||
10627        Opc == X86ISD::INC ||
10628        Opc == X86ISD::DEC ||
10629        Opc == X86ISD::OR ||
10630        Opc == X86ISD::XOR ||
10631        Opc == X86ISD::AND))
10632     return true;
10633
10634   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10635     return true;
10636
10637   return false;
10638 }
10639
10640 static bool isZero(SDValue V) {
10641   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10642   return C && C->isNullValue();
10643 }
10644
10645 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10646   if (V.getOpcode() != ISD::TRUNCATE)
10647     return false;
10648
10649   SDValue VOp0 = V.getOperand(0);
10650   unsigned InBits = VOp0.getValueSizeInBits();
10651   unsigned Bits = V.getValueSizeInBits();
10652   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10653 }
10654
10655 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10656   bool addTest = true;
10657   SDValue Cond  = Op.getOperand(0);
10658   SDValue Op1 = Op.getOperand(1);
10659   SDValue Op2 = Op.getOperand(2);
10660   SDLoc DL(Op);
10661   EVT VT = Op1.getValueType();
10662   SDValue CC;
10663
10664   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10665   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10666   // sequence later on.
10667   if (Cond.getOpcode() == ISD::SETCC &&
10668       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10669        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10670       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10671     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10672     int SSECC = translateX86FSETCC(
10673         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10674
10675     if (SSECC != 8) {
10676       if (Subtarget->hasAVX512()) {
10677         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10678                                   DAG.getConstant(SSECC, MVT::i8));
10679         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10680       }
10681       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10682                                 DAG.getConstant(SSECC, MVT::i8));
10683       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10684       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10685       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10686     }
10687   }
10688
10689   if (Cond.getOpcode() == ISD::SETCC) {
10690     SDValue NewCond = LowerSETCC(Cond, DAG);
10691     if (NewCond.getNode())
10692       Cond = NewCond;
10693   }
10694
10695   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10696   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10697   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10698   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10699   if (Cond.getOpcode() == X86ISD::SETCC &&
10700       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10701       isZero(Cond.getOperand(1).getOperand(1))) {
10702     SDValue Cmp = Cond.getOperand(1);
10703
10704     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10705
10706     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10707         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10708       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10709
10710       SDValue CmpOp0 = Cmp.getOperand(0);
10711       // Apply further optimizations for special cases
10712       // (select (x != 0), -1, 0) -> neg & sbb
10713       // (select (x == 0), 0, -1) -> neg & sbb
10714       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10715         if (YC->isNullValue() &&
10716             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10717           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10718           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10719                                     DAG.getConstant(0, CmpOp0.getValueType()),
10720                                     CmpOp0);
10721           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10722                                     DAG.getConstant(X86::COND_B, MVT::i8),
10723                                     SDValue(Neg.getNode(), 1));
10724           return Res;
10725         }
10726
10727       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10728                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10729       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10730
10731       SDValue Res =   // Res = 0 or -1.
10732         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10733                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10734
10735       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10736         Res = DAG.getNOT(DL, Res, Res.getValueType());
10737
10738       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10739       if (!N2C || !N2C->isNullValue())
10740         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10741       return Res;
10742     }
10743   }
10744
10745   // Look past (and (setcc_carry (cmp ...)), 1).
10746   if (Cond.getOpcode() == ISD::AND &&
10747       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10748     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10749     if (C && C->getAPIntValue() == 1)
10750       Cond = Cond.getOperand(0);
10751   }
10752
10753   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10754   // setting operand in place of the X86ISD::SETCC.
10755   unsigned CondOpcode = Cond.getOpcode();
10756   if (CondOpcode == X86ISD::SETCC ||
10757       CondOpcode == X86ISD::SETCC_CARRY) {
10758     CC = Cond.getOperand(0);
10759
10760     SDValue Cmp = Cond.getOperand(1);
10761     unsigned Opc = Cmp.getOpcode();
10762     MVT VT = Op.getSimpleValueType();
10763
10764     bool IllegalFPCMov = false;
10765     if (VT.isFloatingPoint() && !VT.isVector() &&
10766         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10767       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10768
10769     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10770         Opc == X86ISD::BT) { // FIXME
10771       Cond = Cmp;
10772       addTest = false;
10773     }
10774   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10775              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10776              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10777               Cond.getOperand(0).getValueType() != MVT::i8)) {
10778     SDValue LHS = Cond.getOperand(0);
10779     SDValue RHS = Cond.getOperand(1);
10780     unsigned X86Opcode;
10781     unsigned X86Cond;
10782     SDVTList VTs;
10783     switch (CondOpcode) {
10784     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10785     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10786     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10787     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10788     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10789     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10790     default: llvm_unreachable("unexpected overflowing operator");
10791     }
10792     if (CondOpcode == ISD::UMULO)
10793       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10794                           MVT::i32);
10795     else
10796       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10797
10798     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10799
10800     if (CondOpcode == ISD::UMULO)
10801       Cond = X86Op.getValue(2);
10802     else
10803       Cond = X86Op.getValue(1);
10804
10805     CC = DAG.getConstant(X86Cond, MVT::i8);
10806     addTest = false;
10807   }
10808
10809   if (addTest) {
10810     // Look pass the truncate if the high bits are known zero.
10811     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10812         Cond = Cond.getOperand(0);
10813
10814     // We know the result of AND is compared against zero. Try to match
10815     // it to BT.
10816     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10817       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10818       if (NewSetCC.getNode()) {
10819         CC = NewSetCC.getOperand(0);
10820         Cond = NewSetCC.getOperand(1);
10821         addTest = false;
10822       }
10823     }
10824   }
10825
10826   if (addTest) {
10827     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10828     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10829   }
10830
10831   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10832   // a <  b ?  0 : -1 -> RES = setcc_carry
10833   // a >= b ? -1 :  0 -> RES = setcc_carry
10834   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10835   if (Cond.getOpcode() == X86ISD::SUB) {
10836     Cond = ConvertCmpIfNecessary(Cond, DAG);
10837     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10838
10839     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10840         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10841       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10842                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10843       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10844         return DAG.getNOT(DL, Res, Res.getValueType());
10845       return Res;
10846     }
10847   }
10848
10849   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10850   // widen the cmov and push the truncate through. This avoids introducing a new
10851   // branch during isel and doesn't add any extensions.
10852   if (Op.getValueType() == MVT::i8 &&
10853       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10854     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10855     if (T1.getValueType() == T2.getValueType() &&
10856         // Blacklist CopyFromReg to avoid partial register stalls.
10857         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10858       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10859       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10860       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10861     }
10862   }
10863
10864   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10865   // condition is true.
10866   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10867   SDValue Ops[] = { Op2, Op1, CC, Cond };
10868   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10869 }
10870
10871 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10872   MVT VT = Op->getSimpleValueType(0);
10873   SDValue In = Op->getOperand(0);
10874   MVT InVT = In.getSimpleValueType();
10875   SDLoc dl(Op);
10876
10877   unsigned int NumElts = VT.getVectorNumElements();
10878   if (NumElts != 8 && NumElts != 16)
10879     return SDValue();
10880
10881   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10882     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10883
10884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10885   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10886
10887   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10888   Constant *C = ConstantInt::get(*DAG.getContext(),
10889     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10890
10891   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10892   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10893   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10894                           MachinePointerInfo::getConstantPool(),
10895                           false, false, false, Alignment);
10896   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10897   if (VT.is512BitVector())
10898     return Brcst;
10899   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10900 }
10901
10902 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10903                                 SelectionDAG &DAG) {
10904   MVT VT = Op->getSimpleValueType(0);
10905   SDValue In = Op->getOperand(0);
10906   MVT InVT = In.getSimpleValueType();
10907   SDLoc dl(Op);
10908
10909   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10910     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10911
10912   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10913       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10914       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10915     return SDValue();
10916
10917   if (Subtarget->hasInt256())
10918     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10919
10920   // Optimize vectors in AVX mode
10921   // Sign extend  v8i16 to v8i32 and
10922   //              v4i32 to v4i64
10923   //
10924   // Divide input vector into two parts
10925   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10926   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10927   // concat the vectors to original VT
10928
10929   unsigned NumElems = InVT.getVectorNumElements();
10930   SDValue Undef = DAG.getUNDEF(InVT);
10931
10932   SmallVector<int,8> ShufMask1(NumElems, -1);
10933   for (unsigned i = 0; i != NumElems/2; ++i)
10934     ShufMask1[i] = i;
10935
10936   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10937
10938   SmallVector<int,8> ShufMask2(NumElems, -1);
10939   for (unsigned i = 0; i != NumElems/2; ++i)
10940     ShufMask2[i] = i + NumElems/2;
10941
10942   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10943
10944   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10945                                 VT.getVectorNumElements()/2);
10946
10947   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10948   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10949
10950   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10951 }
10952
10953 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10954 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10955 // from the AND / OR.
10956 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10957   Opc = Op.getOpcode();
10958   if (Opc != ISD::OR && Opc != ISD::AND)
10959     return false;
10960   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10961           Op.getOperand(0).hasOneUse() &&
10962           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10963           Op.getOperand(1).hasOneUse());
10964 }
10965
10966 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10967 // 1 and that the SETCC node has a single use.
10968 static bool isXor1OfSetCC(SDValue Op) {
10969   if (Op.getOpcode() != ISD::XOR)
10970     return false;
10971   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10972   if (N1C && N1C->getAPIntValue() == 1) {
10973     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10974       Op.getOperand(0).hasOneUse();
10975   }
10976   return false;
10977 }
10978
10979 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10980   bool addTest = true;
10981   SDValue Chain = Op.getOperand(0);
10982   SDValue Cond  = Op.getOperand(1);
10983   SDValue Dest  = Op.getOperand(2);
10984   SDLoc dl(Op);
10985   SDValue CC;
10986   bool Inverted = false;
10987
10988   if (Cond.getOpcode() == ISD::SETCC) {
10989     // Check for setcc([su]{add,sub,mul}o == 0).
10990     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10991         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10992         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10993         Cond.getOperand(0).getResNo() == 1 &&
10994         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10995          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10996          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10997          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10998          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10999          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11000       Inverted = true;
11001       Cond = Cond.getOperand(0);
11002     } else {
11003       SDValue NewCond = LowerSETCC(Cond, DAG);
11004       if (NewCond.getNode())
11005         Cond = NewCond;
11006     }
11007   }
11008 #if 0
11009   // FIXME: LowerXALUO doesn't handle these!!
11010   else if (Cond.getOpcode() == X86ISD::ADD  ||
11011            Cond.getOpcode() == X86ISD::SUB  ||
11012            Cond.getOpcode() == X86ISD::SMUL ||
11013            Cond.getOpcode() == X86ISD::UMUL)
11014     Cond = LowerXALUO(Cond, DAG);
11015 #endif
11016
11017   // Look pass (and (setcc_carry (cmp ...)), 1).
11018   if (Cond.getOpcode() == ISD::AND &&
11019       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11020     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11021     if (C && C->getAPIntValue() == 1)
11022       Cond = Cond.getOperand(0);
11023   }
11024
11025   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11026   // setting operand in place of the X86ISD::SETCC.
11027   unsigned CondOpcode = Cond.getOpcode();
11028   if (CondOpcode == X86ISD::SETCC ||
11029       CondOpcode == X86ISD::SETCC_CARRY) {
11030     CC = Cond.getOperand(0);
11031
11032     SDValue Cmp = Cond.getOperand(1);
11033     unsigned Opc = Cmp.getOpcode();
11034     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11035     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11036       Cond = Cmp;
11037       addTest = false;
11038     } else {
11039       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11040       default: break;
11041       case X86::COND_O:
11042       case X86::COND_B:
11043         // These can only come from an arithmetic instruction with overflow,
11044         // e.g. SADDO, UADDO.
11045         Cond = Cond.getNode()->getOperand(1);
11046         addTest = false;
11047         break;
11048       }
11049     }
11050   }
11051   CondOpcode = Cond.getOpcode();
11052   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11053       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11054       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11055        Cond.getOperand(0).getValueType() != MVT::i8)) {
11056     SDValue LHS = Cond.getOperand(0);
11057     SDValue RHS = Cond.getOperand(1);
11058     unsigned X86Opcode;
11059     unsigned X86Cond;
11060     SDVTList VTs;
11061     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11062     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11063     // X86ISD::INC).
11064     switch (CondOpcode) {
11065     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11066     case ISD::SADDO:
11067       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11068         if (C->isOne()) {
11069           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11070           break;
11071         }
11072       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11073     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11074     case ISD::SSUBO:
11075       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11076         if (C->isOne()) {
11077           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11078           break;
11079         }
11080       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11081     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11082     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11083     default: llvm_unreachable("unexpected overflowing operator");
11084     }
11085     if (Inverted)
11086       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11087     if (CondOpcode == ISD::UMULO)
11088       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11089                           MVT::i32);
11090     else
11091       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11092
11093     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11094
11095     if (CondOpcode == ISD::UMULO)
11096       Cond = X86Op.getValue(2);
11097     else
11098       Cond = X86Op.getValue(1);
11099
11100     CC = DAG.getConstant(X86Cond, MVT::i8);
11101     addTest = false;
11102   } else {
11103     unsigned CondOpc;
11104     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11105       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11106       if (CondOpc == ISD::OR) {
11107         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11108         // two branches instead of an explicit OR instruction with a
11109         // separate test.
11110         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11111             isX86LogicalCmp(Cmp)) {
11112           CC = Cond.getOperand(0).getOperand(0);
11113           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11114                               Chain, Dest, CC, Cmp);
11115           CC = Cond.getOperand(1).getOperand(0);
11116           Cond = Cmp;
11117           addTest = false;
11118         }
11119       } else { // ISD::AND
11120         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11121         // two branches instead of an explicit AND instruction with a
11122         // separate test. However, we only do this if this block doesn't
11123         // have a fall-through edge, because this requires an explicit
11124         // jmp when the condition is false.
11125         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11126             isX86LogicalCmp(Cmp) &&
11127             Op.getNode()->hasOneUse()) {
11128           X86::CondCode CCode =
11129             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11130           CCode = X86::GetOppositeBranchCondition(CCode);
11131           CC = DAG.getConstant(CCode, MVT::i8);
11132           SDNode *User = *Op.getNode()->use_begin();
11133           // Look for an unconditional branch following this conditional branch.
11134           // We need this because we need to reverse the successors in order
11135           // to implement FCMP_OEQ.
11136           if (User->getOpcode() == ISD::BR) {
11137             SDValue FalseBB = User->getOperand(1);
11138             SDNode *NewBR =
11139               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11140             assert(NewBR == User);
11141             (void)NewBR;
11142             Dest = FalseBB;
11143
11144             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11145                                 Chain, Dest, CC, Cmp);
11146             X86::CondCode CCode =
11147               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11148             CCode = X86::GetOppositeBranchCondition(CCode);
11149             CC = DAG.getConstant(CCode, MVT::i8);
11150             Cond = Cmp;
11151             addTest = false;
11152           }
11153         }
11154       }
11155     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11156       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11157       // It should be transformed during dag combiner except when the condition
11158       // is set by a arithmetics with overflow node.
11159       X86::CondCode CCode =
11160         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11161       CCode = X86::GetOppositeBranchCondition(CCode);
11162       CC = DAG.getConstant(CCode, MVT::i8);
11163       Cond = Cond.getOperand(0).getOperand(1);
11164       addTest = false;
11165     } else if (Cond.getOpcode() == ISD::SETCC &&
11166                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11167       // For FCMP_OEQ, we can emit
11168       // two branches instead of an explicit AND instruction with a
11169       // separate test. However, we only do this if this block doesn't
11170       // have a fall-through edge, because this requires an explicit
11171       // jmp when the condition is false.
11172       if (Op.getNode()->hasOneUse()) {
11173         SDNode *User = *Op.getNode()->use_begin();
11174         // Look for an unconditional branch following this conditional branch.
11175         // We need this because we need to reverse the successors in order
11176         // to implement FCMP_OEQ.
11177         if (User->getOpcode() == ISD::BR) {
11178           SDValue FalseBB = User->getOperand(1);
11179           SDNode *NewBR =
11180             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11181           assert(NewBR == User);
11182           (void)NewBR;
11183           Dest = FalseBB;
11184
11185           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11186                                     Cond.getOperand(0), Cond.getOperand(1));
11187           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11188           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11189           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11190                               Chain, Dest, CC, Cmp);
11191           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11192           Cond = Cmp;
11193           addTest = false;
11194         }
11195       }
11196     } else if (Cond.getOpcode() == ISD::SETCC &&
11197                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11198       // For FCMP_UNE, we can emit
11199       // two branches instead of an explicit AND instruction with a
11200       // separate test. However, we only do this if this block doesn't
11201       // have a fall-through edge, because this requires an explicit
11202       // jmp when the condition is false.
11203       if (Op.getNode()->hasOneUse()) {
11204         SDNode *User = *Op.getNode()->use_begin();
11205         // Look for an unconditional branch following this conditional branch.
11206         // We need this because we need to reverse the successors in order
11207         // to implement FCMP_UNE.
11208         if (User->getOpcode() == ISD::BR) {
11209           SDValue FalseBB = User->getOperand(1);
11210           SDNode *NewBR =
11211             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11212           assert(NewBR == User);
11213           (void)NewBR;
11214
11215           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11216                                     Cond.getOperand(0), Cond.getOperand(1));
11217           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11218           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11219           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11220                               Chain, Dest, CC, Cmp);
11221           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11222           Cond = Cmp;
11223           addTest = false;
11224           Dest = FalseBB;
11225         }
11226       }
11227     }
11228   }
11229
11230   if (addTest) {
11231     // Look pass the truncate if the high bits are known zero.
11232     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11233         Cond = Cond.getOperand(0);
11234
11235     // We know the result of AND is compared against zero. Try to match
11236     // it to BT.
11237     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11238       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11239       if (NewSetCC.getNode()) {
11240         CC = NewSetCC.getOperand(0);
11241         Cond = NewSetCC.getOperand(1);
11242         addTest = false;
11243       }
11244     }
11245   }
11246
11247   if (addTest) {
11248     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11249     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11250   }
11251   Cond = ConvertCmpIfNecessary(Cond, DAG);
11252   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11253                      Chain, Dest, CC, Cond);
11254 }
11255
11256 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11257 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11258 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11259 // that the guard pages used by the OS virtual memory manager are allocated in
11260 // correct sequence.
11261 SDValue
11262 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11263                                            SelectionDAG &DAG) const {
11264   MachineFunction &MF = DAG.getMachineFunction();
11265   bool SplitStack = MF.shouldSplitStack();
11266   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11267                SplitStack;
11268   SDLoc dl(Op);
11269
11270   if (!Lower) {
11271     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11272     SDNode* Node = Op.getNode();
11273
11274     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11275     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11276         " not tell us which reg is the stack pointer!");
11277     EVT VT = Node->getValueType(0);
11278     SDValue Tmp1 = SDValue(Node, 0);
11279     SDValue Tmp2 = SDValue(Node, 1);
11280     SDValue Tmp3 = Node->getOperand(2);
11281     SDValue Chain = Tmp1.getOperand(0);
11282
11283     // Chain the dynamic stack allocation so that it doesn't modify the stack
11284     // pointer when other instructions are using the stack.
11285     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11286         SDLoc(Node));
11287
11288     SDValue Size = Tmp2.getOperand(1);
11289     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11290     Chain = SP.getValue(1);
11291     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11292     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11293     unsigned StackAlign = TFI.getStackAlignment();
11294     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11295     if (Align > StackAlign)
11296       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11297           DAG.getConstant(-(uint64_t)Align, VT));
11298     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11299
11300     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11301         DAG.getIntPtrConstant(0, true), SDValue(),
11302         SDLoc(Node));
11303
11304     SDValue Ops[2] = { Tmp1, Tmp2 };
11305     return DAG.getMergeValues(Ops, 2, dl);
11306   }
11307
11308   // Get the inputs.
11309   SDValue Chain = Op.getOperand(0);
11310   SDValue Size  = Op.getOperand(1);
11311   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11312   EVT VT = Op.getNode()->getValueType(0);
11313
11314   bool Is64Bit = Subtarget->is64Bit();
11315   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11316
11317   if (SplitStack) {
11318     MachineRegisterInfo &MRI = MF.getRegInfo();
11319
11320     if (Is64Bit) {
11321       // The 64 bit implementation of segmented stacks needs to clobber both r10
11322       // r11. This makes it impossible to use it along with nested parameters.
11323       const Function *F = MF.getFunction();
11324
11325       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11326            I != E; ++I)
11327         if (I->hasNestAttr())
11328           report_fatal_error("Cannot use segmented stacks with functions that "
11329                              "have nested arguments.");
11330     }
11331
11332     const TargetRegisterClass *AddrRegClass =
11333       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11334     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11335     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11336     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11337                                 DAG.getRegister(Vreg, SPTy));
11338     SDValue Ops1[2] = { Value, Chain };
11339     return DAG.getMergeValues(Ops1, 2, dl);
11340   } else {
11341     SDValue Flag;
11342     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11343
11344     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11345     Flag = Chain.getValue(1);
11346     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11347
11348     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11349
11350     const X86RegisterInfo *RegInfo =
11351       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11352     unsigned SPReg = RegInfo->getStackRegister();
11353     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11354     Chain = SP.getValue(1);
11355
11356     if (Align) {
11357       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11358                        DAG.getConstant(-(uint64_t)Align, VT));
11359       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11360     }
11361
11362     SDValue Ops1[2] = { SP, Chain };
11363     return DAG.getMergeValues(Ops1, 2, dl);
11364   }
11365 }
11366
11367 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11368   MachineFunction &MF = DAG.getMachineFunction();
11369   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11370
11371   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11372   SDLoc DL(Op);
11373
11374   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11375     // vastart just stores the address of the VarArgsFrameIndex slot into the
11376     // memory location argument.
11377     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11378                                    getPointerTy());
11379     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11380                         MachinePointerInfo(SV), false, false, 0);
11381   }
11382
11383   // __va_list_tag:
11384   //   gp_offset         (0 - 6 * 8)
11385   //   fp_offset         (48 - 48 + 8 * 16)
11386   //   overflow_arg_area (point to parameters coming in memory).
11387   //   reg_save_area
11388   SmallVector<SDValue, 8> MemOps;
11389   SDValue FIN = Op.getOperand(1);
11390   // Store gp_offset
11391   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11392                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11393                                                MVT::i32),
11394                                FIN, MachinePointerInfo(SV), false, false, 0);
11395   MemOps.push_back(Store);
11396
11397   // Store fp_offset
11398   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11399                     FIN, DAG.getIntPtrConstant(4));
11400   Store = DAG.getStore(Op.getOperand(0), DL,
11401                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11402                                        MVT::i32),
11403                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11404   MemOps.push_back(Store);
11405
11406   // Store ptr to overflow_arg_area
11407   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11408                     FIN, DAG.getIntPtrConstant(4));
11409   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11410                                     getPointerTy());
11411   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11412                        MachinePointerInfo(SV, 8),
11413                        false, false, 0);
11414   MemOps.push_back(Store);
11415
11416   // Store ptr to reg_save_area.
11417   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11418                     FIN, DAG.getIntPtrConstant(8));
11419   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11420                                     getPointerTy());
11421   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11422                        MachinePointerInfo(SV, 16), false, false, 0);
11423   MemOps.push_back(Store);
11424   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11425                      &MemOps[0], MemOps.size());
11426 }
11427
11428 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11429   assert(Subtarget->is64Bit() &&
11430          "LowerVAARG only handles 64-bit va_arg!");
11431   assert((Subtarget->isTargetLinux() ||
11432           Subtarget->isTargetDarwin()) &&
11433           "Unhandled target in LowerVAARG");
11434   assert(Op.getNode()->getNumOperands() == 4);
11435   SDValue Chain = Op.getOperand(0);
11436   SDValue SrcPtr = Op.getOperand(1);
11437   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11438   unsigned Align = Op.getConstantOperandVal(3);
11439   SDLoc dl(Op);
11440
11441   EVT ArgVT = Op.getNode()->getValueType(0);
11442   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11443   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11444   uint8_t ArgMode;
11445
11446   // Decide which area this value should be read from.
11447   // TODO: Implement the AMD64 ABI in its entirety. This simple
11448   // selection mechanism works only for the basic types.
11449   if (ArgVT == MVT::f80) {
11450     llvm_unreachable("va_arg for f80 not yet implemented");
11451   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11452     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11453   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11454     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11455   } else {
11456     llvm_unreachable("Unhandled argument type in LowerVAARG");
11457   }
11458
11459   if (ArgMode == 2) {
11460     // Sanity Check: Make sure using fp_offset makes sense.
11461     assert(!getTargetMachine().Options.UseSoftFloat &&
11462            !(DAG.getMachineFunction()
11463                 .getFunction()->getAttributes()
11464                 .hasAttribute(AttributeSet::FunctionIndex,
11465                               Attribute::NoImplicitFloat)) &&
11466            Subtarget->hasSSE1());
11467   }
11468
11469   // Insert VAARG_64 node into the DAG
11470   // VAARG_64 returns two values: Variable Argument Address, Chain
11471   SmallVector<SDValue, 11> InstOps;
11472   InstOps.push_back(Chain);
11473   InstOps.push_back(SrcPtr);
11474   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11475   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11476   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11477   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11478   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11479                                           VTs, &InstOps[0], InstOps.size(),
11480                                           MVT::i64,
11481                                           MachinePointerInfo(SV),
11482                                           /*Align=*/0,
11483                                           /*Volatile=*/false,
11484                                           /*ReadMem=*/true,
11485                                           /*WriteMem=*/true);
11486   Chain = VAARG.getValue(1);
11487
11488   // Load the next argument and return it
11489   return DAG.getLoad(ArgVT, dl,
11490                      Chain,
11491                      VAARG,
11492                      MachinePointerInfo(),
11493                      false, false, false, 0);
11494 }
11495
11496 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11497                            SelectionDAG &DAG) {
11498   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11499   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11500   SDValue Chain = Op.getOperand(0);
11501   SDValue DstPtr = Op.getOperand(1);
11502   SDValue SrcPtr = Op.getOperand(2);
11503   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11504   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11505   SDLoc DL(Op);
11506
11507   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11508                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11509                        false,
11510                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11511 }
11512
11513 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11514 // amount is a constant. Takes immediate version of shift as input.
11515 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11516                                           SDValue SrcOp, uint64_t ShiftAmt,
11517                                           SelectionDAG &DAG) {
11518   MVT ElementType = VT.getVectorElementType();
11519
11520   // Check for ShiftAmt >= element width
11521   if (ShiftAmt >= ElementType.getSizeInBits()) {
11522     if (Opc == X86ISD::VSRAI)
11523       ShiftAmt = ElementType.getSizeInBits() - 1;
11524     else
11525       return DAG.getConstant(0, VT);
11526   }
11527
11528   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11529          && "Unknown target vector shift-by-constant node");
11530
11531   // Fold this packed vector shift into a build vector if SrcOp is a
11532   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11533   if (VT == SrcOp.getSimpleValueType() &&
11534       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11535     SmallVector<SDValue, 8> Elts;
11536     unsigned NumElts = SrcOp->getNumOperands();
11537     ConstantSDNode *ND;
11538
11539     switch(Opc) {
11540     default: llvm_unreachable(0);
11541     case X86ISD::VSHLI:
11542       for (unsigned i=0; i!=NumElts; ++i) {
11543         SDValue CurrentOp = SrcOp->getOperand(i);
11544         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11545           Elts.push_back(CurrentOp);
11546           continue;
11547         }
11548         ND = cast<ConstantSDNode>(CurrentOp);
11549         const APInt &C = ND->getAPIntValue();
11550         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11551       }
11552       break;
11553     case X86ISD::VSRLI:
11554       for (unsigned i=0; i!=NumElts; ++i) {
11555         SDValue CurrentOp = SrcOp->getOperand(i);
11556         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11557           Elts.push_back(CurrentOp);
11558           continue;
11559         }
11560         ND = cast<ConstantSDNode>(CurrentOp);
11561         const APInt &C = ND->getAPIntValue();
11562         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11563       }
11564       break;
11565     case X86ISD::VSRAI:
11566       for (unsigned i=0; i!=NumElts; ++i) {
11567         SDValue CurrentOp = SrcOp->getOperand(i);
11568         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11569           Elts.push_back(CurrentOp);
11570           continue;
11571         }
11572         ND = cast<ConstantSDNode>(CurrentOp);
11573         const APInt &C = ND->getAPIntValue();
11574         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11575       }
11576       break;
11577     }
11578
11579     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11580   }
11581
11582   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11583 }
11584
11585 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11586 // may or may not be a constant. Takes immediate version of shift as input.
11587 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11588                                    SDValue SrcOp, SDValue ShAmt,
11589                                    SelectionDAG &DAG) {
11590   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11591
11592   // Catch shift-by-constant.
11593   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11594     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11595                                       CShAmt->getZExtValue(), DAG);
11596
11597   // Change opcode to non-immediate version
11598   switch (Opc) {
11599     default: llvm_unreachable("Unknown target vector shift node");
11600     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11601     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11602     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11603   }
11604
11605   // Need to build a vector containing shift amount
11606   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11607   SDValue ShOps[4];
11608   ShOps[0] = ShAmt;
11609   ShOps[1] = DAG.getConstant(0, MVT::i32);
11610   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11611   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11612
11613   // The return type has to be a 128-bit type with the same element
11614   // type as the input type.
11615   MVT EltVT = VT.getVectorElementType();
11616   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11617
11618   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11619   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11620 }
11621
11622 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11623   SDLoc dl(Op);
11624   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11625   switch (IntNo) {
11626   default: return SDValue();    // Don't custom lower most intrinsics.
11627   // Comparison intrinsics.
11628   case Intrinsic::x86_sse_comieq_ss:
11629   case Intrinsic::x86_sse_comilt_ss:
11630   case Intrinsic::x86_sse_comile_ss:
11631   case Intrinsic::x86_sse_comigt_ss:
11632   case Intrinsic::x86_sse_comige_ss:
11633   case Intrinsic::x86_sse_comineq_ss:
11634   case Intrinsic::x86_sse_ucomieq_ss:
11635   case Intrinsic::x86_sse_ucomilt_ss:
11636   case Intrinsic::x86_sse_ucomile_ss:
11637   case Intrinsic::x86_sse_ucomigt_ss:
11638   case Intrinsic::x86_sse_ucomige_ss:
11639   case Intrinsic::x86_sse_ucomineq_ss:
11640   case Intrinsic::x86_sse2_comieq_sd:
11641   case Intrinsic::x86_sse2_comilt_sd:
11642   case Intrinsic::x86_sse2_comile_sd:
11643   case Intrinsic::x86_sse2_comigt_sd:
11644   case Intrinsic::x86_sse2_comige_sd:
11645   case Intrinsic::x86_sse2_comineq_sd:
11646   case Intrinsic::x86_sse2_ucomieq_sd:
11647   case Intrinsic::x86_sse2_ucomilt_sd:
11648   case Intrinsic::x86_sse2_ucomile_sd:
11649   case Intrinsic::x86_sse2_ucomigt_sd:
11650   case Intrinsic::x86_sse2_ucomige_sd:
11651   case Intrinsic::x86_sse2_ucomineq_sd: {
11652     unsigned Opc;
11653     ISD::CondCode CC;
11654     switch (IntNo) {
11655     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11656     case Intrinsic::x86_sse_comieq_ss:
11657     case Intrinsic::x86_sse2_comieq_sd:
11658       Opc = X86ISD::COMI;
11659       CC = ISD::SETEQ;
11660       break;
11661     case Intrinsic::x86_sse_comilt_ss:
11662     case Intrinsic::x86_sse2_comilt_sd:
11663       Opc = X86ISD::COMI;
11664       CC = ISD::SETLT;
11665       break;
11666     case Intrinsic::x86_sse_comile_ss:
11667     case Intrinsic::x86_sse2_comile_sd:
11668       Opc = X86ISD::COMI;
11669       CC = ISD::SETLE;
11670       break;
11671     case Intrinsic::x86_sse_comigt_ss:
11672     case Intrinsic::x86_sse2_comigt_sd:
11673       Opc = X86ISD::COMI;
11674       CC = ISD::SETGT;
11675       break;
11676     case Intrinsic::x86_sse_comige_ss:
11677     case Intrinsic::x86_sse2_comige_sd:
11678       Opc = X86ISD::COMI;
11679       CC = ISD::SETGE;
11680       break;
11681     case Intrinsic::x86_sse_comineq_ss:
11682     case Intrinsic::x86_sse2_comineq_sd:
11683       Opc = X86ISD::COMI;
11684       CC = ISD::SETNE;
11685       break;
11686     case Intrinsic::x86_sse_ucomieq_ss:
11687     case Intrinsic::x86_sse2_ucomieq_sd:
11688       Opc = X86ISD::UCOMI;
11689       CC = ISD::SETEQ;
11690       break;
11691     case Intrinsic::x86_sse_ucomilt_ss:
11692     case Intrinsic::x86_sse2_ucomilt_sd:
11693       Opc = X86ISD::UCOMI;
11694       CC = ISD::SETLT;
11695       break;
11696     case Intrinsic::x86_sse_ucomile_ss:
11697     case Intrinsic::x86_sse2_ucomile_sd:
11698       Opc = X86ISD::UCOMI;
11699       CC = ISD::SETLE;
11700       break;
11701     case Intrinsic::x86_sse_ucomigt_ss:
11702     case Intrinsic::x86_sse2_ucomigt_sd:
11703       Opc = X86ISD::UCOMI;
11704       CC = ISD::SETGT;
11705       break;
11706     case Intrinsic::x86_sse_ucomige_ss:
11707     case Intrinsic::x86_sse2_ucomige_sd:
11708       Opc = X86ISD::UCOMI;
11709       CC = ISD::SETGE;
11710       break;
11711     case Intrinsic::x86_sse_ucomineq_ss:
11712     case Intrinsic::x86_sse2_ucomineq_sd:
11713       Opc = X86ISD::UCOMI;
11714       CC = ISD::SETNE;
11715       break;
11716     }
11717
11718     SDValue LHS = Op.getOperand(1);
11719     SDValue RHS = Op.getOperand(2);
11720     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11721     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11722     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11723     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11724                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11725     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11726   }
11727
11728   // Arithmetic intrinsics.
11729   case Intrinsic::x86_sse2_pmulu_dq:
11730   case Intrinsic::x86_avx2_pmulu_dq:
11731     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11732                        Op.getOperand(1), Op.getOperand(2));
11733
11734   case Intrinsic::x86_sse41_pmuldq:
11735   case Intrinsic::x86_avx2_pmul_dq:
11736     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11737                        Op.getOperand(1), Op.getOperand(2));
11738
11739   case Intrinsic::x86_sse2_pmulhu_w:
11740   case Intrinsic::x86_avx2_pmulhu_w:
11741     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11742                        Op.getOperand(1), Op.getOperand(2));
11743
11744   case Intrinsic::x86_sse2_pmulh_w:
11745   case Intrinsic::x86_avx2_pmulh_w:
11746     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11747                        Op.getOperand(1), Op.getOperand(2));
11748
11749   // SSE2/AVX2 sub with unsigned saturation intrinsics
11750   case Intrinsic::x86_sse2_psubus_b:
11751   case Intrinsic::x86_sse2_psubus_w:
11752   case Intrinsic::x86_avx2_psubus_b:
11753   case Intrinsic::x86_avx2_psubus_w:
11754     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11755                        Op.getOperand(1), Op.getOperand(2));
11756
11757   // SSE3/AVX horizontal add/sub intrinsics
11758   case Intrinsic::x86_sse3_hadd_ps:
11759   case Intrinsic::x86_sse3_hadd_pd:
11760   case Intrinsic::x86_avx_hadd_ps_256:
11761   case Intrinsic::x86_avx_hadd_pd_256:
11762   case Intrinsic::x86_sse3_hsub_ps:
11763   case Intrinsic::x86_sse3_hsub_pd:
11764   case Intrinsic::x86_avx_hsub_ps_256:
11765   case Intrinsic::x86_avx_hsub_pd_256:
11766   case Intrinsic::x86_ssse3_phadd_w_128:
11767   case Intrinsic::x86_ssse3_phadd_d_128:
11768   case Intrinsic::x86_avx2_phadd_w:
11769   case Intrinsic::x86_avx2_phadd_d:
11770   case Intrinsic::x86_ssse3_phsub_w_128:
11771   case Intrinsic::x86_ssse3_phsub_d_128:
11772   case Intrinsic::x86_avx2_phsub_w:
11773   case Intrinsic::x86_avx2_phsub_d: {
11774     unsigned Opcode;
11775     switch (IntNo) {
11776     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11777     case Intrinsic::x86_sse3_hadd_ps:
11778     case Intrinsic::x86_sse3_hadd_pd:
11779     case Intrinsic::x86_avx_hadd_ps_256:
11780     case Intrinsic::x86_avx_hadd_pd_256:
11781       Opcode = X86ISD::FHADD;
11782       break;
11783     case Intrinsic::x86_sse3_hsub_ps:
11784     case Intrinsic::x86_sse3_hsub_pd:
11785     case Intrinsic::x86_avx_hsub_ps_256:
11786     case Intrinsic::x86_avx_hsub_pd_256:
11787       Opcode = X86ISD::FHSUB;
11788       break;
11789     case Intrinsic::x86_ssse3_phadd_w_128:
11790     case Intrinsic::x86_ssse3_phadd_d_128:
11791     case Intrinsic::x86_avx2_phadd_w:
11792     case Intrinsic::x86_avx2_phadd_d:
11793       Opcode = X86ISD::HADD;
11794       break;
11795     case Intrinsic::x86_ssse3_phsub_w_128:
11796     case Intrinsic::x86_ssse3_phsub_d_128:
11797     case Intrinsic::x86_avx2_phsub_w:
11798     case Intrinsic::x86_avx2_phsub_d:
11799       Opcode = X86ISD::HSUB;
11800       break;
11801     }
11802     return DAG.getNode(Opcode, dl, Op.getValueType(),
11803                        Op.getOperand(1), Op.getOperand(2));
11804   }
11805
11806   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11807   case Intrinsic::x86_sse2_pmaxu_b:
11808   case Intrinsic::x86_sse41_pmaxuw:
11809   case Intrinsic::x86_sse41_pmaxud:
11810   case Intrinsic::x86_avx2_pmaxu_b:
11811   case Intrinsic::x86_avx2_pmaxu_w:
11812   case Intrinsic::x86_avx2_pmaxu_d:
11813   case Intrinsic::x86_sse2_pminu_b:
11814   case Intrinsic::x86_sse41_pminuw:
11815   case Intrinsic::x86_sse41_pminud:
11816   case Intrinsic::x86_avx2_pminu_b:
11817   case Intrinsic::x86_avx2_pminu_w:
11818   case Intrinsic::x86_avx2_pminu_d:
11819   case Intrinsic::x86_sse41_pmaxsb:
11820   case Intrinsic::x86_sse2_pmaxs_w:
11821   case Intrinsic::x86_sse41_pmaxsd:
11822   case Intrinsic::x86_avx2_pmaxs_b:
11823   case Intrinsic::x86_avx2_pmaxs_w:
11824   case Intrinsic::x86_avx2_pmaxs_d:
11825   case Intrinsic::x86_sse41_pminsb:
11826   case Intrinsic::x86_sse2_pmins_w:
11827   case Intrinsic::x86_sse41_pminsd:
11828   case Intrinsic::x86_avx2_pmins_b:
11829   case Intrinsic::x86_avx2_pmins_w:
11830   case Intrinsic::x86_avx2_pmins_d: {
11831     unsigned Opcode;
11832     switch (IntNo) {
11833     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11834     case Intrinsic::x86_sse2_pmaxu_b:
11835     case Intrinsic::x86_sse41_pmaxuw:
11836     case Intrinsic::x86_sse41_pmaxud:
11837     case Intrinsic::x86_avx2_pmaxu_b:
11838     case Intrinsic::x86_avx2_pmaxu_w:
11839     case Intrinsic::x86_avx2_pmaxu_d:
11840       Opcode = X86ISD::UMAX;
11841       break;
11842     case Intrinsic::x86_sse2_pminu_b:
11843     case Intrinsic::x86_sse41_pminuw:
11844     case Intrinsic::x86_sse41_pminud:
11845     case Intrinsic::x86_avx2_pminu_b:
11846     case Intrinsic::x86_avx2_pminu_w:
11847     case Intrinsic::x86_avx2_pminu_d:
11848       Opcode = X86ISD::UMIN;
11849       break;
11850     case Intrinsic::x86_sse41_pmaxsb:
11851     case Intrinsic::x86_sse2_pmaxs_w:
11852     case Intrinsic::x86_sse41_pmaxsd:
11853     case Intrinsic::x86_avx2_pmaxs_b:
11854     case Intrinsic::x86_avx2_pmaxs_w:
11855     case Intrinsic::x86_avx2_pmaxs_d:
11856       Opcode = X86ISD::SMAX;
11857       break;
11858     case Intrinsic::x86_sse41_pminsb:
11859     case Intrinsic::x86_sse2_pmins_w:
11860     case Intrinsic::x86_sse41_pminsd:
11861     case Intrinsic::x86_avx2_pmins_b:
11862     case Intrinsic::x86_avx2_pmins_w:
11863     case Intrinsic::x86_avx2_pmins_d:
11864       Opcode = X86ISD::SMIN;
11865       break;
11866     }
11867     return DAG.getNode(Opcode, dl, Op.getValueType(),
11868                        Op.getOperand(1), Op.getOperand(2));
11869   }
11870
11871   // SSE/SSE2/AVX floating point max/min intrinsics.
11872   case Intrinsic::x86_sse_max_ps:
11873   case Intrinsic::x86_sse2_max_pd:
11874   case Intrinsic::x86_avx_max_ps_256:
11875   case Intrinsic::x86_avx_max_pd_256:
11876   case Intrinsic::x86_sse_min_ps:
11877   case Intrinsic::x86_sse2_min_pd:
11878   case Intrinsic::x86_avx_min_ps_256:
11879   case Intrinsic::x86_avx_min_pd_256: {
11880     unsigned Opcode;
11881     switch (IntNo) {
11882     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11883     case Intrinsic::x86_sse_max_ps:
11884     case Intrinsic::x86_sse2_max_pd:
11885     case Intrinsic::x86_avx_max_ps_256:
11886     case Intrinsic::x86_avx_max_pd_256:
11887       Opcode = X86ISD::FMAX;
11888       break;
11889     case Intrinsic::x86_sse_min_ps:
11890     case Intrinsic::x86_sse2_min_pd:
11891     case Intrinsic::x86_avx_min_ps_256:
11892     case Intrinsic::x86_avx_min_pd_256:
11893       Opcode = X86ISD::FMIN;
11894       break;
11895     }
11896     return DAG.getNode(Opcode, dl, Op.getValueType(),
11897                        Op.getOperand(1), Op.getOperand(2));
11898   }
11899
11900   // AVX2 variable shift intrinsics
11901   case Intrinsic::x86_avx2_psllv_d:
11902   case Intrinsic::x86_avx2_psllv_q:
11903   case Intrinsic::x86_avx2_psllv_d_256:
11904   case Intrinsic::x86_avx2_psllv_q_256:
11905   case Intrinsic::x86_avx2_psrlv_d:
11906   case Intrinsic::x86_avx2_psrlv_q:
11907   case Intrinsic::x86_avx2_psrlv_d_256:
11908   case Intrinsic::x86_avx2_psrlv_q_256:
11909   case Intrinsic::x86_avx2_psrav_d:
11910   case Intrinsic::x86_avx2_psrav_d_256: {
11911     unsigned Opcode;
11912     switch (IntNo) {
11913     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11914     case Intrinsic::x86_avx2_psllv_d:
11915     case Intrinsic::x86_avx2_psllv_q:
11916     case Intrinsic::x86_avx2_psllv_d_256:
11917     case Intrinsic::x86_avx2_psllv_q_256:
11918       Opcode = ISD::SHL;
11919       break;
11920     case Intrinsic::x86_avx2_psrlv_d:
11921     case Intrinsic::x86_avx2_psrlv_q:
11922     case Intrinsic::x86_avx2_psrlv_d_256:
11923     case Intrinsic::x86_avx2_psrlv_q_256:
11924       Opcode = ISD::SRL;
11925       break;
11926     case Intrinsic::x86_avx2_psrav_d:
11927     case Intrinsic::x86_avx2_psrav_d_256:
11928       Opcode = ISD::SRA;
11929       break;
11930     }
11931     return DAG.getNode(Opcode, dl, Op.getValueType(),
11932                        Op.getOperand(1), Op.getOperand(2));
11933   }
11934
11935   case Intrinsic::x86_ssse3_pshuf_b_128:
11936   case Intrinsic::x86_avx2_pshuf_b:
11937     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11938                        Op.getOperand(1), Op.getOperand(2));
11939
11940   case Intrinsic::x86_ssse3_psign_b_128:
11941   case Intrinsic::x86_ssse3_psign_w_128:
11942   case Intrinsic::x86_ssse3_psign_d_128:
11943   case Intrinsic::x86_avx2_psign_b:
11944   case Intrinsic::x86_avx2_psign_w:
11945   case Intrinsic::x86_avx2_psign_d:
11946     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11947                        Op.getOperand(1), Op.getOperand(2));
11948
11949   case Intrinsic::x86_sse41_insertps:
11950     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11951                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11952
11953   case Intrinsic::x86_avx_vperm2f128_ps_256:
11954   case Intrinsic::x86_avx_vperm2f128_pd_256:
11955   case Intrinsic::x86_avx_vperm2f128_si_256:
11956   case Intrinsic::x86_avx2_vperm2i128:
11957     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11958                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11959
11960   case Intrinsic::x86_avx2_permd:
11961   case Intrinsic::x86_avx2_permps:
11962     // Operands intentionally swapped. Mask is last operand to intrinsic,
11963     // but second operand for node/instruction.
11964     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11965                        Op.getOperand(2), Op.getOperand(1));
11966
11967   case Intrinsic::x86_sse_sqrt_ps:
11968   case Intrinsic::x86_sse2_sqrt_pd:
11969   case Intrinsic::x86_avx_sqrt_ps_256:
11970   case Intrinsic::x86_avx_sqrt_pd_256:
11971     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11972
11973   // ptest and testp intrinsics. The intrinsic these come from are designed to
11974   // return an integer value, not just an instruction so lower it to the ptest
11975   // or testp pattern and a setcc for the result.
11976   case Intrinsic::x86_sse41_ptestz:
11977   case Intrinsic::x86_sse41_ptestc:
11978   case Intrinsic::x86_sse41_ptestnzc:
11979   case Intrinsic::x86_avx_ptestz_256:
11980   case Intrinsic::x86_avx_ptestc_256:
11981   case Intrinsic::x86_avx_ptestnzc_256:
11982   case Intrinsic::x86_avx_vtestz_ps:
11983   case Intrinsic::x86_avx_vtestc_ps:
11984   case Intrinsic::x86_avx_vtestnzc_ps:
11985   case Intrinsic::x86_avx_vtestz_pd:
11986   case Intrinsic::x86_avx_vtestc_pd:
11987   case Intrinsic::x86_avx_vtestnzc_pd:
11988   case Intrinsic::x86_avx_vtestz_ps_256:
11989   case Intrinsic::x86_avx_vtestc_ps_256:
11990   case Intrinsic::x86_avx_vtestnzc_ps_256:
11991   case Intrinsic::x86_avx_vtestz_pd_256:
11992   case Intrinsic::x86_avx_vtestc_pd_256:
11993   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11994     bool IsTestPacked = false;
11995     unsigned X86CC;
11996     switch (IntNo) {
11997     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11998     case Intrinsic::x86_avx_vtestz_ps:
11999     case Intrinsic::x86_avx_vtestz_pd:
12000     case Intrinsic::x86_avx_vtestz_ps_256:
12001     case Intrinsic::x86_avx_vtestz_pd_256:
12002       IsTestPacked = true; // Fallthrough
12003     case Intrinsic::x86_sse41_ptestz:
12004     case Intrinsic::x86_avx_ptestz_256:
12005       // ZF = 1
12006       X86CC = X86::COND_E;
12007       break;
12008     case Intrinsic::x86_avx_vtestc_ps:
12009     case Intrinsic::x86_avx_vtestc_pd:
12010     case Intrinsic::x86_avx_vtestc_ps_256:
12011     case Intrinsic::x86_avx_vtestc_pd_256:
12012       IsTestPacked = true; // Fallthrough
12013     case Intrinsic::x86_sse41_ptestc:
12014     case Intrinsic::x86_avx_ptestc_256:
12015       // CF = 1
12016       X86CC = X86::COND_B;
12017       break;
12018     case Intrinsic::x86_avx_vtestnzc_ps:
12019     case Intrinsic::x86_avx_vtestnzc_pd:
12020     case Intrinsic::x86_avx_vtestnzc_ps_256:
12021     case Intrinsic::x86_avx_vtestnzc_pd_256:
12022       IsTestPacked = true; // Fallthrough
12023     case Intrinsic::x86_sse41_ptestnzc:
12024     case Intrinsic::x86_avx_ptestnzc_256:
12025       // ZF and CF = 0
12026       X86CC = X86::COND_A;
12027       break;
12028     }
12029
12030     SDValue LHS = Op.getOperand(1);
12031     SDValue RHS = Op.getOperand(2);
12032     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12033     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12034     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12035     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12036     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12037   }
12038   case Intrinsic::x86_avx512_kortestz_w:
12039   case Intrinsic::x86_avx512_kortestc_w: {
12040     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12041     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12042     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12043     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12044     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12045     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12046     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12047   }
12048
12049   // SSE/AVX shift intrinsics
12050   case Intrinsic::x86_sse2_psll_w:
12051   case Intrinsic::x86_sse2_psll_d:
12052   case Intrinsic::x86_sse2_psll_q:
12053   case Intrinsic::x86_avx2_psll_w:
12054   case Intrinsic::x86_avx2_psll_d:
12055   case Intrinsic::x86_avx2_psll_q:
12056   case Intrinsic::x86_sse2_psrl_w:
12057   case Intrinsic::x86_sse2_psrl_d:
12058   case Intrinsic::x86_sse2_psrl_q:
12059   case Intrinsic::x86_avx2_psrl_w:
12060   case Intrinsic::x86_avx2_psrl_d:
12061   case Intrinsic::x86_avx2_psrl_q:
12062   case Intrinsic::x86_sse2_psra_w:
12063   case Intrinsic::x86_sse2_psra_d:
12064   case Intrinsic::x86_avx2_psra_w:
12065   case Intrinsic::x86_avx2_psra_d: {
12066     unsigned Opcode;
12067     switch (IntNo) {
12068     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12069     case Intrinsic::x86_sse2_psll_w:
12070     case Intrinsic::x86_sse2_psll_d:
12071     case Intrinsic::x86_sse2_psll_q:
12072     case Intrinsic::x86_avx2_psll_w:
12073     case Intrinsic::x86_avx2_psll_d:
12074     case Intrinsic::x86_avx2_psll_q:
12075       Opcode = X86ISD::VSHL;
12076       break;
12077     case Intrinsic::x86_sse2_psrl_w:
12078     case Intrinsic::x86_sse2_psrl_d:
12079     case Intrinsic::x86_sse2_psrl_q:
12080     case Intrinsic::x86_avx2_psrl_w:
12081     case Intrinsic::x86_avx2_psrl_d:
12082     case Intrinsic::x86_avx2_psrl_q:
12083       Opcode = X86ISD::VSRL;
12084       break;
12085     case Intrinsic::x86_sse2_psra_w:
12086     case Intrinsic::x86_sse2_psra_d:
12087     case Intrinsic::x86_avx2_psra_w:
12088     case Intrinsic::x86_avx2_psra_d:
12089       Opcode = X86ISD::VSRA;
12090       break;
12091     }
12092     return DAG.getNode(Opcode, dl, Op.getValueType(),
12093                        Op.getOperand(1), Op.getOperand(2));
12094   }
12095
12096   // SSE/AVX immediate shift intrinsics
12097   case Intrinsic::x86_sse2_pslli_w:
12098   case Intrinsic::x86_sse2_pslli_d:
12099   case Intrinsic::x86_sse2_pslli_q:
12100   case Intrinsic::x86_avx2_pslli_w:
12101   case Intrinsic::x86_avx2_pslli_d:
12102   case Intrinsic::x86_avx2_pslli_q:
12103   case Intrinsic::x86_sse2_psrli_w:
12104   case Intrinsic::x86_sse2_psrli_d:
12105   case Intrinsic::x86_sse2_psrli_q:
12106   case Intrinsic::x86_avx2_psrli_w:
12107   case Intrinsic::x86_avx2_psrli_d:
12108   case Intrinsic::x86_avx2_psrli_q:
12109   case Intrinsic::x86_sse2_psrai_w:
12110   case Intrinsic::x86_sse2_psrai_d:
12111   case Intrinsic::x86_avx2_psrai_w:
12112   case Intrinsic::x86_avx2_psrai_d: {
12113     unsigned Opcode;
12114     switch (IntNo) {
12115     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12116     case Intrinsic::x86_sse2_pslli_w:
12117     case Intrinsic::x86_sse2_pslli_d:
12118     case Intrinsic::x86_sse2_pslli_q:
12119     case Intrinsic::x86_avx2_pslli_w:
12120     case Intrinsic::x86_avx2_pslli_d:
12121     case Intrinsic::x86_avx2_pslli_q:
12122       Opcode = X86ISD::VSHLI;
12123       break;
12124     case Intrinsic::x86_sse2_psrli_w:
12125     case Intrinsic::x86_sse2_psrli_d:
12126     case Intrinsic::x86_sse2_psrli_q:
12127     case Intrinsic::x86_avx2_psrli_w:
12128     case Intrinsic::x86_avx2_psrli_d:
12129     case Intrinsic::x86_avx2_psrli_q:
12130       Opcode = X86ISD::VSRLI;
12131       break;
12132     case Intrinsic::x86_sse2_psrai_w:
12133     case Intrinsic::x86_sse2_psrai_d:
12134     case Intrinsic::x86_avx2_psrai_w:
12135     case Intrinsic::x86_avx2_psrai_d:
12136       Opcode = X86ISD::VSRAI;
12137       break;
12138     }
12139     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12140                                Op.getOperand(1), Op.getOperand(2), DAG);
12141   }
12142
12143   case Intrinsic::x86_sse42_pcmpistria128:
12144   case Intrinsic::x86_sse42_pcmpestria128:
12145   case Intrinsic::x86_sse42_pcmpistric128:
12146   case Intrinsic::x86_sse42_pcmpestric128:
12147   case Intrinsic::x86_sse42_pcmpistrio128:
12148   case Intrinsic::x86_sse42_pcmpestrio128:
12149   case Intrinsic::x86_sse42_pcmpistris128:
12150   case Intrinsic::x86_sse42_pcmpestris128:
12151   case Intrinsic::x86_sse42_pcmpistriz128:
12152   case Intrinsic::x86_sse42_pcmpestriz128: {
12153     unsigned Opcode;
12154     unsigned X86CC;
12155     switch (IntNo) {
12156     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12157     case Intrinsic::x86_sse42_pcmpistria128:
12158       Opcode = X86ISD::PCMPISTRI;
12159       X86CC = X86::COND_A;
12160       break;
12161     case Intrinsic::x86_sse42_pcmpestria128:
12162       Opcode = X86ISD::PCMPESTRI;
12163       X86CC = X86::COND_A;
12164       break;
12165     case Intrinsic::x86_sse42_pcmpistric128:
12166       Opcode = X86ISD::PCMPISTRI;
12167       X86CC = X86::COND_B;
12168       break;
12169     case Intrinsic::x86_sse42_pcmpestric128:
12170       Opcode = X86ISD::PCMPESTRI;
12171       X86CC = X86::COND_B;
12172       break;
12173     case Intrinsic::x86_sse42_pcmpistrio128:
12174       Opcode = X86ISD::PCMPISTRI;
12175       X86CC = X86::COND_O;
12176       break;
12177     case Intrinsic::x86_sse42_pcmpestrio128:
12178       Opcode = X86ISD::PCMPESTRI;
12179       X86CC = X86::COND_O;
12180       break;
12181     case Intrinsic::x86_sse42_pcmpistris128:
12182       Opcode = X86ISD::PCMPISTRI;
12183       X86CC = X86::COND_S;
12184       break;
12185     case Intrinsic::x86_sse42_pcmpestris128:
12186       Opcode = X86ISD::PCMPESTRI;
12187       X86CC = X86::COND_S;
12188       break;
12189     case Intrinsic::x86_sse42_pcmpistriz128:
12190       Opcode = X86ISD::PCMPISTRI;
12191       X86CC = X86::COND_E;
12192       break;
12193     case Intrinsic::x86_sse42_pcmpestriz128:
12194       Opcode = X86ISD::PCMPESTRI;
12195       X86CC = X86::COND_E;
12196       break;
12197     }
12198     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12199     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12200     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12201     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12202                                 DAG.getConstant(X86CC, MVT::i8),
12203                                 SDValue(PCMP.getNode(), 1));
12204     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12205   }
12206
12207   case Intrinsic::x86_sse42_pcmpistri128:
12208   case Intrinsic::x86_sse42_pcmpestri128: {
12209     unsigned Opcode;
12210     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12211       Opcode = X86ISD::PCMPISTRI;
12212     else
12213       Opcode = X86ISD::PCMPESTRI;
12214
12215     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12216     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12217     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12218   }
12219   case Intrinsic::x86_fma_vfmadd_ps:
12220   case Intrinsic::x86_fma_vfmadd_pd:
12221   case Intrinsic::x86_fma_vfmsub_ps:
12222   case Intrinsic::x86_fma_vfmsub_pd:
12223   case Intrinsic::x86_fma_vfnmadd_ps:
12224   case Intrinsic::x86_fma_vfnmadd_pd:
12225   case Intrinsic::x86_fma_vfnmsub_ps:
12226   case Intrinsic::x86_fma_vfnmsub_pd:
12227   case Intrinsic::x86_fma_vfmaddsub_ps:
12228   case Intrinsic::x86_fma_vfmaddsub_pd:
12229   case Intrinsic::x86_fma_vfmsubadd_ps:
12230   case Intrinsic::x86_fma_vfmsubadd_pd:
12231   case Intrinsic::x86_fma_vfmadd_ps_256:
12232   case Intrinsic::x86_fma_vfmadd_pd_256:
12233   case Intrinsic::x86_fma_vfmsub_ps_256:
12234   case Intrinsic::x86_fma_vfmsub_pd_256:
12235   case Intrinsic::x86_fma_vfnmadd_ps_256:
12236   case Intrinsic::x86_fma_vfnmadd_pd_256:
12237   case Intrinsic::x86_fma_vfnmsub_ps_256:
12238   case Intrinsic::x86_fma_vfnmsub_pd_256:
12239   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12240   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12241   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12242   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12243   case Intrinsic::x86_fma_vfmadd_ps_512:
12244   case Intrinsic::x86_fma_vfmadd_pd_512:
12245   case Intrinsic::x86_fma_vfmsub_ps_512:
12246   case Intrinsic::x86_fma_vfmsub_pd_512:
12247   case Intrinsic::x86_fma_vfnmadd_ps_512:
12248   case Intrinsic::x86_fma_vfnmadd_pd_512:
12249   case Intrinsic::x86_fma_vfnmsub_ps_512:
12250   case Intrinsic::x86_fma_vfnmsub_pd_512:
12251   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12252   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12253   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12254   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12255     unsigned Opc;
12256     switch (IntNo) {
12257     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12258     case Intrinsic::x86_fma_vfmadd_ps:
12259     case Intrinsic::x86_fma_vfmadd_pd:
12260     case Intrinsic::x86_fma_vfmadd_ps_256:
12261     case Intrinsic::x86_fma_vfmadd_pd_256:
12262     case Intrinsic::x86_fma_vfmadd_ps_512:
12263     case Intrinsic::x86_fma_vfmadd_pd_512:
12264       Opc = X86ISD::FMADD;
12265       break;
12266     case Intrinsic::x86_fma_vfmsub_ps:
12267     case Intrinsic::x86_fma_vfmsub_pd:
12268     case Intrinsic::x86_fma_vfmsub_ps_256:
12269     case Intrinsic::x86_fma_vfmsub_pd_256:
12270     case Intrinsic::x86_fma_vfmsub_ps_512:
12271     case Intrinsic::x86_fma_vfmsub_pd_512:
12272       Opc = X86ISD::FMSUB;
12273       break;
12274     case Intrinsic::x86_fma_vfnmadd_ps:
12275     case Intrinsic::x86_fma_vfnmadd_pd:
12276     case Intrinsic::x86_fma_vfnmadd_ps_256:
12277     case Intrinsic::x86_fma_vfnmadd_pd_256:
12278     case Intrinsic::x86_fma_vfnmadd_ps_512:
12279     case Intrinsic::x86_fma_vfnmadd_pd_512:
12280       Opc = X86ISD::FNMADD;
12281       break;
12282     case Intrinsic::x86_fma_vfnmsub_ps:
12283     case Intrinsic::x86_fma_vfnmsub_pd:
12284     case Intrinsic::x86_fma_vfnmsub_ps_256:
12285     case Intrinsic::x86_fma_vfnmsub_pd_256:
12286     case Intrinsic::x86_fma_vfnmsub_ps_512:
12287     case Intrinsic::x86_fma_vfnmsub_pd_512:
12288       Opc = X86ISD::FNMSUB;
12289       break;
12290     case Intrinsic::x86_fma_vfmaddsub_ps:
12291     case Intrinsic::x86_fma_vfmaddsub_pd:
12292     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12293     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12294     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12295     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12296       Opc = X86ISD::FMADDSUB;
12297       break;
12298     case Intrinsic::x86_fma_vfmsubadd_ps:
12299     case Intrinsic::x86_fma_vfmsubadd_pd:
12300     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12301     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12302     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12303     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12304       Opc = X86ISD::FMSUBADD;
12305       break;
12306     }
12307
12308     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12309                        Op.getOperand(2), Op.getOperand(3));
12310   }
12311   }
12312 }
12313
12314 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12315                              SDValue Base, SDValue Index,
12316                              SDValue ScaleOp, SDValue Chain,
12317                              const X86Subtarget * Subtarget) {
12318   SDLoc dl(Op);
12319   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12320   assert(C && "Invalid scale type");
12321   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12322   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12323   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12324                              Index.getSimpleValueType().getVectorNumElements());
12325   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12326   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12327   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12328   SDValue Segment = DAG.getRegister(0, MVT::i32);
12329   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12330   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12331   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12332   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12333 }
12334
12335 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12336                               SDValue Src, SDValue Mask, SDValue Base,
12337                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12338                               const X86Subtarget * Subtarget) {
12339   SDLoc dl(Op);
12340   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12341   assert(C && "Invalid scale type");
12342   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12343   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12344                              Index.getSimpleValueType().getVectorNumElements());
12345   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12346   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12347   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12348   SDValue Segment = DAG.getRegister(0, MVT::i32);
12349   if (Src.getOpcode() == ISD::UNDEF)
12350     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12351   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12352   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12353   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12354   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12355 }
12356
12357 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12358                               SDValue Src, SDValue Base, SDValue Index,
12359                               SDValue ScaleOp, SDValue Chain) {
12360   SDLoc dl(Op);
12361   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12362   assert(C && "Invalid scale type");
12363   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12364   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12365   SDValue Segment = DAG.getRegister(0, MVT::i32);
12366   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12367                              Index.getSimpleValueType().getVectorNumElements());
12368   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12369   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12370   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12371   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12372   return SDValue(Res, 1);
12373 }
12374
12375 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12376                                SDValue Src, SDValue Mask, SDValue Base,
12377                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12378   SDLoc dl(Op);
12379   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12380   assert(C && "Invalid scale type");
12381   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12382   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12383   SDValue Segment = DAG.getRegister(0, MVT::i32);
12384   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12385                              Index.getSimpleValueType().getVectorNumElements());
12386   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12387   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12388   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12389   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12390   return SDValue(Res, 1);
12391 }
12392
12393 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12394 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12395 // also used to custom lower READCYCLECOUNTER nodes.
12396 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12397                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12398                               SmallVectorImpl<SDValue> &Results) {
12399   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12400   SDValue TheChain = N->getOperand(0);
12401   SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12402   SDValue LO, HI;
12403
12404   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12405   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12406   // and the EAX register is loaded with the low-order 32 bits.
12407   if (Subtarget->is64Bit()) {
12408     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12409     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12410                             LO.getValue(2));
12411   } else {
12412     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12413     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12414                             LO.getValue(2));
12415   }
12416   SDValue Chain = HI.getValue(1);
12417
12418   if (Opcode == X86ISD::RDTSCP_DAG) {
12419     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12420
12421     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12422     // the ECX register. Add 'ecx' explicitly to the chain.
12423     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12424                                      HI.getValue(2));
12425     // Explicitly store the content of ECX at the location passed in input
12426     // to the 'rdtscp' intrinsic.
12427     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12428                          MachinePointerInfo(), false, false, 0);
12429   }
12430
12431   if (Subtarget->is64Bit()) {
12432     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12433     // the EAX register is loaded with the low-order 32 bits.
12434     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12435                               DAG.getConstant(32, MVT::i8));
12436     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12437     Results.push_back(Chain);
12438     return;
12439   }
12440
12441   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12442   SDValue Ops[] = { LO, HI };
12443   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12444                              array_lengthof(Ops));
12445   Results.push_back(Pair);
12446   Results.push_back(Chain);
12447 }
12448
12449 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12450                                      SelectionDAG &DAG) {
12451   SmallVector<SDValue, 2> Results;
12452   SDLoc DL(Op);
12453   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12454                           Results);
12455   return DAG.getMergeValues(&Results[0], Results.size(), DL);
12456 }
12457
12458 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12459                                       SelectionDAG &DAG) {
12460   SDLoc dl(Op);
12461   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12462   switch (IntNo) {
12463   default: return SDValue();    // Don't custom lower most intrinsics.
12464
12465   // RDRAND/RDSEED intrinsics.
12466   case Intrinsic::x86_rdrand_16:
12467   case Intrinsic::x86_rdrand_32:
12468   case Intrinsic::x86_rdrand_64:
12469   case Intrinsic::x86_rdseed_16:
12470   case Intrinsic::x86_rdseed_32:
12471   case Intrinsic::x86_rdseed_64: {
12472     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12473                        IntNo == Intrinsic::x86_rdseed_32 ||
12474                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12475                                                             X86ISD::RDRAND;
12476     // Emit the node with the right value type.
12477     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12478     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12479
12480     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12481     // Otherwise return the value from Rand, which is always 0, casted to i32.
12482     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12483                       DAG.getConstant(1, Op->getValueType(1)),
12484                       DAG.getConstant(X86::COND_B, MVT::i32),
12485                       SDValue(Result.getNode(), 1) };
12486     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12487                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12488                                   Ops, array_lengthof(Ops));
12489
12490     // Return { result, isValid, chain }.
12491     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12492                        SDValue(Result.getNode(), 2));
12493   }
12494   //int_gather(index, base, scale);
12495   case Intrinsic::x86_avx512_gather_qpd_512:
12496   case Intrinsic::x86_avx512_gather_qps_512:
12497   case Intrinsic::x86_avx512_gather_dpd_512:
12498   case Intrinsic::x86_avx512_gather_qpi_512:
12499   case Intrinsic::x86_avx512_gather_qpq_512:
12500   case Intrinsic::x86_avx512_gather_dpq_512:
12501   case Intrinsic::x86_avx512_gather_dps_512:
12502   case Intrinsic::x86_avx512_gather_dpi_512: {
12503     unsigned Opc;
12504     switch (IntNo) {
12505     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12506     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12507     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12508     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12509     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12510     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12511     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12512     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12513     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12514     }
12515     SDValue Chain = Op.getOperand(0);
12516     SDValue Index = Op.getOperand(2);
12517     SDValue Base  = Op.getOperand(3);
12518     SDValue Scale = Op.getOperand(4);
12519     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12520   }
12521   //int_gather_mask(v1, mask, index, base, scale);
12522   case Intrinsic::x86_avx512_gather_qps_mask_512:
12523   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12524   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12525   case Intrinsic::x86_avx512_gather_dps_mask_512:
12526   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12527   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12528   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12529   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12530     unsigned Opc;
12531     switch (IntNo) {
12532     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12533     case Intrinsic::x86_avx512_gather_qps_mask_512:
12534       Opc = X86::VGATHERQPSZrm; break;
12535     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12536       Opc = X86::VGATHERQPDZrm; break;
12537     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12538       Opc = X86::VGATHERDPDZrm; break;
12539     case Intrinsic::x86_avx512_gather_dps_mask_512:
12540       Opc = X86::VGATHERDPSZrm; break;
12541     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12542       Opc = X86::VPGATHERQDZrm; break;
12543     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12544       Opc = X86::VPGATHERQQZrm; break;
12545     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12546       Opc = X86::VPGATHERDDZrm; break;
12547     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12548       Opc = X86::VPGATHERDQZrm; break;
12549     }
12550     SDValue Chain = Op.getOperand(0);
12551     SDValue Src   = Op.getOperand(2);
12552     SDValue Mask  = Op.getOperand(3);
12553     SDValue Index = Op.getOperand(4);
12554     SDValue Base  = Op.getOperand(5);
12555     SDValue Scale = Op.getOperand(6);
12556     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12557                           Subtarget);
12558   }
12559   //int_scatter(base, index, v1, scale);
12560   case Intrinsic::x86_avx512_scatter_qpd_512:
12561   case Intrinsic::x86_avx512_scatter_qps_512:
12562   case Intrinsic::x86_avx512_scatter_dpd_512:
12563   case Intrinsic::x86_avx512_scatter_qpi_512:
12564   case Intrinsic::x86_avx512_scatter_qpq_512:
12565   case Intrinsic::x86_avx512_scatter_dpq_512:
12566   case Intrinsic::x86_avx512_scatter_dps_512:
12567   case Intrinsic::x86_avx512_scatter_dpi_512: {
12568     unsigned Opc;
12569     switch (IntNo) {
12570     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12571     case Intrinsic::x86_avx512_scatter_qpd_512:
12572       Opc = X86::VSCATTERQPDZmr; break;
12573     case Intrinsic::x86_avx512_scatter_qps_512:
12574       Opc = X86::VSCATTERQPSZmr; break;
12575     case Intrinsic::x86_avx512_scatter_dpd_512:
12576       Opc = X86::VSCATTERDPDZmr; break;
12577     case Intrinsic::x86_avx512_scatter_dps_512:
12578       Opc = X86::VSCATTERDPSZmr; break;
12579     case Intrinsic::x86_avx512_scatter_qpi_512:
12580       Opc = X86::VPSCATTERQDZmr; break;
12581     case Intrinsic::x86_avx512_scatter_qpq_512:
12582       Opc = X86::VPSCATTERQQZmr; break;
12583     case Intrinsic::x86_avx512_scatter_dpq_512:
12584       Opc = X86::VPSCATTERDQZmr; break;
12585     case Intrinsic::x86_avx512_scatter_dpi_512:
12586       Opc = X86::VPSCATTERDDZmr; break;
12587     }
12588     SDValue Chain = Op.getOperand(0);
12589     SDValue Base  = Op.getOperand(2);
12590     SDValue Index = Op.getOperand(3);
12591     SDValue Src   = Op.getOperand(4);
12592     SDValue Scale = Op.getOperand(5);
12593     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12594   }
12595   //int_scatter_mask(base, mask, index, v1, scale);
12596   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12597   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12598   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12599   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12600   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12601   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12602   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12603   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12604     unsigned Opc;
12605     switch (IntNo) {
12606     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12607     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12608       Opc = X86::VSCATTERQPDZmr; break;
12609     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12610       Opc = X86::VSCATTERQPSZmr; break;
12611     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12612       Opc = X86::VSCATTERDPDZmr; break;
12613     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12614       Opc = X86::VSCATTERDPSZmr; break;
12615     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12616       Opc = X86::VPSCATTERQDZmr; break;
12617     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12618       Opc = X86::VPSCATTERQQZmr; break;
12619     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12620       Opc = X86::VPSCATTERDQZmr; break;
12621     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12622       Opc = X86::VPSCATTERDDZmr; break;
12623     }
12624     SDValue Chain = Op.getOperand(0);
12625     SDValue Base  = Op.getOperand(2);
12626     SDValue Mask  = Op.getOperand(3);
12627     SDValue Index = Op.getOperand(4);
12628     SDValue Src   = Op.getOperand(5);
12629     SDValue Scale = Op.getOperand(6);
12630     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12631   }
12632   // Read Time Stamp Counter (RDTSC).
12633   case Intrinsic::x86_rdtsc:
12634   // Read Time Stamp Counter and Processor ID (RDTSCP).
12635   case Intrinsic::x86_rdtscp: {
12636     unsigned Opc;
12637     switch (IntNo) {
12638     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12639     case Intrinsic::x86_rdtsc:
12640       Opc = X86ISD::RDTSC_DAG; break;
12641     case Intrinsic::x86_rdtscp:
12642       Opc = X86ISD::RDTSCP_DAG; break;
12643     }
12644     SmallVector<SDValue, 2> Results;
12645     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12646     return DAG.getMergeValues(&Results[0], Results.size(), dl);
12647   }
12648   // XTEST intrinsics.
12649   case Intrinsic::x86_xtest: {
12650     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12651     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12652     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12653                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12654                                 InTrans);
12655     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12656     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12657                        Ret, SDValue(InTrans.getNode(), 1));
12658   }
12659   }
12660 }
12661
12662 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12663                                            SelectionDAG &DAG) const {
12664   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12665   MFI->setReturnAddressIsTaken(true);
12666
12667   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12668     return SDValue();
12669
12670   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12671   SDLoc dl(Op);
12672   EVT PtrVT = getPointerTy();
12673
12674   if (Depth > 0) {
12675     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12676     const X86RegisterInfo *RegInfo =
12677       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12678     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12679     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12680                        DAG.getNode(ISD::ADD, dl, PtrVT,
12681                                    FrameAddr, Offset),
12682                        MachinePointerInfo(), false, false, false, 0);
12683   }
12684
12685   // Just load the return address.
12686   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12687   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12688                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12689 }
12690
12691 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12692   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12693   MFI->setFrameAddressIsTaken(true);
12694
12695   EVT VT = Op.getValueType();
12696   SDLoc dl(Op);  // FIXME probably not meaningful
12697   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12698   const X86RegisterInfo *RegInfo =
12699     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12700   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12701   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12702           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12703          "Invalid Frame Register!");
12704   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12705   while (Depth--)
12706     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12707                             MachinePointerInfo(),
12708                             false, false, false, 0);
12709   return FrameAddr;
12710 }
12711
12712 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12713                                                      SelectionDAG &DAG) const {
12714   const X86RegisterInfo *RegInfo =
12715     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12716   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12717 }
12718
12719 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12720   SDValue Chain     = Op.getOperand(0);
12721   SDValue Offset    = Op.getOperand(1);
12722   SDValue Handler   = Op.getOperand(2);
12723   SDLoc dl      (Op);
12724
12725   EVT PtrVT = getPointerTy();
12726   const X86RegisterInfo *RegInfo =
12727     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12728   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12729   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12730           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12731          "Invalid Frame Register!");
12732   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12733   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12734
12735   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12736                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12737   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12738   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12739                        false, false, 0);
12740   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12741
12742   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12743                      DAG.getRegister(StoreAddrReg, PtrVT));
12744 }
12745
12746 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12747                                                SelectionDAG &DAG) const {
12748   SDLoc DL(Op);
12749   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12750                      DAG.getVTList(MVT::i32, MVT::Other),
12751                      Op.getOperand(0), Op.getOperand(1));
12752 }
12753
12754 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12755                                                 SelectionDAG &DAG) const {
12756   SDLoc DL(Op);
12757   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12758                      Op.getOperand(0), Op.getOperand(1));
12759 }
12760
12761 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12762   return Op.getOperand(0);
12763 }
12764
12765 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12766                                                 SelectionDAG &DAG) const {
12767   SDValue Root = Op.getOperand(0);
12768   SDValue Trmp = Op.getOperand(1); // trampoline
12769   SDValue FPtr = Op.getOperand(2); // nested function
12770   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12771   SDLoc dl (Op);
12772
12773   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12774   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12775
12776   if (Subtarget->is64Bit()) {
12777     SDValue OutChains[6];
12778
12779     // Large code-model.
12780     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12781     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12782
12783     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12784     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12785
12786     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12787
12788     // Load the pointer to the nested function into R11.
12789     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12790     SDValue Addr = Trmp;
12791     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12792                                 Addr, MachinePointerInfo(TrmpAddr),
12793                                 false, false, 0);
12794
12795     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12796                        DAG.getConstant(2, MVT::i64));
12797     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12798                                 MachinePointerInfo(TrmpAddr, 2),
12799                                 false, false, 2);
12800
12801     // Load the 'nest' parameter value into R10.
12802     // R10 is specified in X86CallingConv.td
12803     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12804     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12805                        DAG.getConstant(10, MVT::i64));
12806     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12807                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12808                                 false, false, 0);
12809
12810     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12811                        DAG.getConstant(12, MVT::i64));
12812     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12813                                 MachinePointerInfo(TrmpAddr, 12),
12814                                 false, false, 2);
12815
12816     // Jump to the nested function.
12817     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12818     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12819                        DAG.getConstant(20, MVT::i64));
12820     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12821                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12822                                 false, false, 0);
12823
12824     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12825     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12826                        DAG.getConstant(22, MVT::i64));
12827     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12828                                 MachinePointerInfo(TrmpAddr, 22),
12829                                 false, false, 0);
12830
12831     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12832   } else {
12833     const Function *Func =
12834       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12835     CallingConv::ID CC = Func->getCallingConv();
12836     unsigned NestReg;
12837
12838     switch (CC) {
12839     default:
12840       llvm_unreachable("Unsupported calling convention");
12841     case CallingConv::C:
12842     case CallingConv::X86_StdCall: {
12843       // Pass 'nest' parameter in ECX.
12844       // Must be kept in sync with X86CallingConv.td
12845       NestReg = X86::ECX;
12846
12847       // Check that ECX wasn't needed by an 'inreg' parameter.
12848       FunctionType *FTy = Func->getFunctionType();
12849       const AttributeSet &Attrs = Func->getAttributes();
12850
12851       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12852         unsigned InRegCount = 0;
12853         unsigned Idx = 1;
12854
12855         for (FunctionType::param_iterator I = FTy->param_begin(),
12856              E = FTy->param_end(); I != E; ++I, ++Idx)
12857           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12858             // FIXME: should only count parameters that are lowered to integers.
12859             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12860
12861         if (InRegCount > 2) {
12862           report_fatal_error("Nest register in use - reduce number of inreg"
12863                              " parameters!");
12864         }
12865       }
12866       break;
12867     }
12868     case CallingConv::X86_FastCall:
12869     case CallingConv::X86_ThisCall:
12870     case CallingConv::Fast:
12871       // Pass 'nest' parameter in EAX.
12872       // Must be kept in sync with X86CallingConv.td
12873       NestReg = X86::EAX;
12874       break;
12875     }
12876
12877     SDValue OutChains[4];
12878     SDValue Addr, Disp;
12879
12880     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12881                        DAG.getConstant(10, MVT::i32));
12882     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12883
12884     // This is storing the opcode for MOV32ri.
12885     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12886     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12887     OutChains[0] = DAG.getStore(Root, dl,
12888                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12889                                 Trmp, MachinePointerInfo(TrmpAddr),
12890                                 false, false, 0);
12891
12892     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12893                        DAG.getConstant(1, MVT::i32));
12894     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12895                                 MachinePointerInfo(TrmpAddr, 1),
12896                                 false, false, 1);
12897
12898     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12899     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12900                        DAG.getConstant(5, MVT::i32));
12901     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12902                                 MachinePointerInfo(TrmpAddr, 5),
12903                                 false, false, 1);
12904
12905     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12906                        DAG.getConstant(6, MVT::i32));
12907     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12908                                 MachinePointerInfo(TrmpAddr, 6),
12909                                 false, false, 1);
12910
12911     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12912   }
12913 }
12914
12915 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12916                                             SelectionDAG &DAG) const {
12917   /*
12918    The rounding mode is in bits 11:10 of FPSR, and has the following
12919    settings:
12920      00 Round to nearest
12921      01 Round to -inf
12922      10 Round to +inf
12923      11 Round to 0
12924
12925   FLT_ROUNDS, on the other hand, expects the following:
12926     -1 Undefined
12927      0 Round to 0
12928      1 Round to nearest
12929      2 Round to +inf
12930      3 Round to -inf
12931
12932   To perform the conversion, we do:
12933     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12934   */
12935
12936   MachineFunction &MF = DAG.getMachineFunction();
12937   const TargetMachine &TM = MF.getTarget();
12938   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12939   unsigned StackAlignment = TFI.getStackAlignment();
12940   MVT VT = Op.getSimpleValueType();
12941   SDLoc DL(Op);
12942
12943   // Save FP Control Word to stack slot
12944   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12945   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12946
12947   MachineMemOperand *MMO =
12948    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12949                            MachineMemOperand::MOStore, 2, 2);
12950
12951   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12952   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12953                                           DAG.getVTList(MVT::Other),
12954                                           Ops, array_lengthof(Ops), MVT::i16,
12955                                           MMO);
12956
12957   // Load FP Control Word from stack slot
12958   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12959                             MachinePointerInfo(), false, false, false, 0);
12960
12961   // Transform as necessary
12962   SDValue CWD1 =
12963     DAG.getNode(ISD::SRL, DL, MVT::i16,
12964                 DAG.getNode(ISD::AND, DL, MVT::i16,
12965                             CWD, DAG.getConstant(0x800, MVT::i16)),
12966                 DAG.getConstant(11, MVT::i8));
12967   SDValue CWD2 =
12968     DAG.getNode(ISD::SRL, DL, MVT::i16,
12969                 DAG.getNode(ISD::AND, DL, MVT::i16,
12970                             CWD, DAG.getConstant(0x400, MVT::i16)),
12971                 DAG.getConstant(9, MVT::i8));
12972
12973   SDValue RetVal =
12974     DAG.getNode(ISD::AND, DL, MVT::i16,
12975                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12976                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12977                             DAG.getConstant(1, MVT::i16)),
12978                 DAG.getConstant(3, MVT::i16));
12979
12980   return DAG.getNode((VT.getSizeInBits() < 16 ?
12981                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12982 }
12983
12984 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12985   MVT VT = Op.getSimpleValueType();
12986   EVT OpVT = VT;
12987   unsigned NumBits = VT.getSizeInBits();
12988   SDLoc dl(Op);
12989
12990   Op = Op.getOperand(0);
12991   if (VT == MVT::i8) {
12992     // Zero extend to i32 since there is not an i8 bsr.
12993     OpVT = MVT::i32;
12994     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12995   }
12996
12997   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12998   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12999   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13000
13001   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13002   SDValue Ops[] = {
13003     Op,
13004     DAG.getConstant(NumBits+NumBits-1, OpVT),
13005     DAG.getConstant(X86::COND_E, MVT::i8),
13006     Op.getValue(1)
13007   };
13008   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
13009
13010   // Finally xor with NumBits-1.
13011   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13012
13013   if (VT == MVT::i8)
13014     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13015   return Op;
13016 }
13017
13018 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13019   MVT VT = Op.getSimpleValueType();
13020   EVT OpVT = VT;
13021   unsigned NumBits = VT.getSizeInBits();
13022   SDLoc dl(Op);
13023
13024   Op = Op.getOperand(0);
13025   if (VT == MVT::i8) {
13026     // Zero extend to i32 since there is not an i8 bsr.
13027     OpVT = MVT::i32;
13028     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13029   }
13030
13031   // Issue a bsr (scan bits in reverse).
13032   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13033   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13034
13035   // And xor with NumBits-1.
13036   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13037
13038   if (VT == MVT::i8)
13039     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13040   return Op;
13041 }
13042
13043 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13044   MVT VT = Op.getSimpleValueType();
13045   unsigned NumBits = VT.getSizeInBits();
13046   SDLoc dl(Op);
13047   Op = Op.getOperand(0);
13048
13049   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13050   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13051   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13052
13053   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13054   SDValue Ops[] = {
13055     Op,
13056     DAG.getConstant(NumBits, VT),
13057     DAG.getConstant(X86::COND_E, MVT::i8),
13058     Op.getValue(1)
13059   };
13060   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
13061 }
13062
13063 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13064 // ones, and then concatenate the result back.
13065 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13066   MVT VT = Op.getSimpleValueType();
13067
13068   assert(VT.is256BitVector() && VT.isInteger() &&
13069          "Unsupported value type for operation");
13070
13071   unsigned NumElems = VT.getVectorNumElements();
13072   SDLoc dl(Op);
13073
13074   // Extract the LHS vectors
13075   SDValue LHS = Op.getOperand(0);
13076   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13077   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13078
13079   // Extract the RHS vectors
13080   SDValue RHS = Op.getOperand(1);
13081   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13082   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13083
13084   MVT EltVT = VT.getVectorElementType();
13085   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13086
13087   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13088                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13089                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13090 }
13091
13092 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13093   assert(Op.getSimpleValueType().is256BitVector() &&
13094          Op.getSimpleValueType().isInteger() &&
13095          "Only handle AVX 256-bit vector integer operation");
13096   return Lower256IntArith(Op, DAG);
13097 }
13098
13099 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13100   assert(Op.getSimpleValueType().is256BitVector() &&
13101          Op.getSimpleValueType().isInteger() &&
13102          "Only handle AVX 256-bit vector integer operation");
13103   return Lower256IntArith(Op, DAG);
13104 }
13105
13106 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13107                         SelectionDAG &DAG) {
13108   SDLoc dl(Op);
13109   MVT VT = Op.getSimpleValueType();
13110
13111   // Decompose 256-bit ops into smaller 128-bit ops.
13112   if (VT.is256BitVector() && !Subtarget->hasInt256())
13113     return Lower256IntArith(Op, DAG);
13114
13115   SDValue A = Op.getOperand(0);
13116   SDValue B = Op.getOperand(1);
13117
13118   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13119   if (VT == MVT::v4i32) {
13120     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13121            "Should not custom lower when pmuldq is available!");
13122
13123     // Extract the odd parts.
13124     static const int UnpackMask[] = { 1, -1, 3, -1 };
13125     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13126     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13127
13128     // Multiply the even parts.
13129     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13130     // Now multiply odd parts.
13131     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13132
13133     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13134     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13135
13136     // Merge the two vectors back together with a shuffle. This expands into 2
13137     // shuffles.
13138     static const int ShufMask[] = { 0, 4, 2, 6 };
13139     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13140   }
13141
13142   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13143          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13144
13145   //  Ahi = psrlqi(a, 32);
13146   //  Bhi = psrlqi(b, 32);
13147   //
13148   //  AloBlo = pmuludq(a, b);
13149   //  AloBhi = pmuludq(a, Bhi);
13150   //  AhiBlo = pmuludq(Ahi, b);
13151
13152   //  AloBhi = psllqi(AloBhi, 32);
13153   //  AhiBlo = psllqi(AhiBlo, 32);
13154   //  return AloBlo + AloBhi + AhiBlo;
13155
13156   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13157   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13158
13159   // Bit cast to 32-bit vectors for MULUDQ
13160   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13161                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13162   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13163   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13164   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13165   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13166
13167   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13168   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13169   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13170
13171   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13172   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13173
13174   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13175   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13176 }
13177
13178 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13179                              SelectionDAG &DAG) {
13180   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13181   EVT VT = Op0.getValueType();
13182   SDLoc dl(Op);
13183
13184   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13185          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13186
13187   // Get the high parts.
13188   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13189   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13190   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13191
13192   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13193   // ints.
13194   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13195   unsigned Opcode =
13196       Op->getOpcode() == ISD::UMUL_LOHI ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13197   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13198                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13199   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13200                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13201
13202   // Shuffle it back into the right order.
13203   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13204   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13205   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13206   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13207
13208   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13209 }
13210
13211 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13212                                          const X86Subtarget *Subtarget) {
13213   MVT VT = Op.getSimpleValueType();
13214   SDLoc dl(Op);
13215   SDValue R = Op.getOperand(0);
13216   SDValue Amt = Op.getOperand(1);
13217
13218   // Optimize shl/srl/sra with constant shift amount.
13219   if (isSplatVector(Amt.getNode())) {
13220     SDValue SclrAmt = Amt->getOperand(0);
13221     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13222       uint64_t ShiftAmt = C->getZExtValue();
13223
13224       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13225           (Subtarget->hasInt256() &&
13226            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13227           (Subtarget->hasAVX512() &&
13228            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13229         if (Op.getOpcode() == ISD::SHL)
13230           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13231                                             DAG);
13232         if (Op.getOpcode() == ISD::SRL)
13233           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13234                                             DAG);
13235         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13236           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13237                                             DAG);
13238       }
13239
13240       if (VT == MVT::v16i8) {
13241         if (Op.getOpcode() == ISD::SHL) {
13242           // Make a large shift.
13243           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13244                                                    MVT::v8i16, R, ShiftAmt,
13245                                                    DAG);
13246           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13247           // Zero out the rightmost bits.
13248           SmallVector<SDValue, 16> V(16,
13249                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13250                                                      MVT::i8));
13251           return DAG.getNode(ISD::AND, dl, VT, SHL,
13252                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13253         }
13254         if (Op.getOpcode() == ISD::SRL) {
13255           // Make a large shift.
13256           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13257                                                    MVT::v8i16, R, ShiftAmt,
13258                                                    DAG);
13259           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13260           // Zero out the leftmost bits.
13261           SmallVector<SDValue, 16> V(16,
13262                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13263                                                      MVT::i8));
13264           return DAG.getNode(ISD::AND, dl, VT, SRL,
13265                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13266         }
13267         if (Op.getOpcode() == ISD::SRA) {
13268           if (ShiftAmt == 7) {
13269             // R s>> 7  ===  R s< 0
13270             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13271             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13272           }
13273
13274           // R s>> a === ((R u>> a) ^ m) - m
13275           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13276           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13277                                                          MVT::i8));
13278           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13279           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13280           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13281           return Res;
13282         }
13283         llvm_unreachable("Unknown shift opcode.");
13284       }
13285
13286       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13287         if (Op.getOpcode() == ISD::SHL) {
13288           // Make a large shift.
13289           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13290                                                    MVT::v16i16, R, ShiftAmt,
13291                                                    DAG);
13292           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13293           // Zero out the rightmost bits.
13294           SmallVector<SDValue, 32> V(32,
13295                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13296                                                      MVT::i8));
13297           return DAG.getNode(ISD::AND, dl, VT, SHL,
13298                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13299         }
13300         if (Op.getOpcode() == ISD::SRL) {
13301           // Make a large shift.
13302           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13303                                                    MVT::v16i16, R, ShiftAmt,
13304                                                    DAG);
13305           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13306           // Zero out the leftmost bits.
13307           SmallVector<SDValue, 32> V(32,
13308                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13309                                                      MVT::i8));
13310           return DAG.getNode(ISD::AND, dl, VT, SRL,
13311                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13312         }
13313         if (Op.getOpcode() == ISD::SRA) {
13314           if (ShiftAmt == 7) {
13315             // R s>> 7  ===  R s< 0
13316             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13317             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13318           }
13319
13320           // R s>> a === ((R u>> a) ^ m) - m
13321           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13322           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13323                                                          MVT::i8));
13324           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13325           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13326           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13327           return Res;
13328         }
13329         llvm_unreachable("Unknown shift opcode.");
13330       }
13331     }
13332   }
13333
13334   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13335   if (!Subtarget->is64Bit() &&
13336       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13337       Amt.getOpcode() == ISD::BITCAST &&
13338       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13339     Amt = Amt.getOperand(0);
13340     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13341                      VT.getVectorNumElements();
13342     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13343     uint64_t ShiftAmt = 0;
13344     for (unsigned i = 0; i != Ratio; ++i) {
13345       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13346       if (!C)
13347         return SDValue();
13348       // 6 == Log2(64)
13349       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13350     }
13351     // Check remaining shift amounts.
13352     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13353       uint64_t ShAmt = 0;
13354       for (unsigned j = 0; j != Ratio; ++j) {
13355         ConstantSDNode *C =
13356           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13357         if (!C)
13358           return SDValue();
13359         // 6 == Log2(64)
13360         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13361       }
13362       if (ShAmt != ShiftAmt)
13363         return SDValue();
13364     }
13365     switch (Op.getOpcode()) {
13366     default:
13367       llvm_unreachable("Unknown shift opcode!");
13368     case ISD::SHL:
13369       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13370                                         DAG);
13371     case ISD::SRL:
13372       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13373                                         DAG);
13374     case ISD::SRA:
13375       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13376                                         DAG);
13377     }
13378   }
13379
13380   return SDValue();
13381 }
13382
13383 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13384                                         const X86Subtarget* Subtarget) {
13385   MVT VT = Op.getSimpleValueType();
13386   SDLoc dl(Op);
13387   SDValue R = Op.getOperand(0);
13388   SDValue Amt = Op.getOperand(1);
13389
13390   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13391       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13392       (Subtarget->hasInt256() &&
13393        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13394         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13395        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13396     SDValue BaseShAmt;
13397     EVT EltVT = VT.getVectorElementType();
13398
13399     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13400       unsigned NumElts = VT.getVectorNumElements();
13401       unsigned i, j;
13402       for (i = 0; i != NumElts; ++i) {
13403         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13404           continue;
13405         break;
13406       }
13407       for (j = i; j != NumElts; ++j) {
13408         SDValue Arg = Amt.getOperand(j);
13409         if (Arg.getOpcode() == ISD::UNDEF) continue;
13410         if (Arg != Amt.getOperand(i))
13411           break;
13412       }
13413       if (i != NumElts && j == NumElts)
13414         BaseShAmt = Amt.getOperand(i);
13415     } else {
13416       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13417         Amt = Amt.getOperand(0);
13418       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13419                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13420         SDValue InVec = Amt.getOperand(0);
13421         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13422           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13423           unsigned i = 0;
13424           for (; i != NumElts; ++i) {
13425             SDValue Arg = InVec.getOperand(i);
13426             if (Arg.getOpcode() == ISD::UNDEF) continue;
13427             BaseShAmt = Arg;
13428             break;
13429           }
13430         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13431            if (ConstantSDNode *C =
13432                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13433              unsigned SplatIdx =
13434                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13435              if (C->getZExtValue() == SplatIdx)
13436                BaseShAmt = InVec.getOperand(1);
13437            }
13438         }
13439         if (!BaseShAmt.getNode())
13440           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13441                                   DAG.getIntPtrConstant(0));
13442       }
13443     }
13444
13445     if (BaseShAmt.getNode()) {
13446       if (EltVT.bitsGT(MVT::i32))
13447         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13448       else if (EltVT.bitsLT(MVT::i32))
13449         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13450
13451       switch (Op.getOpcode()) {
13452       default:
13453         llvm_unreachable("Unknown shift opcode!");
13454       case ISD::SHL:
13455         switch (VT.SimpleTy) {
13456         default: return SDValue();
13457         case MVT::v2i64:
13458         case MVT::v4i32:
13459         case MVT::v8i16:
13460         case MVT::v4i64:
13461         case MVT::v8i32:
13462         case MVT::v16i16:
13463         case MVT::v16i32:
13464         case MVT::v8i64:
13465           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13466         }
13467       case ISD::SRA:
13468         switch (VT.SimpleTy) {
13469         default: return SDValue();
13470         case MVT::v4i32:
13471         case MVT::v8i16:
13472         case MVT::v8i32:
13473         case MVT::v16i16:
13474         case MVT::v16i32:
13475         case MVT::v8i64:
13476           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13477         }
13478       case ISD::SRL:
13479         switch (VT.SimpleTy) {
13480         default: return SDValue();
13481         case MVT::v2i64:
13482         case MVT::v4i32:
13483         case MVT::v8i16:
13484         case MVT::v4i64:
13485         case MVT::v8i32:
13486         case MVT::v16i16:
13487         case MVT::v16i32:
13488         case MVT::v8i64:
13489           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13490         }
13491       }
13492     }
13493   }
13494
13495   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13496   if (!Subtarget->is64Bit() &&
13497       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13498       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13499       Amt.getOpcode() == ISD::BITCAST &&
13500       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13501     Amt = Amt.getOperand(0);
13502     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13503                      VT.getVectorNumElements();
13504     std::vector<SDValue> Vals(Ratio);
13505     for (unsigned i = 0; i != Ratio; ++i)
13506       Vals[i] = Amt.getOperand(i);
13507     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13508       for (unsigned j = 0; j != Ratio; ++j)
13509         if (Vals[j] != Amt.getOperand(i + j))
13510           return SDValue();
13511     }
13512     switch (Op.getOpcode()) {
13513     default:
13514       llvm_unreachable("Unknown shift opcode!");
13515     case ISD::SHL:
13516       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13517     case ISD::SRL:
13518       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13519     case ISD::SRA:
13520       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13521     }
13522   }
13523
13524   return SDValue();
13525 }
13526
13527 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13528                           SelectionDAG &DAG) {
13529
13530   MVT VT = Op.getSimpleValueType();
13531   SDLoc dl(Op);
13532   SDValue R = Op.getOperand(0);
13533   SDValue Amt = Op.getOperand(1);
13534   SDValue V;
13535
13536   if (!Subtarget->hasSSE2())
13537     return SDValue();
13538
13539   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13540   if (V.getNode())
13541     return V;
13542
13543   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13544   if (V.getNode())
13545       return V;
13546
13547   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13548     return Op;
13549   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13550   if (Subtarget->hasInt256()) {
13551     if (Op.getOpcode() == ISD::SRL &&
13552         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13553          VT == MVT::v4i64 || VT == MVT::v8i32))
13554       return Op;
13555     if (Op.getOpcode() == ISD::SHL &&
13556         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13557          VT == MVT::v4i64 || VT == MVT::v8i32))
13558       return Op;
13559     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13560       return Op;
13561   }
13562
13563   // If possible, lower this packed shift into a vector multiply instead of
13564   // expanding it into a sequence of scalar shifts.
13565   // Do this only if the vector shift count is a constant build_vector.
13566   if (Op.getOpcode() == ISD::SHL && 
13567       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13568        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13569       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13570     SmallVector<SDValue, 8> Elts;
13571     EVT SVT = VT.getScalarType();
13572     unsigned SVTBits = SVT.getSizeInBits();
13573     const APInt &One = APInt(SVTBits, 1);
13574     unsigned NumElems = VT.getVectorNumElements();
13575
13576     for (unsigned i=0; i !=NumElems; ++i) {
13577       SDValue Op = Amt->getOperand(i);
13578       if (Op->getOpcode() == ISD::UNDEF) {
13579         Elts.push_back(Op);
13580         continue;
13581       }
13582
13583       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13584       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13585       uint64_t ShAmt = C.getZExtValue();
13586       if (ShAmt >= SVTBits) {
13587         Elts.push_back(DAG.getUNDEF(SVT));
13588         continue;
13589       }
13590       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13591     }
13592     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13593     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13594   }
13595
13596   // Lower SHL with variable shift amount.
13597   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13598     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13599
13600     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13601     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13602     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13603     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13604   }
13605
13606   // If possible, lower this shift as a sequence of two shifts by
13607   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13608   // Example:
13609   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13610   //
13611   // Could be rewritten as:
13612   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13613   //
13614   // The advantage is that the two shifts from the example would be
13615   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13616   // the vector shift into four scalar shifts plus four pairs of vector
13617   // insert/extract.
13618   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13619       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13620     unsigned TargetOpcode = X86ISD::MOVSS;
13621     bool CanBeSimplified;
13622     // The splat value for the first packed shift (the 'X' from the example).
13623     SDValue Amt1 = Amt->getOperand(0);
13624     // The splat value for the second packed shift (the 'Y' from the example).
13625     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13626                                         Amt->getOperand(2);
13627
13628     // See if it is possible to replace this node with a sequence of
13629     // two shifts followed by a MOVSS/MOVSD
13630     if (VT == MVT::v4i32) {
13631       // Check if it is legal to use a MOVSS.
13632       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13633                         Amt2 == Amt->getOperand(3);
13634       if (!CanBeSimplified) {
13635         // Otherwise, check if we can still simplify this node using a MOVSD.
13636         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13637                           Amt->getOperand(2) == Amt->getOperand(3);
13638         TargetOpcode = X86ISD::MOVSD;
13639         Amt2 = Amt->getOperand(2);
13640       }
13641     } else {
13642       // Do similar checks for the case where the machine value type
13643       // is MVT::v8i16.
13644       CanBeSimplified = Amt1 == Amt->getOperand(1);
13645       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13646         CanBeSimplified = Amt2 == Amt->getOperand(i);
13647
13648       if (!CanBeSimplified) {
13649         TargetOpcode = X86ISD::MOVSD;
13650         CanBeSimplified = true;
13651         Amt2 = Amt->getOperand(4);
13652         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13653           CanBeSimplified = Amt1 == Amt->getOperand(i);
13654         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13655           CanBeSimplified = Amt2 == Amt->getOperand(j);
13656       }
13657     }
13658     
13659     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13660         isa<ConstantSDNode>(Amt2)) {
13661       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13662       EVT CastVT = MVT::v4i32;
13663       SDValue Splat1 = 
13664         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13665       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13666       SDValue Splat2 = 
13667         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13668       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13669       if (TargetOpcode == X86ISD::MOVSD)
13670         CastVT = MVT::v2i64;
13671       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13672       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13673       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13674                                             BitCast1, DAG);
13675       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13676     }
13677   }
13678
13679   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13680     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13681
13682     // a = a << 5;
13683     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13684     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13685
13686     // Turn 'a' into a mask suitable for VSELECT
13687     SDValue VSelM = DAG.getConstant(0x80, VT);
13688     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13689     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13690
13691     SDValue CM1 = DAG.getConstant(0x0f, VT);
13692     SDValue CM2 = DAG.getConstant(0x3f, VT);
13693
13694     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13695     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13696     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13697     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13698     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13699
13700     // a += a
13701     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13702     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13703     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13704
13705     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13706     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13707     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13708     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13709     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13710
13711     // a += a
13712     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13713     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13714     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13715
13716     // return VSELECT(r, r+r, a);
13717     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13718                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13719     return R;
13720   }
13721
13722   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13723   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13724   // solution better.
13725   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13726     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13727     unsigned ExtOpc =
13728         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13729     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13730     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13731     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13732                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13733     }
13734
13735   // Decompose 256-bit shifts into smaller 128-bit shifts.
13736   if (VT.is256BitVector()) {
13737     unsigned NumElems = VT.getVectorNumElements();
13738     MVT EltVT = VT.getVectorElementType();
13739     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13740
13741     // Extract the two vectors
13742     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13743     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13744
13745     // Recreate the shift amount vectors
13746     SDValue Amt1, Amt2;
13747     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13748       // Constant shift amount
13749       SmallVector<SDValue, 4> Amt1Csts;
13750       SmallVector<SDValue, 4> Amt2Csts;
13751       for (unsigned i = 0; i != NumElems/2; ++i)
13752         Amt1Csts.push_back(Amt->getOperand(i));
13753       for (unsigned i = NumElems/2; i != NumElems; ++i)
13754         Amt2Csts.push_back(Amt->getOperand(i));
13755
13756       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13757                                  &Amt1Csts[0], NumElems/2);
13758       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13759                                  &Amt2Csts[0], NumElems/2);
13760     } else {
13761       // Variable shift amount
13762       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13763       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13764     }
13765
13766     // Issue new vector shifts for the smaller types
13767     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13768     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13769
13770     // Concatenate the result back
13771     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13772   }
13773
13774   return SDValue();
13775 }
13776
13777 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13778   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13779   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13780   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13781   // has only one use.
13782   SDNode *N = Op.getNode();
13783   SDValue LHS = N->getOperand(0);
13784   SDValue RHS = N->getOperand(1);
13785   unsigned BaseOp = 0;
13786   unsigned Cond = 0;
13787   SDLoc DL(Op);
13788   switch (Op.getOpcode()) {
13789   default: llvm_unreachable("Unknown ovf instruction!");
13790   case ISD::SADDO:
13791     // A subtract of one will be selected as a INC. Note that INC doesn't
13792     // set CF, so we can't do this for UADDO.
13793     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13794       if (C->isOne()) {
13795         BaseOp = X86ISD::INC;
13796         Cond = X86::COND_O;
13797         break;
13798       }
13799     BaseOp = X86ISD::ADD;
13800     Cond = X86::COND_O;
13801     break;
13802   case ISD::UADDO:
13803     BaseOp = X86ISD::ADD;
13804     Cond = X86::COND_B;
13805     break;
13806   case ISD::SSUBO:
13807     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13808     // set CF, so we can't do this for USUBO.
13809     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13810       if (C->isOne()) {
13811         BaseOp = X86ISD::DEC;
13812         Cond = X86::COND_O;
13813         break;
13814       }
13815     BaseOp = X86ISD::SUB;
13816     Cond = X86::COND_O;
13817     break;
13818   case ISD::USUBO:
13819     BaseOp = X86ISD::SUB;
13820     Cond = X86::COND_B;
13821     break;
13822   case ISD::SMULO:
13823     BaseOp = X86ISD::SMUL;
13824     Cond = X86::COND_O;
13825     break;
13826   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13827     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13828                                  MVT::i32);
13829     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13830
13831     SDValue SetCC =
13832       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13833                   DAG.getConstant(X86::COND_O, MVT::i32),
13834                   SDValue(Sum.getNode(), 2));
13835
13836     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13837   }
13838   }
13839
13840   // Also sets EFLAGS.
13841   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13842   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13843
13844   SDValue SetCC =
13845     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13846                 DAG.getConstant(Cond, MVT::i32),
13847                 SDValue(Sum.getNode(), 1));
13848
13849   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13850 }
13851
13852 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13853                                                   SelectionDAG &DAG) const {
13854   SDLoc dl(Op);
13855   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13856   MVT VT = Op.getSimpleValueType();
13857
13858   if (!Subtarget->hasSSE2() || !VT.isVector())
13859     return SDValue();
13860
13861   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13862                       ExtraVT.getScalarType().getSizeInBits();
13863
13864   switch (VT.SimpleTy) {
13865     default: return SDValue();
13866     case MVT::v8i32:
13867     case MVT::v16i16:
13868       if (!Subtarget->hasFp256())
13869         return SDValue();
13870       if (!Subtarget->hasInt256()) {
13871         // needs to be split
13872         unsigned NumElems = VT.getVectorNumElements();
13873
13874         // Extract the LHS vectors
13875         SDValue LHS = Op.getOperand(0);
13876         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13877         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13878
13879         MVT EltVT = VT.getVectorElementType();
13880         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13881
13882         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13883         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13884         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13885                                    ExtraNumElems/2);
13886         SDValue Extra = DAG.getValueType(ExtraVT);
13887
13888         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13889         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13890
13891         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13892       }
13893       // fall through
13894     case MVT::v4i32:
13895     case MVT::v8i16: {
13896       SDValue Op0 = Op.getOperand(0);
13897       SDValue Op00 = Op0.getOperand(0);
13898       SDValue Tmp1;
13899       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13900       if (Op0.getOpcode() == ISD::BITCAST &&
13901           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13902         // (sext (vzext x)) -> (vsext x)
13903         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13904         if (Tmp1.getNode()) {
13905           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13906           // This folding is only valid when the in-reg type is a vector of i8,
13907           // i16, or i32.
13908           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13909               ExtraEltVT == MVT::i32) {
13910             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13911             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13912                    "This optimization is invalid without a VZEXT.");
13913             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13914           }
13915           Op0 = Tmp1;
13916         }
13917       }
13918
13919       // If the above didn't work, then just use Shift-Left + Shift-Right.
13920       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13921                                         DAG);
13922       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13923                                         DAG);
13924     }
13925   }
13926 }
13927
13928 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13929                                  SelectionDAG &DAG) {
13930   SDLoc dl(Op);
13931   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13932     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13933   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13934     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13935
13936   // The only fence that needs an instruction is a sequentially-consistent
13937   // cross-thread fence.
13938   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13939     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13940     // no-sse2). There isn't any reason to disable it if the target processor
13941     // supports it.
13942     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13943       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13944
13945     SDValue Chain = Op.getOperand(0);
13946     SDValue Zero = DAG.getConstant(0, MVT::i32);
13947     SDValue Ops[] = {
13948       DAG.getRegister(X86::ESP, MVT::i32), // Base
13949       DAG.getTargetConstant(1, MVT::i8),   // Scale
13950       DAG.getRegister(0, MVT::i32),        // Index
13951       DAG.getTargetConstant(0, MVT::i32),  // Disp
13952       DAG.getRegister(0, MVT::i32),        // Segment.
13953       Zero,
13954       Chain
13955     };
13956     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13957     return SDValue(Res, 0);
13958   }
13959
13960   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13961   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13962 }
13963
13964 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13965                              SelectionDAG &DAG) {
13966   MVT T = Op.getSimpleValueType();
13967   SDLoc DL(Op);
13968   unsigned Reg = 0;
13969   unsigned size = 0;
13970   switch(T.SimpleTy) {
13971   default: llvm_unreachable("Invalid value type!");
13972   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13973   case MVT::i16: Reg = X86::AX;  size = 2; break;
13974   case MVT::i32: Reg = X86::EAX; size = 4; break;
13975   case MVT::i64:
13976     assert(Subtarget->is64Bit() && "Node not type legal!");
13977     Reg = X86::RAX; size = 8;
13978     break;
13979   }
13980   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13981                                     Op.getOperand(2), SDValue());
13982   SDValue Ops[] = { cpIn.getValue(0),
13983                     Op.getOperand(1),
13984                     Op.getOperand(3),
13985                     DAG.getTargetConstant(size, MVT::i8),
13986                     cpIn.getValue(1) };
13987   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13988   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13989   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13990                                            Ops, array_lengthof(Ops), T, MMO);
13991   SDValue cpOut =
13992     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13993   return cpOut;
13994 }
13995
13996 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13997                             SelectionDAG &DAG) {
13998   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13999   MVT DstVT = Op.getSimpleValueType();
14000   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14001          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14002   assert((DstVT == MVT::i64 ||
14003           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14004          "Unexpected custom BITCAST");
14005   // i64 <=> MMX conversions are Legal.
14006   if (SrcVT==MVT::i64 && DstVT.isVector())
14007     return Op;
14008   if (DstVT==MVT::i64 && SrcVT.isVector())
14009     return Op;
14010   // MMX <=> MMX conversions are Legal.
14011   if (SrcVT.isVector() && DstVT.isVector())
14012     return Op;
14013   // All other conversions need to be expanded.
14014   return SDValue();
14015 }
14016
14017 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14018   SDNode *Node = Op.getNode();
14019   SDLoc dl(Node);
14020   EVT T = Node->getValueType(0);
14021   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14022                               DAG.getConstant(0, T), Node->getOperand(2));
14023   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14024                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14025                        Node->getOperand(0),
14026                        Node->getOperand(1), negOp,
14027                        cast<AtomicSDNode>(Node)->getMemOperand(),
14028                        cast<AtomicSDNode>(Node)->getOrdering(),
14029                        cast<AtomicSDNode>(Node)->getSynchScope());
14030 }
14031
14032 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14033   SDNode *Node = Op.getNode();
14034   SDLoc dl(Node);
14035   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14036
14037   // Convert seq_cst store -> xchg
14038   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14039   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14040   //        (The only way to get a 16-byte store is cmpxchg16b)
14041   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14042   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14043       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14044     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14045                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14046                                  Node->getOperand(0),
14047                                  Node->getOperand(1), Node->getOperand(2),
14048                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14049                                  cast<AtomicSDNode>(Node)->getOrdering(),
14050                                  cast<AtomicSDNode>(Node)->getSynchScope());
14051     return Swap.getValue(1);
14052   }
14053   // Other atomic stores have a simple pattern.
14054   return Op;
14055 }
14056
14057 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14058   EVT VT = Op.getNode()->getSimpleValueType(0);
14059
14060   // Let legalize expand this if it isn't a legal type yet.
14061   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14062     return SDValue();
14063
14064   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14065
14066   unsigned Opc;
14067   bool ExtraOp = false;
14068   switch (Op.getOpcode()) {
14069   default: llvm_unreachable("Invalid code");
14070   case ISD::ADDC: Opc = X86ISD::ADD; break;
14071   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14072   case ISD::SUBC: Opc = X86ISD::SUB; break;
14073   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14074   }
14075
14076   if (!ExtraOp)
14077     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14078                        Op.getOperand(1));
14079   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14080                      Op.getOperand(1), Op.getOperand(2));
14081 }
14082
14083 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14084                             SelectionDAG &DAG) {
14085   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14086
14087   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14088   // which returns the values as { float, float } (in XMM0) or
14089   // { double, double } (which is returned in XMM0, XMM1).
14090   SDLoc dl(Op);
14091   SDValue Arg = Op.getOperand(0);
14092   EVT ArgVT = Arg.getValueType();
14093   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14094
14095   TargetLowering::ArgListTy Args;
14096   TargetLowering::ArgListEntry Entry;
14097
14098   Entry.Node = Arg;
14099   Entry.Ty = ArgTy;
14100   Entry.isSExt = false;
14101   Entry.isZExt = false;
14102   Args.push_back(Entry);
14103
14104   bool isF64 = ArgVT == MVT::f64;
14105   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14106   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14107   // the results are returned via SRet in memory.
14108   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14109   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14110   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14111
14112   Type *RetTy = isF64
14113     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14114     : (Type*)VectorType::get(ArgTy, 4);
14115   TargetLowering::
14116     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14117                          false, false, false, false, 0,
14118                          CallingConv::C, /*isTaillCall=*/false,
14119                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14120                          Callee, Args, DAG, dl);
14121   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14122
14123   if (isF64)
14124     // Returned in xmm0 and xmm1.
14125     return CallResult.first;
14126
14127   // Returned in bits 0:31 and 32:64 xmm0.
14128   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14129                                CallResult.first, DAG.getIntPtrConstant(0));
14130   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14131                                CallResult.first, DAG.getIntPtrConstant(1));
14132   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14133   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14134 }
14135
14136 /// LowerOperation - Provide custom lowering hooks for some operations.
14137 ///
14138 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14139   switch (Op.getOpcode()) {
14140   default: llvm_unreachable("Should not custom lower this!");
14141   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14142   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14143   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14144   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14145   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14146   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14147   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14148   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14149   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14150   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14151   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14152   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14153   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14154   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14155   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14156   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14157   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14158   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14159   case ISD::SHL_PARTS:
14160   case ISD::SRA_PARTS:
14161   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14162   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14163   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14164   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14165   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14166   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14167   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14168   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14169   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14170   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14171   case ISD::FABS:               return LowerFABS(Op, DAG);
14172   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14173   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14174   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14175   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14176   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14177   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14178   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14179   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14180   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14181   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14182   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14183   case ISD::INTRINSIC_VOID:
14184   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14185   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14186   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14187   case ISD::FRAME_TO_ARGS_OFFSET:
14188                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14189   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14190   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14191   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14192   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14193   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14194   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14195   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14196   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14197   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14198   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14199   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14200   case ISD::UMUL_LOHI:
14201   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14202   case ISD::SRA:
14203   case ISD::SRL:
14204   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14205   case ISD::SADDO:
14206   case ISD::UADDO:
14207   case ISD::SSUBO:
14208   case ISD::USUBO:
14209   case ISD::SMULO:
14210   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14211   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14212   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14213   case ISD::ADDC:
14214   case ISD::ADDE:
14215   case ISD::SUBC:
14216   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14217   case ISD::ADD:                return LowerADD(Op, DAG);
14218   case ISD::SUB:                return LowerSUB(Op, DAG);
14219   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14220   }
14221 }
14222
14223 static void ReplaceATOMIC_LOAD(SDNode *Node,
14224                                   SmallVectorImpl<SDValue> &Results,
14225                                   SelectionDAG &DAG) {
14226   SDLoc dl(Node);
14227   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14228
14229   // Convert wide load -> cmpxchg8b/cmpxchg16b
14230   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14231   //        (The only way to get a 16-byte load is cmpxchg16b)
14232   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14233   SDValue Zero = DAG.getConstant(0, VT);
14234   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14235                                Node->getOperand(0),
14236                                Node->getOperand(1), Zero, Zero,
14237                                cast<AtomicSDNode>(Node)->getMemOperand(),
14238                                cast<AtomicSDNode>(Node)->getOrdering(),
14239                                cast<AtomicSDNode>(Node)->getOrdering(),
14240                                cast<AtomicSDNode>(Node)->getSynchScope());
14241   Results.push_back(Swap.getValue(0));
14242   Results.push_back(Swap.getValue(1));
14243 }
14244
14245 static void
14246 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14247                         SelectionDAG &DAG, unsigned NewOp) {
14248   SDLoc dl(Node);
14249   assert (Node->getValueType(0) == MVT::i64 &&
14250           "Only know how to expand i64 atomics");
14251
14252   SDValue Chain = Node->getOperand(0);
14253   SDValue In1 = Node->getOperand(1);
14254   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14255                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14256   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14257                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14258   SDValue Ops[] = { Chain, In1, In2L, In2H };
14259   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14260   SDValue Result =
14261     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14262                             cast<MemSDNode>(Node)->getMemOperand());
14263   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14264   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14265   Results.push_back(Result.getValue(2));
14266 }
14267
14268 /// ReplaceNodeResults - Replace a node with an illegal result type
14269 /// with a new node built out of custom code.
14270 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14271                                            SmallVectorImpl<SDValue>&Results,
14272                                            SelectionDAG &DAG) const {
14273   SDLoc dl(N);
14274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14275   switch (N->getOpcode()) {
14276   default:
14277     llvm_unreachable("Do not know how to custom type legalize this operation!");
14278   case ISD::SIGN_EXTEND_INREG:
14279   case ISD::ADDC:
14280   case ISD::ADDE:
14281   case ISD::SUBC:
14282   case ISD::SUBE:
14283     // We don't want to expand or promote these.
14284     return;
14285   case ISD::FP_TO_SINT:
14286   case ISD::FP_TO_UINT: {
14287     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14288
14289     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14290       return;
14291
14292     std::pair<SDValue,SDValue> Vals =
14293         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14294     SDValue FIST = Vals.first, StackSlot = Vals.second;
14295     if (FIST.getNode()) {
14296       EVT VT = N->getValueType(0);
14297       // Return a load from the stack slot.
14298       if (StackSlot.getNode())
14299         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14300                                       MachinePointerInfo(),
14301                                       false, false, false, 0));
14302       else
14303         Results.push_back(FIST);
14304     }
14305     return;
14306   }
14307   case ISD::UINT_TO_FP: {
14308     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14309     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14310         N->getValueType(0) != MVT::v2f32)
14311       return;
14312     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14313                                  N->getOperand(0));
14314     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14315                                      MVT::f64);
14316     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14317     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14318                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14319     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14320     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14321     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14322     return;
14323   }
14324   case ISD::FP_ROUND: {
14325     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14326         return;
14327     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14328     Results.push_back(V);
14329     return;
14330   }
14331   case ISD::INTRINSIC_W_CHAIN: {
14332     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14333     switch (IntNo) {
14334     default : llvm_unreachable("Do not know how to custom type "
14335                                "legalize this intrinsic operation!");
14336     case Intrinsic::x86_rdtsc:
14337       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14338                                      Results);
14339     case Intrinsic::x86_rdtscp:
14340       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14341                                      Results);
14342     }
14343   }
14344   case ISD::READCYCLECOUNTER: {
14345     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14346                                    Results);
14347   }
14348   case ISD::ATOMIC_CMP_SWAP: {
14349     EVT T = N->getValueType(0);
14350     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14351     bool Regs64bit = T == MVT::i128;
14352     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14353     SDValue cpInL, cpInH;
14354     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14355                         DAG.getConstant(0, HalfT));
14356     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14357                         DAG.getConstant(1, HalfT));
14358     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14359                              Regs64bit ? X86::RAX : X86::EAX,
14360                              cpInL, SDValue());
14361     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14362                              Regs64bit ? X86::RDX : X86::EDX,
14363                              cpInH, cpInL.getValue(1));
14364     SDValue swapInL, swapInH;
14365     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14366                           DAG.getConstant(0, HalfT));
14367     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14368                           DAG.getConstant(1, HalfT));
14369     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14370                                Regs64bit ? X86::RBX : X86::EBX,
14371                                swapInL, cpInH.getValue(1));
14372     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14373                                Regs64bit ? X86::RCX : X86::ECX,
14374                                swapInH, swapInL.getValue(1));
14375     SDValue Ops[] = { swapInH.getValue(0),
14376                       N->getOperand(1),
14377                       swapInH.getValue(1) };
14378     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14379     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14380     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14381                                   X86ISD::LCMPXCHG8_DAG;
14382     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14383                                              Ops, array_lengthof(Ops), T, MMO);
14384     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14385                                         Regs64bit ? X86::RAX : X86::EAX,
14386                                         HalfT, Result.getValue(1));
14387     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14388                                         Regs64bit ? X86::RDX : X86::EDX,
14389                                         HalfT, cpOutL.getValue(2));
14390     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14391     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14392     Results.push_back(cpOutH.getValue(1));
14393     return;
14394   }
14395   case ISD::ATOMIC_LOAD_ADD:
14396   case ISD::ATOMIC_LOAD_AND:
14397   case ISD::ATOMIC_LOAD_NAND:
14398   case ISD::ATOMIC_LOAD_OR:
14399   case ISD::ATOMIC_LOAD_SUB:
14400   case ISD::ATOMIC_LOAD_XOR:
14401   case ISD::ATOMIC_LOAD_MAX:
14402   case ISD::ATOMIC_LOAD_MIN:
14403   case ISD::ATOMIC_LOAD_UMAX:
14404   case ISD::ATOMIC_LOAD_UMIN:
14405   case ISD::ATOMIC_SWAP: {
14406     unsigned Opc;
14407     switch (N->getOpcode()) {
14408     default: llvm_unreachable("Unexpected opcode");
14409     case ISD::ATOMIC_LOAD_ADD:
14410       Opc = X86ISD::ATOMADD64_DAG;
14411       break;
14412     case ISD::ATOMIC_LOAD_AND:
14413       Opc = X86ISD::ATOMAND64_DAG;
14414       break;
14415     case ISD::ATOMIC_LOAD_NAND:
14416       Opc = X86ISD::ATOMNAND64_DAG;
14417       break;
14418     case ISD::ATOMIC_LOAD_OR:
14419       Opc = X86ISD::ATOMOR64_DAG;
14420       break;
14421     case ISD::ATOMIC_LOAD_SUB:
14422       Opc = X86ISD::ATOMSUB64_DAG;
14423       break;
14424     case ISD::ATOMIC_LOAD_XOR:
14425       Opc = X86ISD::ATOMXOR64_DAG;
14426       break;
14427     case ISD::ATOMIC_LOAD_MAX:
14428       Opc = X86ISD::ATOMMAX64_DAG;
14429       break;
14430     case ISD::ATOMIC_LOAD_MIN:
14431       Opc = X86ISD::ATOMMIN64_DAG;
14432       break;
14433     case ISD::ATOMIC_LOAD_UMAX:
14434       Opc = X86ISD::ATOMUMAX64_DAG;
14435       break;
14436     case ISD::ATOMIC_LOAD_UMIN:
14437       Opc = X86ISD::ATOMUMIN64_DAG;
14438       break;
14439     case ISD::ATOMIC_SWAP:
14440       Opc = X86ISD::ATOMSWAP64_DAG;
14441       break;
14442     }
14443     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14444     return;
14445   }
14446   case ISD::ATOMIC_LOAD:
14447     ReplaceATOMIC_LOAD(N, Results, DAG);
14448   }
14449 }
14450
14451 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14452   switch (Opcode) {
14453   default: return nullptr;
14454   case X86ISD::BSF:                return "X86ISD::BSF";
14455   case X86ISD::BSR:                return "X86ISD::BSR";
14456   case X86ISD::SHLD:               return "X86ISD::SHLD";
14457   case X86ISD::SHRD:               return "X86ISD::SHRD";
14458   case X86ISD::FAND:               return "X86ISD::FAND";
14459   case X86ISD::FANDN:              return "X86ISD::FANDN";
14460   case X86ISD::FOR:                return "X86ISD::FOR";
14461   case X86ISD::FXOR:               return "X86ISD::FXOR";
14462   case X86ISD::FSRL:               return "X86ISD::FSRL";
14463   case X86ISD::FILD:               return "X86ISD::FILD";
14464   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14465   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14466   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14467   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14468   case X86ISD::FLD:                return "X86ISD::FLD";
14469   case X86ISD::FST:                return "X86ISD::FST";
14470   case X86ISD::CALL:               return "X86ISD::CALL";
14471   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14472   case X86ISD::BT:                 return "X86ISD::BT";
14473   case X86ISD::CMP:                return "X86ISD::CMP";
14474   case X86ISD::COMI:               return "X86ISD::COMI";
14475   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14476   case X86ISD::CMPM:               return "X86ISD::CMPM";
14477   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14478   case X86ISD::SETCC:              return "X86ISD::SETCC";
14479   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14480   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14481   case X86ISD::CMOV:               return "X86ISD::CMOV";
14482   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14483   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14484   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14485   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14486   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14487   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14488   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14489   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14490   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14491   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14492   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14493   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14494   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14495   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14496   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14497   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14498   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14499   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14500   case X86ISD::HADD:               return "X86ISD::HADD";
14501   case X86ISD::HSUB:               return "X86ISD::HSUB";
14502   case X86ISD::FHADD:              return "X86ISD::FHADD";
14503   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14504   case X86ISD::UMAX:               return "X86ISD::UMAX";
14505   case X86ISD::UMIN:               return "X86ISD::UMIN";
14506   case X86ISD::SMAX:               return "X86ISD::SMAX";
14507   case X86ISD::SMIN:               return "X86ISD::SMIN";
14508   case X86ISD::FMAX:               return "X86ISD::FMAX";
14509   case X86ISD::FMIN:               return "X86ISD::FMIN";
14510   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14511   case X86ISD::FMINC:              return "X86ISD::FMINC";
14512   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14513   case X86ISD::FRCP:               return "X86ISD::FRCP";
14514   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14515   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14516   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14517   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14518   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14519   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14520   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14521   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14522   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14523   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14524   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14525   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14526   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14527   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14528   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14529   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14530   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14531   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14532   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14533   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14534   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14535   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14536   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14537   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14538   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14539   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14540   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14541   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14542   case X86ISD::VSHL:               return "X86ISD::VSHL";
14543   case X86ISD::VSRL:               return "X86ISD::VSRL";
14544   case X86ISD::VSRA:               return "X86ISD::VSRA";
14545   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14546   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14547   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14548   case X86ISD::CMPP:               return "X86ISD::CMPP";
14549   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14550   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14551   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14552   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14553   case X86ISD::ADD:                return "X86ISD::ADD";
14554   case X86ISD::SUB:                return "X86ISD::SUB";
14555   case X86ISD::ADC:                return "X86ISD::ADC";
14556   case X86ISD::SBB:                return "X86ISD::SBB";
14557   case X86ISD::SMUL:               return "X86ISD::SMUL";
14558   case X86ISD::UMUL:               return "X86ISD::UMUL";
14559   case X86ISD::INC:                return "X86ISD::INC";
14560   case X86ISD::DEC:                return "X86ISD::DEC";
14561   case X86ISD::OR:                 return "X86ISD::OR";
14562   case X86ISD::XOR:                return "X86ISD::XOR";
14563   case X86ISD::AND:                return "X86ISD::AND";
14564   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14565   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14566   case X86ISD::PTEST:              return "X86ISD::PTEST";
14567   case X86ISD::TESTP:              return "X86ISD::TESTP";
14568   case X86ISD::TESTM:              return "X86ISD::TESTM";
14569   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14570   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14571   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14572   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14573   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14574   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14575   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14576   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14577   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14578   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14579   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14580   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14581   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14582   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14583   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14584   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14585   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14586   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14587   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14588   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14589   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14590   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14591   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14592   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14593   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14594   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14595   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14596   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14597   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14598   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14599   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14600   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14601   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14602   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14603   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14604   case X86ISD::SAHF:               return "X86ISD::SAHF";
14605   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14606   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14607   case X86ISD::FMADD:              return "X86ISD::FMADD";
14608   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14609   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14610   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14611   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14612   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14613   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14614   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14615   case X86ISD::XTEST:              return "X86ISD::XTEST";
14616   }
14617 }
14618
14619 // isLegalAddressingMode - Return true if the addressing mode represented
14620 // by AM is legal for this target, for a load/store of the specified type.
14621 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14622                                               Type *Ty) const {
14623   // X86 supports extremely general addressing modes.
14624   CodeModel::Model M = getTargetMachine().getCodeModel();
14625   Reloc::Model R = getTargetMachine().getRelocationModel();
14626
14627   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14628   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14629     return false;
14630
14631   if (AM.BaseGV) {
14632     unsigned GVFlags =
14633       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14634
14635     // If a reference to this global requires an extra load, we can't fold it.
14636     if (isGlobalStubReference(GVFlags))
14637       return false;
14638
14639     // If BaseGV requires a register for the PIC base, we cannot also have a
14640     // BaseReg specified.
14641     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14642       return false;
14643
14644     // If lower 4G is not available, then we must use rip-relative addressing.
14645     if ((M != CodeModel::Small || R != Reloc::Static) &&
14646         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14647       return false;
14648   }
14649
14650   switch (AM.Scale) {
14651   case 0:
14652   case 1:
14653   case 2:
14654   case 4:
14655   case 8:
14656     // These scales always work.
14657     break;
14658   case 3:
14659   case 5:
14660   case 9:
14661     // These scales are formed with basereg+scalereg.  Only accept if there is
14662     // no basereg yet.
14663     if (AM.HasBaseReg)
14664       return false;
14665     break;
14666   default:  // Other stuff never works.
14667     return false;
14668   }
14669
14670   return true;
14671 }
14672
14673 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14674   unsigned Bits = Ty->getScalarSizeInBits();
14675
14676   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14677   // particularly cheaper than those without.
14678   if (Bits == 8)
14679     return false;
14680
14681   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14682   // variable shifts just as cheap as scalar ones.
14683   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14684     return false;
14685
14686   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14687   // fully general vector.
14688   return true;
14689 }
14690
14691 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14692   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14693     return false;
14694   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14695   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14696   return NumBits1 > NumBits2;
14697 }
14698
14699 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14700   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14701     return false;
14702
14703   if (!isTypeLegal(EVT::getEVT(Ty1)))
14704     return false;
14705
14706   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14707
14708   // Assuming the caller doesn't have a zeroext or signext return parameter,
14709   // truncation all the way down to i1 is valid.
14710   return true;
14711 }
14712
14713 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14714   return isInt<32>(Imm);
14715 }
14716
14717 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14718   // Can also use sub to handle negated immediates.
14719   return isInt<32>(Imm);
14720 }
14721
14722 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14723   if (!VT1.isInteger() || !VT2.isInteger())
14724     return false;
14725   unsigned NumBits1 = VT1.getSizeInBits();
14726   unsigned NumBits2 = VT2.getSizeInBits();
14727   return NumBits1 > NumBits2;
14728 }
14729
14730 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14731   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14732   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14733 }
14734
14735 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14736   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14737   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14738 }
14739
14740 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14741   EVT VT1 = Val.getValueType();
14742   if (isZExtFree(VT1, VT2))
14743     return true;
14744
14745   if (Val.getOpcode() != ISD::LOAD)
14746     return false;
14747
14748   if (!VT1.isSimple() || !VT1.isInteger() ||
14749       !VT2.isSimple() || !VT2.isInteger())
14750     return false;
14751
14752   switch (VT1.getSimpleVT().SimpleTy) {
14753   default: break;
14754   case MVT::i8:
14755   case MVT::i16:
14756   case MVT::i32:
14757     // X86 has 8, 16, and 32-bit zero-extending loads.
14758     return true;
14759   }
14760
14761   return false;
14762 }
14763
14764 bool
14765 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14766   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14767     return false;
14768
14769   VT = VT.getScalarType();
14770
14771   if (!VT.isSimple())
14772     return false;
14773
14774   switch (VT.getSimpleVT().SimpleTy) {
14775   case MVT::f32:
14776   case MVT::f64:
14777     return true;
14778   default:
14779     break;
14780   }
14781
14782   return false;
14783 }
14784
14785 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14786   // i16 instructions are longer (0x66 prefix) and potentially slower.
14787   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14788 }
14789
14790 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14791 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14792 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14793 /// are assumed to be legal.
14794 bool
14795 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14796                                       EVT VT) const {
14797   if (!VT.isSimple())
14798     return false;
14799
14800   MVT SVT = VT.getSimpleVT();
14801
14802   // Very little shuffling can be done for 64-bit vectors right now.
14803   if (VT.getSizeInBits() == 64)
14804     return false;
14805
14806   // FIXME: pshufb, blends, shifts.
14807   return (SVT.getVectorNumElements() == 2 ||
14808           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14809           isMOVLMask(M, SVT) ||
14810           isSHUFPMask(M, SVT) ||
14811           isPSHUFDMask(M, SVT) ||
14812           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14813           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14814           isPALIGNRMask(M, SVT, Subtarget) ||
14815           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14816           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14817           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14818           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14819 }
14820
14821 bool
14822 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14823                                           EVT VT) const {
14824   if (!VT.isSimple())
14825     return false;
14826
14827   MVT SVT = VT.getSimpleVT();
14828   unsigned NumElts = SVT.getVectorNumElements();
14829   // FIXME: This collection of masks seems suspect.
14830   if (NumElts == 2)
14831     return true;
14832   if (NumElts == 4 && SVT.is128BitVector()) {
14833     return (isMOVLMask(Mask, SVT)  ||
14834             isCommutedMOVLMask(Mask, SVT, true) ||
14835             isSHUFPMask(Mask, SVT) ||
14836             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14837   }
14838   return false;
14839 }
14840
14841 //===----------------------------------------------------------------------===//
14842 //                           X86 Scheduler Hooks
14843 //===----------------------------------------------------------------------===//
14844
14845 /// Utility function to emit xbegin specifying the start of an RTM region.
14846 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14847                                      const TargetInstrInfo *TII) {
14848   DebugLoc DL = MI->getDebugLoc();
14849
14850   const BasicBlock *BB = MBB->getBasicBlock();
14851   MachineFunction::iterator I = MBB;
14852   ++I;
14853
14854   // For the v = xbegin(), we generate
14855   //
14856   // thisMBB:
14857   //  xbegin sinkMBB
14858   //
14859   // mainMBB:
14860   //  eax = -1
14861   //
14862   // sinkMBB:
14863   //  v = eax
14864
14865   MachineBasicBlock *thisMBB = MBB;
14866   MachineFunction *MF = MBB->getParent();
14867   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14868   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14869   MF->insert(I, mainMBB);
14870   MF->insert(I, sinkMBB);
14871
14872   // Transfer the remainder of BB and its successor edges to sinkMBB.
14873   sinkMBB->splice(sinkMBB->begin(), MBB,
14874                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14875   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14876
14877   // thisMBB:
14878   //  xbegin sinkMBB
14879   //  # fallthrough to mainMBB
14880   //  # abortion to sinkMBB
14881   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14882   thisMBB->addSuccessor(mainMBB);
14883   thisMBB->addSuccessor(sinkMBB);
14884
14885   // mainMBB:
14886   //  EAX = -1
14887   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14888   mainMBB->addSuccessor(sinkMBB);
14889
14890   // sinkMBB:
14891   // EAX is live into the sinkMBB
14892   sinkMBB->addLiveIn(X86::EAX);
14893   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14894           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14895     .addReg(X86::EAX);
14896
14897   MI->eraseFromParent();
14898   return sinkMBB;
14899 }
14900
14901 // Get CMPXCHG opcode for the specified data type.
14902 static unsigned getCmpXChgOpcode(EVT VT) {
14903   switch (VT.getSimpleVT().SimpleTy) {
14904   case MVT::i8:  return X86::LCMPXCHG8;
14905   case MVT::i16: return X86::LCMPXCHG16;
14906   case MVT::i32: return X86::LCMPXCHG32;
14907   case MVT::i64: return X86::LCMPXCHG64;
14908   default:
14909     break;
14910   }
14911   llvm_unreachable("Invalid operand size!");
14912 }
14913
14914 // Get LOAD opcode for the specified data type.
14915 static unsigned getLoadOpcode(EVT VT) {
14916   switch (VT.getSimpleVT().SimpleTy) {
14917   case MVT::i8:  return X86::MOV8rm;
14918   case MVT::i16: return X86::MOV16rm;
14919   case MVT::i32: return X86::MOV32rm;
14920   case MVT::i64: return X86::MOV64rm;
14921   default:
14922     break;
14923   }
14924   llvm_unreachable("Invalid operand size!");
14925 }
14926
14927 // Get opcode of the non-atomic one from the specified atomic instruction.
14928 static unsigned getNonAtomicOpcode(unsigned Opc) {
14929   switch (Opc) {
14930   case X86::ATOMAND8:  return X86::AND8rr;
14931   case X86::ATOMAND16: return X86::AND16rr;
14932   case X86::ATOMAND32: return X86::AND32rr;
14933   case X86::ATOMAND64: return X86::AND64rr;
14934   case X86::ATOMOR8:   return X86::OR8rr;
14935   case X86::ATOMOR16:  return X86::OR16rr;
14936   case X86::ATOMOR32:  return X86::OR32rr;
14937   case X86::ATOMOR64:  return X86::OR64rr;
14938   case X86::ATOMXOR8:  return X86::XOR8rr;
14939   case X86::ATOMXOR16: return X86::XOR16rr;
14940   case X86::ATOMXOR32: return X86::XOR32rr;
14941   case X86::ATOMXOR64: return X86::XOR64rr;
14942   }
14943   llvm_unreachable("Unhandled atomic-load-op opcode!");
14944 }
14945
14946 // Get opcode of the non-atomic one from the specified atomic instruction with
14947 // extra opcode.
14948 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14949                                                unsigned &ExtraOpc) {
14950   switch (Opc) {
14951   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14952   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14953   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14954   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14955   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14956   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14957   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14958   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14959   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14960   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14961   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14962   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14963   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14964   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14965   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14966   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14967   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14968   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14969   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14970   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14971   }
14972   llvm_unreachable("Unhandled atomic-load-op opcode!");
14973 }
14974
14975 // Get opcode of the non-atomic one from the specified atomic instruction for
14976 // 64-bit data type on 32-bit target.
14977 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14978   switch (Opc) {
14979   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14980   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14981   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14982   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14983   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14984   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14985   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14986   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14987   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14988   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14989   }
14990   llvm_unreachable("Unhandled atomic-load-op opcode!");
14991 }
14992
14993 // Get opcode of the non-atomic one from the specified atomic instruction for
14994 // 64-bit data type on 32-bit target with extra opcode.
14995 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14996                                                    unsigned &HiOpc,
14997                                                    unsigned &ExtraOpc) {
14998   switch (Opc) {
14999   case X86::ATOMNAND6432:
15000     ExtraOpc = X86::NOT32r;
15001     HiOpc = X86::AND32rr;
15002     return X86::AND32rr;
15003   }
15004   llvm_unreachable("Unhandled atomic-load-op opcode!");
15005 }
15006
15007 // Get pseudo CMOV opcode from the specified data type.
15008 static unsigned getPseudoCMOVOpc(EVT VT) {
15009   switch (VT.getSimpleVT().SimpleTy) {
15010   case MVT::i8:  return X86::CMOV_GR8;
15011   case MVT::i16: return X86::CMOV_GR16;
15012   case MVT::i32: return X86::CMOV_GR32;
15013   default:
15014     break;
15015   }
15016   llvm_unreachable("Unknown CMOV opcode!");
15017 }
15018
15019 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15020 // They will be translated into a spin-loop or compare-exchange loop from
15021 //
15022 //    ...
15023 //    dst = atomic-fetch-op MI.addr, MI.val
15024 //    ...
15025 //
15026 // to
15027 //
15028 //    ...
15029 //    t1 = LOAD MI.addr
15030 // loop:
15031 //    t4 = phi(t1, t3 / loop)
15032 //    t2 = OP MI.val, t4
15033 //    EAX = t4
15034 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15035 //    t3 = EAX
15036 //    JNE loop
15037 // sink:
15038 //    dst = t3
15039 //    ...
15040 MachineBasicBlock *
15041 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15042                                        MachineBasicBlock *MBB) const {
15043   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15044   DebugLoc DL = MI->getDebugLoc();
15045
15046   MachineFunction *MF = MBB->getParent();
15047   MachineRegisterInfo &MRI = MF->getRegInfo();
15048
15049   const BasicBlock *BB = MBB->getBasicBlock();
15050   MachineFunction::iterator I = MBB;
15051   ++I;
15052
15053   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15054          "Unexpected number of operands");
15055
15056   assert(MI->hasOneMemOperand() &&
15057          "Expected atomic-load-op to have one memoperand");
15058
15059   // Memory Reference
15060   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15061   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15062
15063   unsigned DstReg, SrcReg;
15064   unsigned MemOpndSlot;
15065
15066   unsigned CurOp = 0;
15067
15068   DstReg = MI->getOperand(CurOp++).getReg();
15069   MemOpndSlot = CurOp;
15070   CurOp += X86::AddrNumOperands;
15071   SrcReg = MI->getOperand(CurOp++).getReg();
15072
15073   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15074   MVT::SimpleValueType VT = *RC->vt_begin();
15075   unsigned t1 = MRI.createVirtualRegister(RC);
15076   unsigned t2 = MRI.createVirtualRegister(RC);
15077   unsigned t3 = MRI.createVirtualRegister(RC);
15078   unsigned t4 = MRI.createVirtualRegister(RC);
15079   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15080
15081   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15082   unsigned LOADOpc = getLoadOpcode(VT);
15083
15084   // For the atomic load-arith operator, we generate
15085   //
15086   //  thisMBB:
15087   //    t1 = LOAD [MI.addr]
15088   //  mainMBB:
15089   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15090   //    t1 = OP MI.val, EAX
15091   //    EAX = t4
15092   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15093   //    t3 = EAX
15094   //    JNE mainMBB
15095   //  sinkMBB:
15096   //    dst = t3
15097
15098   MachineBasicBlock *thisMBB = MBB;
15099   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15100   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15101   MF->insert(I, mainMBB);
15102   MF->insert(I, sinkMBB);
15103
15104   MachineInstrBuilder MIB;
15105
15106   // Transfer the remainder of BB and its successor edges to sinkMBB.
15107   sinkMBB->splice(sinkMBB->begin(), MBB,
15108                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15109   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15110
15111   // thisMBB:
15112   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15113   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15114     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15115     if (NewMO.isReg())
15116       NewMO.setIsKill(false);
15117     MIB.addOperand(NewMO);
15118   }
15119   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15120     unsigned flags = (*MMOI)->getFlags();
15121     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15122     MachineMemOperand *MMO =
15123       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15124                                (*MMOI)->getSize(),
15125                                (*MMOI)->getBaseAlignment(),
15126                                (*MMOI)->getTBAAInfo(),
15127                                (*MMOI)->getRanges());
15128     MIB.addMemOperand(MMO);
15129   }
15130
15131   thisMBB->addSuccessor(mainMBB);
15132
15133   // mainMBB:
15134   MachineBasicBlock *origMainMBB = mainMBB;
15135
15136   // Add a PHI.
15137   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15138                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15139
15140   unsigned Opc = MI->getOpcode();
15141   switch (Opc) {
15142   default:
15143     llvm_unreachable("Unhandled atomic-load-op opcode!");
15144   case X86::ATOMAND8:
15145   case X86::ATOMAND16:
15146   case X86::ATOMAND32:
15147   case X86::ATOMAND64:
15148   case X86::ATOMOR8:
15149   case X86::ATOMOR16:
15150   case X86::ATOMOR32:
15151   case X86::ATOMOR64:
15152   case X86::ATOMXOR8:
15153   case X86::ATOMXOR16:
15154   case X86::ATOMXOR32:
15155   case X86::ATOMXOR64: {
15156     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15157     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15158       .addReg(t4);
15159     break;
15160   }
15161   case X86::ATOMNAND8:
15162   case X86::ATOMNAND16:
15163   case X86::ATOMNAND32:
15164   case X86::ATOMNAND64: {
15165     unsigned Tmp = MRI.createVirtualRegister(RC);
15166     unsigned NOTOpc;
15167     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15168     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15169       .addReg(t4);
15170     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15171     break;
15172   }
15173   case X86::ATOMMAX8:
15174   case X86::ATOMMAX16:
15175   case X86::ATOMMAX32:
15176   case X86::ATOMMAX64:
15177   case X86::ATOMMIN8:
15178   case X86::ATOMMIN16:
15179   case X86::ATOMMIN32:
15180   case X86::ATOMMIN64:
15181   case X86::ATOMUMAX8:
15182   case X86::ATOMUMAX16:
15183   case X86::ATOMUMAX32:
15184   case X86::ATOMUMAX64:
15185   case X86::ATOMUMIN8:
15186   case X86::ATOMUMIN16:
15187   case X86::ATOMUMIN32:
15188   case X86::ATOMUMIN64: {
15189     unsigned CMPOpc;
15190     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15191
15192     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15193       .addReg(SrcReg)
15194       .addReg(t4);
15195
15196     if (Subtarget->hasCMov()) {
15197       if (VT != MVT::i8) {
15198         // Native support
15199         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15200           .addReg(SrcReg)
15201           .addReg(t4);
15202       } else {
15203         // Promote i8 to i32 to use CMOV32
15204         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15205         const TargetRegisterClass *RC32 =
15206           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15207         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15208         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15209         unsigned Tmp = MRI.createVirtualRegister(RC32);
15210
15211         unsigned Undef = MRI.createVirtualRegister(RC32);
15212         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15213
15214         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15215           .addReg(Undef)
15216           .addReg(SrcReg)
15217           .addImm(X86::sub_8bit);
15218         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15219           .addReg(Undef)
15220           .addReg(t4)
15221           .addImm(X86::sub_8bit);
15222
15223         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15224           .addReg(SrcReg32)
15225           .addReg(AccReg32);
15226
15227         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15228           .addReg(Tmp, 0, X86::sub_8bit);
15229       }
15230     } else {
15231       // Use pseudo select and lower them.
15232       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15233              "Invalid atomic-load-op transformation!");
15234       unsigned SelOpc = getPseudoCMOVOpc(VT);
15235       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15236       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15237       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15238               .addReg(SrcReg).addReg(t4)
15239               .addImm(CC);
15240       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15241       // Replace the original PHI node as mainMBB is changed after CMOV
15242       // lowering.
15243       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15244         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15245       Phi->eraseFromParent();
15246     }
15247     break;
15248   }
15249   }
15250
15251   // Copy PhyReg back from virtual register.
15252   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15253     .addReg(t4);
15254
15255   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15256   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15257     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15258     if (NewMO.isReg())
15259       NewMO.setIsKill(false);
15260     MIB.addOperand(NewMO);
15261   }
15262   MIB.addReg(t2);
15263   MIB.setMemRefs(MMOBegin, MMOEnd);
15264
15265   // Copy PhyReg back to virtual register.
15266   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15267     .addReg(PhyReg);
15268
15269   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15270
15271   mainMBB->addSuccessor(origMainMBB);
15272   mainMBB->addSuccessor(sinkMBB);
15273
15274   // sinkMBB:
15275   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15276           TII->get(TargetOpcode::COPY), DstReg)
15277     .addReg(t3);
15278
15279   MI->eraseFromParent();
15280   return sinkMBB;
15281 }
15282
15283 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15284 // instructions. They will be translated into a spin-loop or compare-exchange
15285 // loop from
15286 //
15287 //    ...
15288 //    dst = atomic-fetch-op MI.addr, MI.val
15289 //    ...
15290 //
15291 // to
15292 //
15293 //    ...
15294 //    t1L = LOAD [MI.addr + 0]
15295 //    t1H = LOAD [MI.addr + 4]
15296 // loop:
15297 //    t4L = phi(t1L, t3L / loop)
15298 //    t4H = phi(t1H, t3H / loop)
15299 //    t2L = OP MI.val.lo, t4L
15300 //    t2H = OP MI.val.hi, t4H
15301 //    EAX = t4L
15302 //    EDX = t4H
15303 //    EBX = t2L
15304 //    ECX = t2H
15305 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15306 //    t3L = EAX
15307 //    t3H = EDX
15308 //    JNE loop
15309 // sink:
15310 //    dstL = t3L
15311 //    dstH = t3H
15312 //    ...
15313 MachineBasicBlock *
15314 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15315                                            MachineBasicBlock *MBB) const {
15316   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15317   DebugLoc DL = MI->getDebugLoc();
15318
15319   MachineFunction *MF = MBB->getParent();
15320   MachineRegisterInfo &MRI = MF->getRegInfo();
15321
15322   const BasicBlock *BB = MBB->getBasicBlock();
15323   MachineFunction::iterator I = MBB;
15324   ++I;
15325
15326   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15327          "Unexpected number of operands");
15328
15329   assert(MI->hasOneMemOperand() &&
15330          "Expected atomic-load-op32 to have one memoperand");
15331
15332   // Memory Reference
15333   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15334   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15335
15336   unsigned DstLoReg, DstHiReg;
15337   unsigned SrcLoReg, SrcHiReg;
15338   unsigned MemOpndSlot;
15339
15340   unsigned CurOp = 0;
15341
15342   DstLoReg = MI->getOperand(CurOp++).getReg();
15343   DstHiReg = MI->getOperand(CurOp++).getReg();
15344   MemOpndSlot = CurOp;
15345   CurOp += X86::AddrNumOperands;
15346   SrcLoReg = MI->getOperand(CurOp++).getReg();
15347   SrcHiReg = MI->getOperand(CurOp++).getReg();
15348
15349   const TargetRegisterClass *RC = &X86::GR32RegClass;
15350   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15351
15352   unsigned t1L = MRI.createVirtualRegister(RC);
15353   unsigned t1H = MRI.createVirtualRegister(RC);
15354   unsigned t2L = MRI.createVirtualRegister(RC);
15355   unsigned t2H = MRI.createVirtualRegister(RC);
15356   unsigned t3L = MRI.createVirtualRegister(RC);
15357   unsigned t3H = MRI.createVirtualRegister(RC);
15358   unsigned t4L = MRI.createVirtualRegister(RC);
15359   unsigned t4H = MRI.createVirtualRegister(RC);
15360
15361   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15362   unsigned LOADOpc = X86::MOV32rm;
15363
15364   // For the atomic load-arith operator, we generate
15365   //
15366   //  thisMBB:
15367   //    t1L = LOAD [MI.addr + 0]
15368   //    t1H = LOAD [MI.addr + 4]
15369   //  mainMBB:
15370   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15371   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15372   //    t2L = OP MI.val.lo, t4L
15373   //    t2H = OP MI.val.hi, t4H
15374   //    EBX = t2L
15375   //    ECX = t2H
15376   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15377   //    t3L = EAX
15378   //    t3H = EDX
15379   //    JNE loop
15380   //  sinkMBB:
15381   //    dstL = t3L
15382   //    dstH = t3H
15383
15384   MachineBasicBlock *thisMBB = MBB;
15385   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15386   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15387   MF->insert(I, mainMBB);
15388   MF->insert(I, sinkMBB);
15389
15390   MachineInstrBuilder MIB;
15391
15392   // Transfer the remainder of BB and its successor edges to sinkMBB.
15393   sinkMBB->splice(sinkMBB->begin(), MBB,
15394                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15395   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15396
15397   // thisMBB:
15398   // Lo
15399   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15400   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15401     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15402     if (NewMO.isReg())
15403       NewMO.setIsKill(false);
15404     MIB.addOperand(NewMO);
15405   }
15406   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15407     unsigned flags = (*MMOI)->getFlags();
15408     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15409     MachineMemOperand *MMO =
15410       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15411                                (*MMOI)->getSize(),
15412                                (*MMOI)->getBaseAlignment(),
15413                                (*MMOI)->getTBAAInfo(),
15414                                (*MMOI)->getRanges());
15415     MIB.addMemOperand(MMO);
15416   };
15417   MachineInstr *LowMI = MIB;
15418
15419   // Hi
15420   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15421   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15422     if (i == X86::AddrDisp) {
15423       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15424     } else {
15425       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15426       if (NewMO.isReg())
15427         NewMO.setIsKill(false);
15428       MIB.addOperand(NewMO);
15429     }
15430   }
15431   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15432
15433   thisMBB->addSuccessor(mainMBB);
15434
15435   // mainMBB:
15436   MachineBasicBlock *origMainMBB = mainMBB;
15437
15438   // Add PHIs.
15439   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15440                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15441   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15442                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15443
15444   unsigned Opc = MI->getOpcode();
15445   switch (Opc) {
15446   default:
15447     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15448   case X86::ATOMAND6432:
15449   case X86::ATOMOR6432:
15450   case X86::ATOMXOR6432:
15451   case X86::ATOMADD6432:
15452   case X86::ATOMSUB6432: {
15453     unsigned HiOpc;
15454     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15455     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15456       .addReg(SrcLoReg);
15457     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15458       .addReg(SrcHiReg);
15459     break;
15460   }
15461   case X86::ATOMNAND6432: {
15462     unsigned HiOpc, NOTOpc;
15463     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15464     unsigned TmpL = MRI.createVirtualRegister(RC);
15465     unsigned TmpH = MRI.createVirtualRegister(RC);
15466     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15467       .addReg(t4L);
15468     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15469       .addReg(t4H);
15470     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15471     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15472     break;
15473   }
15474   case X86::ATOMMAX6432:
15475   case X86::ATOMMIN6432:
15476   case X86::ATOMUMAX6432:
15477   case X86::ATOMUMIN6432: {
15478     unsigned HiOpc;
15479     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15480     unsigned cL = MRI.createVirtualRegister(RC8);
15481     unsigned cH = MRI.createVirtualRegister(RC8);
15482     unsigned cL32 = MRI.createVirtualRegister(RC);
15483     unsigned cH32 = MRI.createVirtualRegister(RC);
15484     unsigned cc = MRI.createVirtualRegister(RC);
15485     // cl := cmp src_lo, lo
15486     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15487       .addReg(SrcLoReg).addReg(t4L);
15488     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15489     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15490     // ch := cmp src_hi, hi
15491     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15492       .addReg(SrcHiReg).addReg(t4H);
15493     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15494     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15495     // cc := if (src_hi == hi) ? cl : ch;
15496     if (Subtarget->hasCMov()) {
15497       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15498         .addReg(cH32).addReg(cL32);
15499     } else {
15500       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15501               .addReg(cH32).addReg(cL32)
15502               .addImm(X86::COND_E);
15503       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15504     }
15505     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15506     if (Subtarget->hasCMov()) {
15507       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15508         .addReg(SrcLoReg).addReg(t4L);
15509       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15510         .addReg(SrcHiReg).addReg(t4H);
15511     } else {
15512       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15513               .addReg(SrcLoReg).addReg(t4L)
15514               .addImm(X86::COND_NE);
15515       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15516       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15517       // 2nd CMOV lowering.
15518       mainMBB->addLiveIn(X86::EFLAGS);
15519       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15520               .addReg(SrcHiReg).addReg(t4H)
15521               .addImm(X86::COND_NE);
15522       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15523       // Replace the original PHI node as mainMBB is changed after CMOV
15524       // lowering.
15525       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15526         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15527       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15528         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15529       PhiL->eraseFromParent();
15530       PhiH->eraseFromParent();
15531     }
15532     break;
15533   }
15534   case X86::ATOMSWAP6432: {
15535     unsigned HiOpc;
15536     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15537     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15538     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15539     break;
15540   }
15541   }
15542
15543   // Copy EDX:EAX back from HiReg:LoReg
15544   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15545   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15546   // Copy ECX:EBX from t1H:t1L
15547   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15548   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15549
15550   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15551   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15552     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15553     if (NewMO.isReg())
15554       NewMO.setIsKill(false);
15555     MIB.addOperand(NewMO);
15556   }
15557   MIB.setMemRefs(MMOBegin, MMOEnd);
15558
15559   // Copy EDX:EAX back to t3H:t3L
15560   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15561   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15562
15563   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15564
15565   mainMBB->addSuccessor(origMainMBB);
15566   mainMBB->addSuccessor(sinkMBB);
15567
15568   // sinkMBB:
15569   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15570           TII->get(TargetOpcode::COPY), DstLoReg)
15571     .addReg(t3L);
15572   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15573           TII->get(TargetOpcode::COPY), DstHiReg)
15574     .addReg(t3H);
15575
15576   MI->eraseFromParent();
15577   return sinkMBB;
15578 }
15579
15580 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15581 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15582 // in the .td file.
15583 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15584                                        const TargetInstrInfo *TII) {
15585   unsigned Opc;
15586   switch (MI->getOpcode()) {
15587   default: llvm_unreachable("illegal opcode!");
15588   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15589   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15590   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15591   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15592   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15593   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15594   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15595   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15596   }
15597
15598   DebugLoc dl = MI->getDebugLoc();
15599   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15600
15601   unsigned NumArgs = MI->getNumOperands();
15602   for (unsigned i = 1; i < NumArgs; ++i) {
15603     MachineOperand &Op = MI->getOperand(i);
15604     if (!(Op.isReg() && Op.isImplicit()))
15605       MIB.addOperand(Op);
15606   }
15607   if (MI->hasOneMemOperand())
15608     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15609
15610   BuildMI(*BB, MI, dl,
15611     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15612     .addReg(X86::XMM0);
15613
15614   MI->eraseFromParent();
15615   return BB;
15616 }
15617
15618 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15619 // defs in an instruction pattern
15620 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15621                                        const TargetInstrInfo *TII) {
15622   unsigned Opc;
15623   switch (MI->getOpcode()) {
15624   default: llvm_unreachable("illegal opcode!");
15625   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15626   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15627   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15628   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15629   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15630   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15631   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15632   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15633   }
15634
15635   DebugLoc dl = MI->getDebugLoc();
15636   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15637
15638   unsigned NumArgs = MI->getNumOperands(); // remove the results
15639   for (unsigned i = 1; i < NumArgs; ++i) {
15640     MachineOperand &Op = MI->getOperand(i);
15641     if (!(Op.isReg() && Op.isImplicit()))
15642       MIB.addOperand(Op);
15643   }
15644   if (MI->hasOneMemOperand())
15645     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15646
15647   BuildMI(*BB, MI, dl,
15648     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15649     .addReg(X86::ECX);
15650
15651   MI->eraseFromParent();
15652   return BB;
15653 }
15654
15655 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15656                                        const TargetInstrInfo *TII,
15657                                        const X86Subtarget* Subtarget) {
15658   DebugLoc dl = MI->getDebugLoc();
15659
15660   // Address into RAX/EAX, other two args into ECX, EDX.
15661   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15662   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15663   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15664   for (int i = 0; i < X86::AddrNumOperands; ++i)
15665     MIB.addOperand(MI->getOperand(i));
15666
15667   unsigned ValOps = X86::AddrNumOperands;
15668   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15669     .addReg(MI->getOperand(ValOps).getReg());
15670   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15671     .addReg(MI->getOperand(ValOps+1).getReg());
15672
15673   // The instruction doesn't actually take any operands though.
15674   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15675
15676   MI->eraseFromParent(); // The pseudo is gone now.
15677   return BB;
15678 }
15679
15680 MachineBasicBlock *
15681 X86TargetLowering::EmitVAARG64WithCustomInserter(
15682                    MachineInstr *MI,
15683                    MachineBasicBlock *MBB) const {
15684   // Emit va_arg instruction on X86-64.
15685
15686   // Operands to this pseudo-instruction:
15687   // 0  ) Output        : destination address (reg)
15688   // 1-5) Input         : va_list address (addr, i64mem)
15689   // 6  ) ArgSize       : Size (in bytes) of vararg type
15690   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15691   // 8  ) Align         : Alignment of type
15692   // 9  ) EFLAGS (implicit-def)
15693
15694   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15695   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15696
15697   unsigned DestReg = MI->getOperand(0).getReg();
15698   MachineOperand &Base = MI->getOperand(1);
15699   MachineOperand &Scale = MI->getOperand(2);
15700   MachineOperand &Index = MI->getOperand(3);
15701   MachineOperand &Disp = MI->getOperand(4);
15702   MachineOperand &Segment = MI->getOperand(5);
15703   unsigned ArgSize = MI->getOperand(6).getImm();
15704   unsigned ArgMode = MI->getOperand(7).getImm();
15705   unsigned Align = MI->getOperand(8).getImm();
15706
15707   // Memory Reference
15708   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15709   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15710   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15711
15712   // Machine Information
15713   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15714   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15715   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15716   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15717   DebugLoc DL = MI->getDebugLoc();
15718
15719   // struct va_list {
15720   //   i32   gp_offset
15721   //   i32   fp_offset
15722   //   i64   overflow_area (address)
15723   //   i64   reg_save_area (address)
15724   // }
15725   // sizeof(va_list) = 24
15726   // alignment(va_list) = 8
15727
15728   unsigned TotalNumIntRegs = 6;
15729   unsigned TotalNumXMMRegs = 8;
15730   bool UseGPOffset = (ArgMode == 1);
15731   bool UseFPOffset = (ArgMode == 2);
15732   unsigned MaxOffset = TotalNumIntRegs * 8 +
15733                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15734
15735   /* Align ArgSize to a multiple of 8 */
15736   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15737   bool NeedsAlign = (Align > 8);
15738
15739   MachineBasicBlock *thisMBB = MBB;
15740   MachineBasicBlock *overflowMBB;
15741   MachineBasicBlock *offsetMBB;
15742   MachineBasicBlock *endMBB;
15743
15744   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15745   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15746   unsigned OffsetReg = 0;
15747
15748   if (!UseGPOffset && !UseFPOffset) {
15749     // If we only pull from the overflow region, we don't create a branch.
15750     // We don't need to alter control flow.
15751     OffsetDestReg = 0; // unused
15752     OverflowDestReg = DestReg;
15753
15754     offsetMBB = nullptr;
15755     overflowMBB = thisMBB;
15756     endMBB = thisMBB;
15757   } else {
15758     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15759     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15760     // If not, pull from overflow_area. (branch to overflowMBB)
15761     //
15762     //       thisMBB
15763     //         |     .
15764     //         |        .
15765     //     offsetMBB   overflowMBB
15766     //         |        .
15767     //         |     .
15768     //        endMBB
15769
15770     // Registers for the PHI in endMBB
15771     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15772     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15773
15774     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15775     MachineFunction *MF = MBB->getParent();
15776     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15777     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15778     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15779
15780     MachineFunction::iterator MBBIter = MBB;
15781     ++MBBIter;
15782
15783     // Insert the new basic blocks
15784     MF->insert(MBBIter, offsetMBB);
15785     MF->insert(MBBIter, overflowMBB);
15786     MF->insert(MBBIter, endMBB);
15787
15788     // Transfer the remainder of MBB and its successor edges to endMBB.
15789     endMBB->splice(endMBB->begin(), thisMBB,
15790                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15791     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15792
15793     // Make offsetMBB and overflowMBB successors of thisMBB
15794     thisMBB->addSuccessor(offsetMBB);
15795     thisMBB->addSuccessor(overflowMBB);
15796
15797     // endMBB is a successor of both offsetMBB and overflowMBB
15798     offsetMBB->addSuccessor(endMBB);
15799     overflowMBB->addSuccessor(endMBB);
15800
15801     // Load the offset value into a register
15802     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15803     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15804       .addOperand(Base)
15805       .addOperand(Scale)
15806       .addOperand(Index)
15807       .addDisp(Disp, UseFPOffset ? 4 : 0)
15808       .addOperand(Segment)
15809       .setMemRefs(MMOBegin, MMOEnd);
15810
15811     // Check if there is enough room left to pull this argument.
15812     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15813       .addReg(OffsetReg)
15814       .addImm(MaxOffset + 8 - ArgSizeA8);
15815
15816     // Branch to "overflowMBB" if offset >= max
15817     // Fall through to "offsetMBB" otherwise
15818     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15819       .addMBB(overflowMBB);
15820   }
15821
15822   // In offsetMBB, emit code to use the reg_save_area.
15823   if (offsetMBB) {
15824     assert(OffsetReg != 0);
15825
15826     // Read the reg_save_area address.
15827     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15828     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15829       .addOperand(Base)
15830       .addOperand(Scale)
15831       .addOperand(Index)
15832       .addDisp(Disp, 16)
15833       .addOperand(Segment)
15834       .setMemRefs(MMOBegin, MMOEnd);
15835
15836     // Zero-extend the offset
15837     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15838       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15839         .addImm(0)
15840         .addReg(OffsetReg)
15841         .addImm(X86::sub_32bit);
15842
15843     // Add the offset to the reg_save_area to get the final address.
15844     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15845       .addReg(OffsetReg64)
15846       .addReg(RegSaveReg);
15847
15848     // Compute the offset for the next argument
15849     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15850     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15851       .addReg(OffsetReg)
15852       .addImm(UseFPOffset ? 16 : 8);
15853
15854     // Store it back into the va_list.
15855     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15856       .addOperand(Base)
15857       .addOperand(Scale)
15858       .addOperand(Index)
15859       .addDisp(Disp, UseFPOffset ? 4 : 0)
15860       .addOperand(Segment)
15861       .addReg(NextOffsetReg)
15862       .setMemRefs(MMOBegin, MMOEnd);
15863
15864     // Jump to endMBB
15865     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15866       .addMBB(endMBB);
15867   }
15868
15869   //
15870   // Emit code to use overflow area
15871   //
15872
15873   // Load the overflow_area address into a register.
15874   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15875   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15876     .addOperand(Base)
15877     .addOperand(Scale)
15878     .addOperand(Index)
15879     .addDisp(Disp, 8)
15880     .addOperand(Segment)
15881     .setMemRefs(MMOBegin, MMOEnd);
15882
15883   // If we need to align it, do so. Otherwise, just copy the address
15884   // to OverflowDestReg.
15885   if (NeedsAlign) {
15886     // Align the overflow address
15887     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15888     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15889
15890     // aligned_addr = (addr + (align-1)) & ~(align-1)
15891     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15892       .addReg(OverflowAddrReg)
15893       .addImm(Align-1);
15894
15895     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15896       .addReg(TmpReg)
15897       .addImm(~(uint64_t)(Align-1));
15898   } else {
15899     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15900       .addReg(OverflowAddrReg);
15901   }
15902
15903   // Compute the next overflow address after this argument.
15904   // (the overflow address should be kept 8-byte aligned)
15905   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15906   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15907     .addReg(OverflowDestReg)
15908     .addImm(ArgSizeA8);
15909
15910   // Store the new overflow address.
15911   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15912     .addOperand(Base)
15913     .addOperand(Scale)
15914     .addOperand(Index)
15915     .addDisp(Disp, 8)
15916     .addOperand(Segment)
15917     .addReg(NextAddrReg)
15918     .setMemRefs(MMOBegin, MMOEnd);
15919
15920   // If we branched, emit the PHI to the front of endMBB.
15921   if (offsetMBB) {
15922     BuildMI(*endMBB, endMBB->begin(), DL,
15923             TII->get(X86::PHI), DestReg)
15924       .addReg(OffsetDestReg).addMBB(offsetMBB)
15925       .addReg(OverflowDestReg).addMBB(overflowMBB);
15926   }
15927
15928   // Erase the pseudo instruction
15929   MI->eraseFromParent();
15930
15931   return endMBB;
15932 }
15933
15934 MachineBasicBlock *
15935 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15936                                                  MachineInstr *MI,
15937                                                  MachineBasicBlock *MBB) const {
15938   // Emit code to save XMM registers to the stack. The ABI says that the
15939   // number of registers to save is given in %al, so it's theoretically
15940   // possible to do an indirect jump trick to avoid saving all of them,
15941   // however this code takes a simpler approach and just executes all
15942   // of the stores if %al is non-zero. It's less code, and it's probably
15943   // easier on the hardware branch predictor, and stores aren't all that
15944   // expensive anyway.
15945
15946   // Create the new basic blocks. One block contains all the XMM stores,
15947   // and one block is the final destination regardless of whether any
15948   // stores were performed.
15949   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15950   MachineFunction *F = MBB->getParent();
15951   MachineFunction::iterator MBBIter = MBB;
15952   ++MBBIter;
15953   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15954   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15955   F->insert(MBBIter, XMMSaveMBB);
15956   F->insert(MBBIter, EndMBB);
15957
15958   // Transfer the remainder of MBB and its successor edges to EndMBB.
15959   EndMBB->splice(EndMBB->begin(), MBB,
15960                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15961   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15962
15963   // The original block will now fall through to the XMM save block.
15964   MBB->addSuccessor(XMMSaveMBB);
15965   // The XMMSaveMBB will fall through to the end block.
15966   XMMSaveMBB->addSuccessor(EndMBB);
15967
15968   // Now add the instructions.
15969   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15970   DebugLoc DL = MI->getDebugLoc();
15971
15972   unsigned CountReg = MI->getOperand(0).getReg();
15973   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15974   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15975
15976   if (!Subtarget->isTargetWin64()) {
15977     // If %al is 0, branch around the XMM save block.
15978     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15979     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15980     MBB->addSuccessor(EndMBB);
15981   }
15982
15983   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15984   // that was just emitted, but clearly shouldn't be "saved".
15985   assert((MI->getNumOperands() <= 3 ||
15986           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15987           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15988          && "Expected last argument to be EFLAGS");
15989   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15990   // In the XMM save block, save all the XMM argument registers.
15991   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15992     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15993     MachineMemOperand *MMO =
15994       F->getMachineMemOperand(
15995           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15996         MachineMemOperand::MOStore,
15997         /*Size=*/16, /*Align=*/16);
15998     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15999       .addFrameIndex(RegSaveFrameIndex)
16000       .addImm(/*Scale=*/1)
16001       .addReg(/*IndexReg=*/0)
16002       .addImm(/*Disp=*/Offset)
16003       .addReg(/*Segment=*/0)
16004       .addReg(MI->getOperand(i).getReg())
16005       .addMemOperand(MMO);
16006   }
16007
16008   MI->eraseFromParent();   // The pseudo instruction is gone now.
16009
16010   return EndMBB;
16011 }
16012
16013 // The EFLAGS operand of SelectItr might be missing a kill marker
16014 // because there were multiple uses of EFLAGS, and ISel didn't know
16015 // which to mark. Figure out whether SelectItr should have had a
16016 // kill marker, and set it if it should. Returns the correct kill
16017 // marker value.
16018 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16019                                      MachineBasicBlock* BB,
16020                                      const TargetRegisterInfo* TRI) {
16021   // Scan forward through BB for a use/def of EFLAGS.
16022   MachineBasicBlock::iterator miI(std::next(SelectItr));
16023   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16024     const MachineInstr& mi = *miI;
16025     if (mi.readsRegister(X86::EFLAGS))
16026       return false;
16027     if (mi.definesRegister(X86::EFLAGS))
16028       break; // Should have kill-flag - update below.
16029   }
16030
16031   // If we hit the end of the block, check whether EFLAGS is live into a
16032   // successor.
16033   if (miI == BB->end()) {
16034     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16035                                           sEnd = BB->succ_end();
16036          sItr != sEnd; ++sItr) {
16037       MachineBasicBlock* succ = *sItr;
16038       if (succ->isLiveIn(X86::EFLAGS))
16039         return false;
16040     }
16041   }
16042
16043   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16044   // out. SelectMI should have a kill flag on EFLAGS.
16045   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16046   return true;
16047 }
16048
16049 MachineBasicBlock *
16050 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16051                                      MachineBasicBlock *BB) const {
16052   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16053   DebugLoc DL = MI->getDebugLoc();
16054
16055   // To "insert" a SELECT_CC instruction, we actually have to insert the
16056   // diamond control-flow pattern.  The incoming instruction knows the
16057   // destination vreg to set, the condition code register to branch on, the
16058   // true/false values to select between, and a branch opcode to use.
16059   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16060   MachineFunction::iterator It = BB;
16061   ++It;
16062
16063   //  thisMBB:
16064   //  ...
16065   //   TrueVal = ...
16066   //   cmpTY ccX, r1, r2
16067   //   bCC copy1MBB
16068   //   fallthrough --> copy0MBB
16069   MachineBasicBlock *thisMBB = BB;
16070   MachineFunction *F = BB->getParent();
16071   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16072   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16073   F->insert(It, copy0MBB);
16074   F->insert(It, sinkMBB);
16075
16076   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16077   // live into the sink and copy blocks.
16078   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16079   if (!MI->killsRegister(X86::EFLAGS) &&
16080       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16081     copy0MBB->addLiveIn(X86::EFLAGS);
16082     sinkMBB->addLiveIn(X86::EFLAGS);
16083   }
16084
16085   // Transfer the remainder of BB and its successor edges to sinkMBB.
16086   sinkMBB->splice(sinkMBB->begin(), BB,
16087                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16088   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16089
16090   // Add the true and fallthrough blocks as its successors.
16091   BB->addSuccessor(copy0MBB);
16092   BB->addSuccessor(sinkMBB);
16093
16094   // Create the conditional branch instruction.
16095   unsigned Opc =
16096     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16097   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16098
16099   //  copy0MBB:
16100   //   %FalseValue = ...
16101   //   # fallthrough to sinkMBB
16102   copy0MBB->addSuccessor(sinkMBB);
16103
16104   //  sinkMBB:
16105   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16106   //  ...
16107   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16108           TII->get(X86::PHI), MI->getOperand(0).getReg())
16109     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16110     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16111
16112   MI->eraseFromParent();   // The pseudo instruction is gone now.
16113   return sinkMBB;
16114 }
16115
16116 MachineBasicBlock *
16117 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16118                                         bool Is64Bit) const {
16119   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16120   DebugLoc DL = MI->getDebugLoc();
16121   MachineFunction *MF = BB->getParent();
16122   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16123
16124   assert(MF->shouldSplitStack());
16125
16126   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16127   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16128
16129   // BB:
16130   //  ... [Till the alloca]
16131   // If stacklet is not large enough, jump to mallocMBB
16132   //
16133   // bumpMBB:
16134   //  Allocate by subtracting from RSP
16135   //  Jump to continueMBB
16136   //
16137   // mallocMBB:
16138   //  Allocate by call to runtime
16139   //
16140   // continueMBB:
16141   //  ...
16142   //  [rest of original BB]
16143   //
16144
16145   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16146   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16147   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16148
16149   MachineRegisterInfo &MRI = MF->getRegInfo();
16150   const TargetRegisterClass *AddrRegClass =
16151     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16152
16153   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16154     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16155     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16156     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16157     sizeVReg = MI->getOperand(1).getReg(),
16158     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16159
16160   MachineFunction::iterator MBBIter = BB;
16161   ++MBBIter;
16162
16163   MF->insert(MBBIter, bumpMBB);
16164   MF->insert(MBBIter, mallocMBB);
16165   MF->insert(MBBIter, continueMBB);
16166
16167   continueMBB->splice(continueMBB->begin(), BB,
16168                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16169   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16170
16171   // Add code to the main basic block to check if the stack limit has been hit,
16172   // and if so, jump to mallocMBB otherwise to bumpMBB.
16173   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16174   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16175     .addReg(tmpSPVReg).addReg(sizeVReg);
16176   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16177     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16178     .addReg(SPLimitVReg);
16179   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16180
16181   // bumpMBB simply decreases the stack pointer, since we know the current
16182   // stacklet has enough space.
16183   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16184     .addReg(SPLimitVReg);
16185   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16186     .addReg(SPLimitVReg);
16187   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16188
16189   // Calls into a routine in libgcc to allocate more space from the heap.
16190   const uint32_t *RegMask =
16191     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16192   if (Is64Bit) {
16193     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16194       .addReg(sizeVReg);
16195     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16196       .addExternalSymbol("__morestack_allocate_stack_space")
16197       .addRegMask(RegMask)
16198       .addReg(X86::RDI, RegState::Implicit)
16199       .addReg(X86::RAX, RegState::ImplicitDefine);
16200   } else {
16201     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16202       .addImm(12);
16203     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16204     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16205       .addExternalSymbol("__morestack_allocate_stack_space")
16206       .addRegMask(RegMask)
16207       .addReg(X86::EAX, RegState::ImplicitDefine);
16208   }
16209
16210   if (!Is64Bit)
16211     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16212       .addImm(16);
16213
16214   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16215     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16216   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16217
16218   // Set up the CFG correctly.
16219   BB->addSuccessor(bumpMBB);
16220   BB->addSuccessor(mallocMBB);
16221   mallocMBB->addSuccessor(continueMBB);
16222   bumpMBB->addSuccessor(continueMBB);
16223
16224   // Take care of the PHI nodes.
16225   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16226           MI->getOperand(0).getReg())
16227     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16228     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16229
16230   // Delete the original pseudo instruction.
16231   MI->eraseFromParent();
16232
16233   // And we're done.
16234   return continueMBB;
16235 }
16236
16237 MachineBasicBlock *
16238 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16239                                           MachineBasicBlock *BB) const {
16240   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16241   DebugLoc DL = MI->getDebugLoc();
16242
16243   assert(!Subtarget->isTargetMacho());
16244
16245   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16246   // non-trivial part is impdef of ESP.
16247
16248   if (Subtarget->isTargetWin64()) {
16249     if (Subtarget->isTargetCygMing()) {
16250       // ___chkstk(Mingw64):
16251       // Clobbers R10, R11, RAX and EFLAGS.
16252       // Updates RSP.
16253       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16254         .addExternalSymbol("___chkstk")
16255         .addReg(X86::RAX, RegState::Implicit)
16256         .addReg(X86::RSP, RegState::Implicit)
16257         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16258         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16259         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16260     } else {
16261       // __chkstk(MSVCRT): does not update stack pointer.
16262       // Clobbers R10, R11 and EFLAGS.
16263       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16264         .addExternalSymbol("__chkstk")
16265         .addReg(X86::RAX, RegState::Implicit)
16266         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16267       // RAX has the offset to be subtracted from RSP.
16268       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16269         .addReg(X86::RSP)
16270         .addReg(X86::RAX);
16271     }
16272   } else {
16273     const char *StackProbeSymbol =
16274       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16275
16276     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16277       .addExternalSymbol(StackProbeSymbol)
16278       .addReg(X86::EAX, RegState::Implicit)
16279       .addReg(X86::ESP, RegState::Implicit)
16280       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16281       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16282       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16283   }
16284
16285   MI->eraseFromParent();   // The pseudo instruction is gone now.
16286   return BB;
16287 }
16288
16289 MachineBasicBlock *
16290 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16291                                       MachineBasicBlock *BB) const {
16292   // This is pretty easy.  We're taking the value that we received from
16293   // our load from the relocation, sticking it in either RDI (x86-64)
16294   // or EAX and doing an indirect call.  The return value will then
16295   // be in the normal return register.
16296   const X86InstrInfo *TII
16297     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16298   DebugLoc DL = MI->getDebugLoc();
16299   MachineFunction *F = BB->getParent();
16300
16301   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16302   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16303
16304   // Get a register mask for the lowered call.
16305   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16306   // proper register mask.
16307   const uint32_t *RegMask =
16308     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16309   if (Subtarget->is64Bit()) {
16310     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16311                                       TII->get(X86::MOV64rm), X86::RDI)
16312     .addReg(X86::RIP)
16313     .addImm(0).addReg(0)
16314     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16315                       MI->getOperand(3).getTargetFlags())
16316     .addReg(0);
16317     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16318     addDirectMem(MIB, X86::RDI);
16319     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16320   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16321     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16322                                       TII->get(X86::MOV32rm), X86::EAX)
16323     .addReg(0)
16324     .addImm(0).addReg(0)
16325     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16326                       MI->getOperand(3).getTargetFlags())
16327     .addReg(0);
16328     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16329     addDirectMem(MIB, X86::EAX);
16330     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16331   } else {
16332     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16333                                       TII->get(X86::MOV32rm), X86::EAX)
16334     .addReg(TII->getGlobalBaseReg(F))
16335     .addImm(0).addReg(0)
16336     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16337                       MI->getOperand(3).getTargetFlags())
16338     .addReg(0);
16339     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16340     addDirectMem(MIB, X86::EAX);
16341     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16342   }
16343
16344   MI->eraseFromParent(); // The pseudo instruction is gone now.
16345   return BB;
16346 }
16347
16348 MachineBasicBlock *
16349 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16350                                     MachineBasicBlock *MBB) const {
16351   DebugLoc DL = MI->getDebugLoc();
16352   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16353
16354   MachineFunction *MF = MBB->getParent();
16355   MachineRegisterInfo &MRI = MF->getRegInfo();
16356
16357   const BasicBlock *BB = MBB->getBasicBlock();
16358   MachineFunction::iterator I = MBB;
16359   ++I;
16360
16361   // Memory Reference
16362   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16363   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16364
16365   unsigned DstReg;
16366   unsigned MemOpndSlot = 0;
16367
16368   unsigned CurOp = 0;
16369
16370   DstReg = MI->getOperand(CurOp++).getReg();
16371   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16372   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16373   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16374   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16375
16376   MemOpndSlot = CurOp;
16377
16378   MVT PVT = getPointerTy();
16379   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16380          "Invalid Pointer Size!");
16381
16382   // For v = setjmp(buf), we generate
16383   //
16384   // thisMBB:
16385   //  buf[LabelOffset] = restoreMBB
16386   //  SjLjSetup restoreMBB
16387   //
16388   // mainMBB:
16389   //  v_main = 0
16390   //
16391   // sinkMBB:
16392   //  v = phi(main, restore)
16393   //
16394   // restoreMBB:
16395   //  v_restore = 1
16396
16397   MachineBasicBlock *thisMBB = MBB;
16398   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16399   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16400   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16401   MF->insert(I, mainMBB);
16402   MF->insert(I, sinkMBB);
16403   MF->push_back(restoreMBB);
16404
16405   MachineInstrBuilder MIB;
16406
16407   // Transfer the remainder of BB and its successor edges to sinkMBB.
16408   sinkMBB->splice(sinkMBB->begin(), MBB,
16409                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16410   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16411
16412   // thisMBB:
16413   unsigned PtrStoreOpc = 0;
16414   unsigned LabelReg = 0;
16415   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16416   Reloc::Model RM = getTargetMachine().getRelocationModel();
16417   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16418                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16419
16420   // Prepare IP either in reg or imm.
16421   if (!UseImmLabel) {
16422     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16423     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16424     LabelReg = MRI.createVirtualRegister(PtrRC);
16425     if (Subtarget->is64Bit()) {
16426       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16427               .addReg(X86::RIP)
16428               .addImm(0)
16429               .addReg(0)
16430               .addMBB(restoreMBB)
16431               .addReg(0);
16432     } else {
16433       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16434       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16435               .addReg(XII->getGlobalBaseReg(MF))
16436               .addImm(0)
16437               .addReg(0)
16438               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16439               .addReg(0);
16440     }
16441   } else
16442     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16443   // Store IP
16444   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16445   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16446     if (i == X86::AddrDisp)
16447       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16448     else
16449       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16450   }
16451   if (!UseImmLabel)
16452     MIB.addReg(LabelReg);
16453   else
16454     MIB.addMBB(restoreMBB);
16455   MIB.setMemRefs(MMOBegin, MMOEnd);
16456   // Setup
16457   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16458           .addMBB(restoreMBB);
16459
16460   const X86RegisterInfo *RegInfo =
16461     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16462   MIB.addRegMask(RegInfo->getNoPreservedMask());
16463   thisMBB->addSuccessor(mainMBB);
16464   thisMBB->addSuccessor(restoreMBB);
16465
16466   // mainMBB:
16467   //  EAX = 0
16468   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16469   mainMBB->addSuccessor(sinkMBB);
16470
16471   // sinkMBB:
16472   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16473           TII->get(X86::PHI), DstReg)
16474     .addReg(mainDstReg).addMBB(mainMBB)
16475     .addReg(restoreDstReg).addMBB(restoreMBB);
16476
16477   // restoreMBB:
16478   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16479   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16480   restoreMBB->addSuccessor(sinkMBB);
16481
16482   MI->eraseFromParent();
16483   return sinkMBB;
16484 }
16485
16486 MachineBasicBlock *
16487 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16488                                      MachineBasicBlock *MBB) const {
16489   DebugLoc DL = MI->getDebugLoc();
16490   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16491
16492   MachineFunction *MF = MBB->getParent();
16493   MachineRegisterInfo &MRI = MF->getRegInfo();
16494
16495   // Memory Reference
16496   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16497   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16498
16499   MVT PVT = getPointerTy();
16500   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16501          "Invalid Pointer Size!");
16502
16503   const TargetRegisterClass *RC =
16504     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16505   unsigned Tmp = MRI.createVirtualRegister(RC);
16506   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16507   const X86RegisterInfo *RegInfo =
16508     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16509   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16510   unsigned SP = RegInfo->getStackRegister();
16511
16512   MachineInstrBuilder MIB;
16513
16514   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16515   const int64_t SPOffset = 2 * PVT.getStoreSize();
16516
16517   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16518   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16519
16520   // Reload FP
16521   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16522   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16523     MIB.addOperand(MI->getOperand(i));
16524   MIB.setMemRefs(MMOBegin, MMOEnd);
16525   // Reload IP
16526   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16527   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16528     if (i == X86::AddrDisp)
16529       MIB.addDisp(MI->getOperand(i), LabelOffset);
16530     else
16531       MIB.addOperand(MI->getOperand(i));
16532   }
16533   MIB.setMemRefs(MMOBegin, MMOEnd);
16534   // Reload SP
16535   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16536   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16537     if (i == X86::AddrDisp)
16538       MIB.addDisp(MI->getOperand(i), SPOffset);
16539     else
16540       MIB.addOperand(MI->getOperand(i));
16541   }
16542   MIB.setMemRefs(MMOBegin, MMOEnd);
16543   // Jump
16544   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16545
16546   MI->eraseFromParent();
16547   return MBB;
16548 }
16549
16550 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16551 // accumulator loops. Writing back to the accumulator allows the coalescer
16552 // to remove extra copies in the loop.   
16553 MachineBasicBlock *
16554 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16555                                  MachineBasicBlock *MBB) const {
16556   MachineOperand &AddendOp = MI->getOperand(3);
16557
16558   // Bail out early if the addend isn't a register - we can't switch these.
16559   if (!AddendOp.isReg())
16560     return MBB;
16561
16562   MachineFunction &MF = *MBB->getParent();
16563   MachineRegisterInfo &MRI = MF.getRegInfo();
16564
16565   // Check whether the addend is defined by a PHI:
16566   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16567   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16568   if (!AddendDef.isPHI())
16569     return MBB;
16570
16571   // Look for the following pattern:
16572   // loop:
16573   //   %addend = phi [%entry, 0], [%loop, %result]
16574   //   ...
16575   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16576
16577   // Replace with:
16578   //   loop:
16579   //   %addend = phi [%entry, 0], [%loop, %result]
16580   //   ...
16581   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16582
16583   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16584     assert(AddendDef.getOperand(i).isReg());
16585     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16586     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16587     if (&PHISrcInst == MI) {
16588       // Found a matching instruction.
16589       unsigned NewFMAOpc = 0;
16590       switch (MI->getOpcode()) {
16591         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16592         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16593         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16594         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16595         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16596         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16597         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16598         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16599         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16600         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16601         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16602         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16603         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16604         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16605         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16606         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16607         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16608         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16609         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16610         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16611         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16612         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16613         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16614         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16615         default: llvm_unreachable("Unrecognized FMA variant.");
16616       }
16617
16618       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16619       MachineInstrBuilder MIB =
16620         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16621         .addOperand(MI->getOperand(0))
16622         .addOperand(MI->getOperand(3))
16623         .addOperand(MI->getOperand(2))
16624         .addOperand(MI->getOperand(1));
16625       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16626       MI->eraseFromParent();
16627     }
16628   }
16629
16630   return MBB;
16631 }
16632
16633 MachineBasicBlock *
16634 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16635                                                MachineBasicBlock *BB) const {
16636   switch (MI->getOpcode()) {
16637   default: llvm_unreachable("Unexpected instr type to insert");
16638   case X86::TAILJMPd64:
16639   case X86::TAILJMPr64:
16640   case X86::TAILJMPm64:
16641     llvm_unreachable("TAILJMP64 would not be touched here.");
16642   case X86::TCRETURNdi64:
16643   case X86::TCRETURNri64:
16644   case X86::TCRETURNmi64:
16645     return BB;
16646   case X86::WIN_ALLOCA:
16647     return EmitLoweredWinAlloca(MI, BB);
16648   case X86::SEG_ALLOCA_32:
16649     return EmitLoweredSegAlloca(MI, BB, false);
16650   case X86::SEG_ALLOCA_64:
16651     return EmitLoweredSegAlloca(MI, BB, true);
16652   case X86::TLSCall_32:
16653   case X86::TLSCall_64:
16654     return EmitLoweredTLSCall(MI, BB);
16655   case X86::CMOV_GR8:
16656   case X86::CMOV_FR32:
16657   case X86::CMOV_FR64:
16658   case X86::CMOV_V4F32:
16659   case X86::CMOV_V2F64:
16660   case X86::CMOV_V2I64:
16661   case X86::CMOV_V8F32:
16662   case X86::CMOV_V4F64:
16663   case X86::CMOV_V4I64:
16664   case X86::CMOV_V16F32:
16665   case X86::CMOV_V8F64:
16666   case X86::CMOV_V8I64:
16667   case X86::CMOV_GR16:
16668   case X86::CMOV_GR32:
16669   case X86::CMOV_RFP32:
16670   case X86::CMOV_RFP64:
16671   case X86::CMOV_RFP80:
16672     return EmitLoweredSelect(MI, BB);
16673
16674   case X86::FP32_TO_INT16_IN_MEM:
16675   case X86::FP32_TO_INT32_IN_MEM:
16676   case X86::FP32_TO_INT64_IN_MEM:
16677   case X86::FP64_TO_INT16_IN_MEM:
16678   case X86::FP64_TO_INT32_IN_MEM:
16679   case X86::FP64_TO_INT64_IN_MEM:
16680   case X86::FP80_TO_INT16_IN_MEM:
16681   case X86::FP80_TO_INT32_IN_MEM:
16682   case X86::FP80_TO_INT64_IN_MEM: {
16683     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16684     DebugLoc DL = MI->getDebugLoc();
16685
16686     // Change the floating point control register to use "round towards zero"
16687     // mode when truncating to an integer value.
16688     MachineFunction *F = BB->getParent();
16689     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16690     addFrameReference(BuildMI(*BB, MI, DL,
16691                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16692
16693     // Load the old value of the high byte of the control word...
16694     unsigned OldCW =
16695       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16696     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16697                       CWFrameIdx);
16698
16699     // Set the high part to be round to zero...
16700     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16701       .addImm(0xC7F);
16702
16703     // Reload the modified control word now...
16704     addFrameReference(BuildMI(*BB, MI, DL,
16705                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16706
16707     // Restore the memory image of control word to original value
16708     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16709       .addReg(OldCW);
16710
16711     // Get the X86 opcode to use.
16712     unsigned Opc;
16713     switch (MI->getOpcode()) {
16714     default: llvm_unreachable("illegal opcode!");
16715     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16716     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16717     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16718     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16719     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16720     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16721     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16722     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16723     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16724     }
16725
16726     X86AddressMode AM;
16727     MachineOperand &Op = MI->getOperand(0);
16728     if (Op.isReg()) {
16729       AM.BaseType = X86AddressMode::RegBase;
16730       AM.Base.Reg = Op.getReg();
16731     } else {
16732       AM.BaseType = X86AddressMode::FrameIndexBase;
16733       AM.Base.FrameIndex = Op.getIndex();
16734     }
16735     Op = MI->getOperand(1);
16736     if (Op.isImm())
16737       AM.Scale = Op.getImm();
16738     Op = MI->getOperand(2);
16739     if (Op.isImm())
16740       AM.IndexReg = Op.getImm();
16741     Op = MI->getOperand(3);
16742     if (Op.isGlobal()) {
16743       AM.GV = Op.getGlobal();
16744     } else {
16745       AM.Disp = Op.getImm();
16746     }
16747     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16748                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16749
16750     // Reload the original control word now.
16751     addFrameReference(BuildMI(*BB, MI, DL,
16752                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16753
16754     MI->eraseFromParent();   // The pseudo instruction is gone now.
16755     return BB;
16756   }
16757     // String/text processing lowering.
16758   case X86::PCMPISTRM128REG:
16759   case X86::VPCMPISTRM128REG:
16760   case X86::PCMPISTRM128MEM:
16761   case X86::VPCMPISTRM128MEM:
16762   case X86::PCMPESTRM128REG:
16763   case X86::VPCMPESTRM128REG:
16764   case X86::PCMPESTRM128MEM:
16765   case X86::VPCMPESTRM128MEM:
16766     assert(Subtarget->hasSSE42() &&
16767            "Target must have SSE4.2 or AVX features enabled");
16768     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16769
16770   // String/text processing lowering.
16771   case X86::PCMPISTRIREG:
16772   case X86::VPCMPISTRIREG:
16773   case X86::PCMPISTRIMEM:
16774   case X86::VPCMPISTRIMEM:
16775   case X86::PCMPESTRIREG:
16776   case X86::VPCMPESTRIREG:
16777   case X86::PCMPESTRIMEM:
16778   case X86::VPCMPESTRIMEM:
16779     assert(Subtarget->hasSSE42() &&
16780            "Target must have SSE4.2 or AVX features enabled");
16781     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16782
16783   // Thread synchronization.
16784   case X86::MONITOR:
16785     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16786
16787   // xbegin
16788   case X86::XBEGIN:
16789     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16790
16791   // Atomic Lowering.
16792   case X86::ATOMAND8:
16793   case X86::ATOMAND16:
16794   case X86::ATOMAND32:
16795   case X86::ATOMAND64:
16796     // Fall through
16797   case X86::ATOMOR8:
16798   case X86::ATOMOR16:
16799   case X86::ATOMOR32:
16800   case X86::ATOMOR64:
16801     // Fall through
16802   case X86::ATOMXOR16:
16803   case X86::ATOMXOR8:
16804   case X86::ATOMXOR32:
16805   case X86::ATOMXOR64:
16806     // Fall through
16807   case X86::ATOMNAND8:
16808   case X86::ATOMNAND16:
16809   case X86::ATOMNAND32:
16810   case X86::ATOMNAND64:
16811     // Fall through
16812   case X86::ATOMMAX8:
16813   case X86::ATOMMAX16:
16814   case X86::ATOMMAX32:
16815   case X86::ATOMMAX64:
16816     // Fall through
16817   case X86::ATOMMIN8:
16818   case X86::ATOMMIN16:
16819   case X86::ATOMMIN32:
16820   case X86::ATOMMIN64:
16821     // Fall through
16822   case X86::ATOMUMAX8:
16823   case X86::ATOMUMAX16:
16824   case X86::ATOMUMAX32:
16825   case X86::ATOMUMAX64:
16826     // Fall through
16827   case X86::ATOMUMIN8:
16828   case X86::ATOMUMIN16:
16829   case X86::ATOMUMIN32:
16830   case X86::ATOMUMIN64:
16831     return EmitAtomicLoadArith(MI, BB);
16832
16833   // This group does 64-bit operations on a 32-bit host.
16834   case X86::ATOMAND6432:
16835   case X86::ATOMOR6432:
16836   case X86::ATOMXOR6432:
16837   case X86::ATOMNAND6432:
16838   case X86::ATOMADD6432:
16839   case X86::ATOMSUB6432:
16840   case X86::ATOMMAX6432:
16841   case X86::ATOMMIN6432:
16842   case X86::ATOMUMAX6432:
16843   case X86::ATOMUMIN6432:
16844   case X86::ATOMSWAP6432:
16845     return EmitAtomicLoadArith6432(MI, BB);
16846
16847   case X86::VASTART_SAVE_XMM_REGS:
16848     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16849
16850   case X86::VAARG_64:
16851     return EmitVAARG64WithCustomInserter(MI, BB);
16852
16853   case X86::EH_SjLj_SetJmp32:
16854   case X86::EH_SjLj_SetJmp64:
16855     return emitEHSjLjSetJmp(MI, BB);
16856
16857   case X86::EH_SjLj_LongJmp32:
16858   case X86::EH_SjLj_LongJmp64:
16859     return emitEHSjLjLongJmp(MI, BB);
16860
16861   case TargetOpcode::STACKMAP:
16862   case TargetOpcode::PATCHPOINT:
16863     return emitPatchPoint(MI, BB);
16864
16865   case X86::VFMADDPDr213r:
16866   case X86::VFMADDPSr213r:
16867   case X86::VFMADDSDr213r:
16868   case X86::VFMADDSSr213r:
16869   case X86::VFMSUBPDr213r:
16870   case X86::VFMSUBPSr213r:
16871   case X86::VFMSUBSDr213r:
16872   case X86::VFMSUBSSr213r:
16873   case X86::VFNMADDPDr213r:
16874   case X86::VFNMADDPSr213r:
16875   case X86::VFNMADDSDr213r:
16876   case X86::VFNMADDSSr213r:
16877   case X86::VFNMSUBPDr213r:
16878   case X86::VFNMSUBPSr213r:
16879   case X86::VFNMSUBSDr213r:
16880   case X86::VFNMSUBSSr213r:
16881   case X86::VFMADDPDr213rY:
16882   case X86::VFMADDPSr213rY:
16883   case X86::VFMSUBPDr213rY:
16884   case X86::VFMSUBPSr213rY:
16885   case X86::VFNMADDPDr213rY:
16886   case X86::VFNMADDPSr213rY:
16887   case X86::VFNMSUBPDr213rY:
16888   case X86::VFNMSUBPSr213rY:
16889     return emitFMA3Instr(MI, BB);
16890   }
16891 }
16892
16893 //===----------------------------------------------------------------------===//
16894 //                           X86 Optimization Hooks
16895 //===----------------------------------------------------------------------===//
16896
16897 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16898                                                        APInt &KnownZero,
16899                                                        APInt &KnownOne,
16900                                                        const SelectionDAG &DAG,
16901                                                        unsigned Depth) const {
16902   unsigned BitWidth = KnownZero.getBitWidth();
16903   unsigned Opc = Op.getOpcode();
16904   assert((Opc >= ISD::BUILTIN_OP_END ||
16905           Opc == ISD::INTRINSIC_WO_CHAIN ||
16906           Opc == ISD::INTRINSIC_W_CHAIN ||
16907           Opc == ISD::INTRINSIC_VOID) &&
16908          "Should use MaskedValueIsZero if you don't know whether Op"
16909          " is a target node!");
16910
16911   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16912   switch (Opc) {
16913   default: break;
16914   case X86ISD::ADD:
16915   case X86ISD::SUB:
16916   case X86ISD::ADC:
16917   case X86ISD::SBB:
16918   case X86ISD::SMUL:
16919   case X86ISD::UMUL:
16920   case X86ISD::INC:
16921   case X86ISD::DEC:
16922   case X86ISD::OR:
16923   case X86ISD::XOR:
16924   case X86ISD::AND:
16925     // These nodes' second result is a boolean.
16926     if (Op.getResNo() == 0)
16927       break;
16928     // Fallthrough
16929   case X86ISD::SETCC:
16930     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16931     break;
16932   case ISD::INTRINSIC_WO_CHAIN: {
16933     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16934     unsigned NumLoBits = 0;
16935     switch (IntId) {
16936     default: break;
16937     case Intrinsic::x86_sse_movmsk_ps:
16938     case Intrinsic::x86_avx_movmsk_ps_256:
16939     case Intrinsic::x86_sse2_movmsk_pd:
16940     case Intrinsic::x86_avx_movmsk_pd_256:
16941     case Intrinsic::x86_mmx_pmovmskb:
16942     case Intrinsic::x86_sse2_pmovmskb_128:
16943     case Intrinsic::x86_avx2_pmovmskb: {
16944       // High bits of movmskp{s|d}, pmovmskb are known zero.
16945       switch (IntId) {
16946         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16947         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16948         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16949         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16950         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16951         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16952         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16953         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16954       }
16955       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16956       break;
16957     }
16958     }
16959     break;
16960   }
16961   }
16962 }
16963
16964 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16965   SDValue Op,
16966   const SelectionDAG &,
16967   unsigned Depth) const {
16968   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16969   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16970     return Op.getValueType().getScalarType().getSizeInBits();
16971
16972   // Fallback case.
16973   return 1;
16974 }
16975
16976 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16977 /// node is a GlobalAddress + offset.
16978 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16979                                        const GlobalValue* &GA,
16980                                        int64_t &Offset) const {
16981   if (N->getOpcode() == X86ISD::Wrapper) {
16982     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16983       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16984       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16985       return true;
16986     }
16987   }
16988   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16989 }
16990
16991 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16992 /// same as extracting the high 128-bit part of 256-bit vector and then
16993 /// inserting the result into the low part of a new 256-bit vector
16994 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16995   EVT VT = SVOp->getValueType(0);
16996   unsigned NumElems = VT.getVectorNumElements();
16997
16998   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16999   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17000     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17001         SVOp->getMaskElt(j) >= 0)
17002       return false;
17003
17004   return true;
17005 }
17006
17007 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17008 /// same as extracting the low 128-bit part of 256-bit vector and then
17009 /// inserting the result into the high part of a new 256-bit vector
17010 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17011   EVT VT = SVOp->getValueType(0);
17012   unsigned NumElems = VT.getVectorNumElements();
17013
17014   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17015   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17016     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17017         SVOp->getMaskElt(j) >= 0)
17018       return false;
17019
17020   return true;
17021 }
17022
17023 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17024 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17025                                         TargetLowering::DAGCombinerInfo &DCI,
17026                                         const X86Subtarget* Subtarget) {
17027   SDLoc dl(N);
17028   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17029   SDValue V1 = SVOp->getOperand(0);
17030   SDValue V2 = SVOp->getOperand(1);
17031   EVT VT = SVOp->getValueType(0);
17032   unsigned NumElems = VT.getVectorNumElements();
17033
17034   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17035       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17036     //
17037     //                   0,0,0,...
17038     //                      |
17039     //    V      UNDEF    BUILD_VECTOR    UNDEF
17040     //     \      /           \           /
17041     //  CONCAT_VECTOR         CONCAT_VECTOR
17042     //         \                  /
17043     //          \                /
17044     //          RESULT: V + zero extended
17045     //
17046     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17047         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17048         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17049       return SDValue();
17050
17051     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17052       return SDValue();
17053
17054     // To match the shuffle mask, the first half of the mask should
17055     // be exactly the first vector, and all the rest a splat with the
17056     // first element of the second one.
17057     for (unsigned i = 0; i != NumElems/2; ++i)
17058       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17059           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17060         return SDValue();
17061
17062     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17063     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17064       if (Ld->hasNUsesOfValue(1, 0)) {
17065         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17066         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17067         SDValue ResNode =
17068           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17069                                   array_lengthof(Ops),
17070                                   Ld->getMemoryVT(),
17071                                   Ld->getPointerInfo(),
17072                                   Ld->getAlignment(),
17073                                   false/*isVolatile*/, true/*ReadMem*/,
17074                                   false/*WriteMem*/);
17075
17076         // Make sure the newly-created LOAD is in the same position as Ld in
17077         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17078         // and update uses of Ld's output chain to use the TokenFactor.
17079         if (Ld->hasAnyUseOfValue(1)) {
17080           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17081                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17082           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17083           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17084                                  SDValue(ResNode.getNode(), 1));
17085         }
17086
17087         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17088       }
17089     }
17090
17091     // Emit a zeroed vector and insert the desired subvector on its
17092     // first half.
17093     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17094     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17095     return DCI.CombineTo(N, InsV);
17096   }
17097
17098   //===--------------------------------------------------------------------===//
17099   // Combine some shuffles into subvector extracts and inserts:
17100   //
17101
17102   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17103   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17104     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17105     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17106     return DCI.CombineTo(N, InsV);
17107   }
17108
17109   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17110   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17111     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17112     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17113     return DCI.CombineTo(N, InsV);
17114   }
17115
17116   return SDValue();
17117 }
17118
17119 /// PerformShuffleCombine - Performs several different shuffle combines.
17120 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17121                                      TargetLowering::DAGCombinerInfo &DCI,
17122                                      const X86Subtarget *Subtarget) {
17123   SDLoc dl(N);
17124   EVT VT = N->getValueType(0);
17125
17126   // Don't create instructions with illegal types after legalize types has run.
17127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17128   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17129     return SDValue();
17130
17131   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17132   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17133       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17134     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17135
17136   // Only handle 128 wide vector from here on.
17137   if (!VT.is128BitVector())
17138     return SDValue();
17139
17140   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17141   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17142   // consecutive, non-overlapping, and in the right order.
17143   SmallVector<SDValue, 16> Elts;
17144   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17145     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17146
17147   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17148 }
17149
17150 /// PerformTruncateCombine - Converts truncate operation to
17151 /// a sequence of vector shuffle operations.
17152 /// It is possible when we truncate 256-bit vector to 128-bit vector
17153 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17154                                       TargetLowering::DAGCombinerInfo &DCI,
17155                                       const X86Subtarget *Subtarget)  {
17156   return SDValue();
17157 }
17158
17159 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17160 /// specific shuffle of a load can be folded into a single element load.
17161 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17162 /// shuffles have been customed lowered so we need to handle those here.
17163 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17164                                          TargetLowering::DAGCombinerInfo &DCI) {
17165   if (DCI.isBeforeLegalizeOps())
17166     return SDValue();
17167
17168   SDValue InVec = N->getOperand(0);
17169   SDValue EltNo = N->getOperand(1);
17170
17171   if (!isa<ConstantSDNode>(EltNo))
17172     return SDValue();
17173
17174   EVT VT = InVec.getValueType();
17175
17176   bool HasShuffleIntoBitcast = false;
17177   if (InVec.getOpcode() == ISD::BITCAST) {
17178     // Don't duplicate a load with other uses.
17179     if (!InVec.hasOneUse())
17180       return SDValue();
17181     EVT BCVT = InVec.getOperand(0).getValueType();
17182     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17183       return SDValue();
17184     InVec = InVec.getOperand(0);
17185     HasShuffleIntoBitcast = true;
17186   }
17187
17188   if (!isTargetShuffle(InVec.getOpcode()))
17189     return SDValue();
17190
17191   // Don't duplicate a load with other uses.
17192   if (!InVec.hasOneUse())
17193     return SDValue();
17194
17195   SmallVector<int, 16> ShuffleMask;
17196   bool UnaryShuffle;
17197   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17198                             UnaryShuffle))
17199     return SDValue();
17200
17201   // Select the input vector, guarding against out of range extract vector.
17202   unsigned NumElems = VT.getVectorNumElements();
17203   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17204   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17205   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17206                                          : InVec.getOperand(1);
17207
17208   // If inputs to shuffle are the same for both ops, then allow 2 uses
17209   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17210
17211   if (LdNode.getOpcode() == ISD::BITCAST) {
17212     // Don't duplicate a load with other uses.
17213     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17214       return SDValue();
17215
17216     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17217     LdNode = LdNode.getOperand(0);
17218   }
17219
17220   if (!ISD::isNormalLoad(LdNode.getNode()))
17221     return SDValue();
17222
17223   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17224
17225   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17226     return SDValue();
17227
17228   if (HasShuffleIntoBitcast) {
17229     // If there's a bitcast before the shuffle, check if the load type and
17230     // alignment is valid.
17231     unsigned Align = LN0->getAlignment();
17232     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17233     unsigned NewAlign = TLI.getDataLayout()->
17234       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17235
17236     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17237       return SDValue();
17238   }
17239
17240   // All checks match so transform back to vector_shuffle so that DAG combiner
17241   // can finish the job
17242   SDLoc dl(N);
17243
17244   // Create shuffle node taking into account the case that its a unary shuffle
17245   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17246   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17247                                  InVec.getOperand(0), Shuffle,
17248                                  &ShuffleMask[0]);
17249   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17250   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17251                      EltNo);
17252 }
17253
17254 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17255 /// generation and convert it from being a bunch of shuffles and extracts
17256 /// to a simple store and scalar loads to extract the elements.
17257 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17258                                          TargetLowering::DAGCombinerInfo &DCI) {
17259   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17260   if (NewOp.getNode())
17261     return NewOp;
17262
17263   SDValue InputVector = N->getOperand(0);
17264
17265   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17266   // from mmx to v2i32 has a single usage.
17267   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17268       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17269       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17270     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17271                        N->getValueType(0),
17272                        InputVector.getNode()->getOperand(0));
17273
17274   // Only operate on vectors of 4 elements, where the alternative shuffling
17275   // gets to be more expensive.
17276   if (InputVector.getValueType() != MVT::v4i32)
17277     return SDValue();
17278
17279   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17280   // single use which is a sign-extend or zero-extend, and all elements are
17281   // used.
17282   SmallVector<SDNode *, 4> Uses;
17283   unsigned ExtractedElements = 0;
17284   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17285        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17286     if (UI.getUse().getResNo() != InputVector.getResNo())
17287       return SDValue();
17288
17289     SDNode *Extract = *UI;
17290     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17291       return SDValue();
17292
17293     if (Extract->getValueType(0) != MVT::i32)
17294       return SDValue();
17295     if (!Extract->hasOneUse())
17296       return SDValue();
17297     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17298         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17299       return SDValue();
17300     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17301       return SDValue();
17302
17303     // Record which element was extracted.
17304     ExtractedElements |=
17305       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17306
17307     Uses.push_back(Extract);
17308   }
17309
17310   // If not all the elements were used, this may not be worthwhile.
17311   if (ExtractedElements != 15)
17312     return SDValue();
17313
17314   // Ok, we've now decided to do the transformation.
17315   SDLoc dl(InputVector);
17316
17317   // Store the value to a temporary stack slot.
17318   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17319   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17320                             MachinePointerInfo(), false, false, 0);
17321
17322   // Replace each use (extract) with a load of the appropriate element.
17323   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17324        UE = Uses.end(); UI != UE; ++UI) {
17325     SDNode *Extract = *UI;
17326
17327     // cOMpute the element's address.
17328     SDValue Idx = Extract->getOperand(1);
17329     unsigned EltSize =
17330         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17331     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17332     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17333     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17334
17335     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17336                                      StackPtr, OffsetVal);
17337
17338     // Load the scalar.
17339     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17340                                      ScalarAddr, MachinePointerInfo(),
17341                                      false, false, false, 0);
17342
17343     // Replace the exact with the load.
17344     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17345   }
17346
17347   // The replacement was made in place; don't return anything.
17348   return SDValue();
17349 }
17350
17351 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17352 static std::pair<unsigned, bool>
17353 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17354                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17355   if (!VT.isVector())
17356     return std::make_pair(0, false);
17357
17358   bool NeedSplit = false;
17359   switch (VT.getSimpleVT().SimpleTy) {
17360   default: return std::make_pair(0, false);
17361   case MVT::v32i8:
17362   case MVT::v16i16:
17363   case MVT::v8i32:
17364     if (!Subtarget->hasAVX2())
17365       NeedSplit = true;
17366     if (!Subtarget->hasAVX())
17367       return std::make_pair(0, false);
17368     break;
17369   case MVT::v16i8:
17370   case MVT::v8i16:
17371   case MVT::v4i32:
17372     if (!Subtarget->hasSSE2())
17373       return std::make_pair(0, false);
17374   }
17375
17376   // SSE2 has only a small subset of the operations.
17377   bool hasUnsigned = Subtarget->hasSSE41() ||
17378                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17379   bool hasSigned = Subtarget->hasSSE41() ||
17380                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17381
17382   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17383
17384   unsigned Opc = 0;
17385   // Check for x CC y ? x : y.
17386   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17387       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17388     switch (CC) {
17389     default: break;
17390     case ISD::SETULT:
17391     case ISD::SETULE:
17392       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17393     case ISD::SETUGT:
17394     case ISD::SETUGE:
17395       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17396     case ISD::SETLT:
17397     case ISD::SETLE:
17398       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17399     case ISD::SETGT:
17400     case ISD::SETGE:
17401       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17402     }
17403   // Check for x CC y ? y : x -- a min/max with reversed arms.
17404   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17405              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17406     switch (CC) {
17407     default: break;
17408     case ISD::SETULT:
17409     case ISD::SETULE:
17410       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17411     case ISD::SETUGT:
17412     case ISD::SETUGE:
17413       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17414     case ISD::SETLT:
17415     case ISD::SETLE:
17416       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17417     case ISD::SETGT:
17418     case ISD::SETGE:
17419       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17420     }
17421   }
17422
17423   return std::make_pair(Opc, NeedSplit);
17424 }
17425
17426 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17427 /// nodes.
17428 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17429                                     TargetLowering::DAGCombinerInfo &DCI,
17430                                     const X86Subtarget *Subtarget) {
17431   SDLoc DL(N);
17432   SDValue Cond = N->getOperand(0);
17433   // Get the LHS/RHS of the select.
17434   SDValue LHS = N->getOperand(1);
17435   SDValue RHS = N->getOperand(2);
17436   EVT VT = LHS.getValueType();
17437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17438
17439   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17440   // instructions match the semantics of the common C idiom x<y?x:y but not
17441   // x<=y?x:y, because of how they handle negative zero (which can be
17442   // ignored in unsafe-math mode).
17443   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17444       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17445       (Subtarget->hasSSE2() ||
17446        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17447     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17448
17449     unsigned Opcode = 0;
17450     // Check for x CC y ? x : y.
17451     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17452         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17453       switch (CC) {
17454       default: break;
17455       case ISD::SETULT:
17456         // Converting this to a min would handle NaNs incorrectly, and swapping
17457         // the operands would cause it to handle comparisons between positive
17458         // and negative zero incorrectly.
17459         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17460           if (!DAG.getTarget().Options.UnsafeFPMath &&
17461               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17462             break;
17463           std::swap(LHS, RHS);
17464         }
17465         Opcode = X86ISD::FMIN;
17466         break;
17467       case ISD::SETOLE:
17468         // Converting this to a min would handle comparisons between positive
17469         // and negative zero incorrectly.
17470         if (!DAG.getTarget().Options.UnsafeFPMath &&
17471             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17472           break;
17473         Opcode = X86ISD::FMIN;
17474         break;
17475       case ISD::SETULE:
17476         // Converting this to a min would handle both negative zeros and NaNs
17477         // incorrectly, but we can swap the operands to fix both.
17478         std::swap(LHS, RHS);
17479       case ISD::SETOLT:
17480       case ISD::SETLT:
17481       case ISD::SETLE:
17482         Opcode = X86ISD::FMIN;
17483         break;
17484
17485       case ISD::SETOGE:
17486         // Converting this to a max would handle comparisons between positive
17487         // and negative zero incorrectly.
17488         if (!DAG.getTarget().Options.UnsafeFPMath &&
17489             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17490           break;
17491         Opcode = X86ISD::FMAX;
17492         break;
17493       case ISD::SETUGT:
17494         // Converting this to a max would handle NaNs incorrectly, and swapping
17495         // the operands would cause it to handle comparisons between positive
17496         // and negative zero incorrectly.
17497         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17498           if (!DAG.getTarget().Options.UnsafeFPMath &&
17499               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17500             break;
17501           std::swap(LHS, RHS);
17502         }
17503         Opcode = X86ISD::FMAX;
17504         break;
17505       case ISD::SETUGE:
17506         // Converting this to a max would handle both negative zeros and NaNs
17507         // incorrectly, but we can swap the operands to fix both.
17508         std::swap(LHS, RHS);
17509       case ISD::SETOGT:
17510       case ISD::SETGT:
17511       case ISD::SETGE:
17512         Opcode = X86ISD::FMAX;
17513         break;
17514       }
17515     // Check for x CC y ? y : x -- a min/max with reversed arms.
17516     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17517                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17518       switch (CC) {
17519       default: break;
17520       case ISD::SETOGE:
17521         // Converting this to a min would handle comparisons between positive
17522         // and negative zero incorrectly, and swapping the operands would
17523         // cause it to handle NaNs incorrectly.
17524         if (!DAG.getTarget().Options.UnsafeFPMath &&
17525             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17526           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17527             break;
17528           std::swap(LHS, RHS);
17529         }
17530         Opcode = X86ISD::FMIN;
17531         break;
17532       case ISD::SETUGT:
17533         // Converting this to a min would handle NaNs incorrectly.
17534         if (!DAG.getTarget().Options.UnsafeFPMath &&
17535             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17536           break;
17537         Opcode = X86ISD::FMIN;
17538         break;
17539       case ISD::SETUGE:
17540         // Converting this to a min would handle both negative zeros and NaNs
17541         // incorrectly, but we can swap the operands to fix both.
17542         std::swap(LHS, RHS);
17543       case ISD::SETOGT:
17544       case ISD::SETGT:
17545       case ISD::SETGE:
17546         Opcode = X86ISD::FMIN;
17547         break;
17548
17549       case ISD::SETULT:
17550         // Converting this to a max would handle NaNs incorrectly.
17551         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17552           break;
17553         Opcode = X86ISD::FMAX;
17554         break;
17555       case ISD::SETOLE:
17556         // Converting this to a max would handle comparisons between positive
17557         // and negative zero incorrectly, and swapping the operands would
17558         // cause it to handle NaNs incorrectly.
17559         if (!DAG.getTarget().Options.UnsafeFPMath &&
17560             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17561           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17562             break;
17563           std::swap(LHS, RHS);
17564         }
17565         Opcode = X86ISD::FMAX;
17566         break;
17567       case ISD::SETULE:
17568         // Converting this to a max would handle both negative zeros and NaNs
17569         // incorrectly, but we can swap the operands to fix both.
17570         std::swap(LHS, RHS);
17571       case ISD::SETOLT:
17572       case ISD::SETLT:
17573       case ISD::SETLE:
17574         Opcode = X86ISD::FMAX;
17575         break;
17576       }
17577     }
17578
17579     if (Opcode)
17580       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17581   }
17582
17583   EVT CondVT = Cond.getValueType();
17584   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17585       CondVT.getVectorElementType() == MVT::i1) {
17586     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17587     // lowering on AVX-512. In this case we convert it to
17588     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17589     // The same situation for all 128 and 256-bit vectors of i8 and i16
17590     EVT OpVT = LHS.getValueType();
17591     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17592         (OpVT.getVectorElementType() == MVT::i8 ||
17593          OpVT.getVectorElementType() == MVT::i16)) {
17594       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17595       DCI.AddToWorklist(Cond.getNode());
17596       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17597     }
17598   }
17599   // If this is a select between two integer constants, try to do some
17600   // optimizations.
17601   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17602     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17603       // Don't do this for crazy integer types.
17604       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17605         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17606         // so that TrueC (the true value) is larger than FalseC.
17607         bool NeedsCondInvert = false;
17608
17609         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17610             // Efficiently invertible.
17611             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17612              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17613               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17614           NeedsCondInvert = true;
17615           std::swap(TrueC, FalseC);
17616         }
17617
17618         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17619         if (FalseC->getAPIntValue() == 0 &&
17620             TrueC->getAPIntValue().isPowerOf2()) {
17621           if (NeedsCondInvert) // Invert the condition if needed.
17622             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17623                                DAG.getConstant(1, Cond.getValueType()));
17624
17625           // Zero extend the condition if needed.
17626           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17627
17628           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17629           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17630                              DAG.getConstant(ShAmt, MVT::i8));
17631         }
17632
17633         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17634         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17635           if (NeedsCondInvert) // Invert the condition if needed.
17636             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17637                                DAG.getConstant(1, Cond.getValueType()));
17638
17639           // Zero extend the condition if needed.
17640           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17641                              FalseC->getValueType(0), Cond);
17642           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17643                              SDValue(FalseC, 0));
17644         }
17645
17646         // Optimize cases that will turn into an LEA instruction.  This requires
17647         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17648         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17649           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17650           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17651
17652           bool isFastMultiplier = false;
17653           if (Diff < 10) {
17654             switch ((unsigned char)Diff) {
17655               default: break;
17656               case 1:  // result = add base, cond
17657               case 2:  // result = lea base(    , cond*2)
17658               case 3:  // result = lea base(cond, cond*2)
17659               case 4:  // result = lea base(    , cond*4)
17660               case 5:  // result = lea base(cond, cond*4)
17661               case 8:  // result = lea base(    , cond*8)
17662               case 9:  // result = lea base(cond, cond*8)
17663                 isFastMultiplier = true;
17664                 break;
17665             }
17666           }
17667
17668           if (isFastMultiplier) {
17669             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17670             if (NeedsCondInvert) // Invert the condition if needed.
17671               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17672                                  DAG.getConstant(1, Cond.getValueType()));
17673
17674             // Zero extend the condition if needed.
17675             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17676                                Cond);
17677             // Scale the condition by the difference.
17678             if (Diff != 1)
17679               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17680                                  DAG.getConstant(Diff, Cond.getValueType()));
17681
17682             // Add the base if non-zero.
17683             if (FalseC->getAPIntValue() != 0)
17684               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17685                                  SDValue(FalseC, 0));
17686             return Cond;
17687           }
17688         }
17689       }
17690   }
17691
17692   // Canonicalize max and min:
17693   // (x > y) ? x : y -> (x >= y) ? x : y
17694   // (x < y) ? x : y -> (x <= y) ? x : y
17695   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17696   // the need for an extra compare
17697   // against zero. e.g.
17698   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17699   // subl   %esi, %edi
17700   // testl  %edi, %edi
17701   // movl   $0, %eax
17702   // cmovgl %edi, %eax
17703   // =>
17704   // xorl   %eax, %eax
17705   // subl   %esi, $edi
17706   // cmovsl %eax, %edi
17707   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17708       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17709       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17710     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17711     switch (CC) {
17712     default: break;
17713     case ISD::SETLT:
17714     case ISD::SETGT: {
17715       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17716       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17717                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17718       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17719     }
17720     }
17721   }
17722
17723   // Early exit check
17724   if (!TLI.isTypeLegal(VT))
17725     return SDValue();
17726
17727   // Match VSELECTs into subs with unsigned saturation.
17728   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17729       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17730       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17731        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17732     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17733
17734     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17735     // left side invert the predicate to simplify logic below.
17736     SDValue Other;
17737     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17738       Other = RHS;
17739       CC = ISD::getSetCCInverse(CC, true);
17740     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17741       Other = LHS;
17742     }
17743
17744     if (Other.getNode() && Other->getNumOperands() == 2 &&
17745         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17746       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17747       SDValue CondRHS = Cond->getOperand(1);
17748
17749       // Look for a general sub with unsigned saturation first.
17750       // x >= y ? x-y : 0 --> subus x, y
17751       // x >  y ? x-y : 0 --> subus x, y
17752       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17753           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17754         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17755
17756       // If the RHS is a constant we have to reverse the const canonicalization.
17757       // x > C-1 ? x+-C : 0 --> subus x, C
17758       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17759           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17760         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17761         if (CondRHS.getConstantOperandVal(0) == -A-1)
17762           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17763                              DAG.getConstant(-A, VT));
17764       }
17765
17766       // Another special case: If C was a sign bit, the sub has been
17767       // canonicalized into a xor.
17768       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17769       //        it's safe to decanonicalize the xor?
17770       // x s< 0 ? x^C : 0 --> subus x, C
17771       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17772           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17773           isSplatVector(OpRHS.getNode())) {
17774         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17775         if (A.isSignBit())
17776           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17777       }
17778     }
17779   }
17780
17781   // Try to match a min/max vector operation.
17782   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17783     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17784     unsigned Opc = ret.first;
17785     bool NeedSplit = ret.second;
17786
17787     if (Opc && NeedSplit) {
17788       unsigned NumElems = VT.getVectorNumElements();
17789       // Extract the LHS vectors
17790       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17791       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17792
17793       // Extract the RHS vectors
17794       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17795       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17796
17797       // Create min/max for each subvector
17798       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17799       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17800
17801       // Merge the result
17802       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17803     } else if (Opc)
17804       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17805   }
17806
17807   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17808   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17809       // Check if SETCC has already been promoted
17810       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17811       // Check that condition value type matches vselect operand type
17812       CondVT == VT) { 
17813
17814     assert(Cond.getValueType().isVector() &&
17815            "vector select expects a vector selector!");
17816
17817     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17818     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17819
17820     if (!TValIsAllOnes && !FValIsAllZeros) {
17821       // Try invert the condition if true value is not all 1s and false value
17822       // is not all 0s.
17823       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17824       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17825
17826       if (TValIsAllZeros || FValIsAllOnes) {
17827         SDValue CC = Cond.getOperand(2);
17828         ISD::CondCode NewCC =
17829           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17830                                Cond.getOperand(0).getValueType().isInteger());
17831         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17832         std::swap(LHS, RHS);
17833         TValIsAllOnes = FValIsAllOnes;
17834         FValIsAllZeros = TValIsAllZeros;
17835       }
17836     }
17837
17838     if (TValIsAllOnes || FValIsAllZeros) {
17839       SDValue Ret;
17840
17841       if (TValIsAllOnes && FValIsAllZeros)
17842         Ret = Cond;
17843       else if (TValIsAllOnes)
17844         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17845                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17846       else if (FValIsAllZeros)
17847         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17848                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17849
17850       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17851     }
17852   }
17853
17854   // Try to fold this VSELECT into a MOVSS/MOVSD
17855   if (N->getOpcode() == ISD::VSELECT &&
17856       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17857     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17858         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17859       bool CanFold = false;
17860       unsigned NumElems = Cond.getNumOperands();
17861       SDValue A = LHS;
17862       SDValue B = RHS;
17863       
17864       if (isZero(Cond.getOperand(0))) {
17865         CanFold = true;
17866
17867         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17868         // fold (vselect <0,-1> -> (movsd A, B)
17869         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17870           CanFold = isAllOnes(Cond.getOperand(i));
17871       } else if (isAllOnes(Cond.getOperand(0))) {
17872         CanFold = true;
17873         std::swap(A, B);
17874
17875         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17876         // fold (vselect <-1,0> -> (movsd B, A)
17877         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17878           CanFold = isZero(Cond.getOperand(i));
17879       }
17880
17881       if (CanFold) {
17882         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17883           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17884         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17885       }
17886
17887       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17888         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17889         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17890         //                             (v2i64 (bitcast B)))))
17891         //
17892         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17893         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17894         //                             (v2f64 (bitcast B)))))
17895         //
17896         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17897         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17898         //                             (v2i64 (bitcast A)))))
17899         //
17900         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17901         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17902         //                             (v2f64 (bitcast A)))))
17903
17904         CanFold = (isZero(Cond.getOperand(0)) &&
17905                    isZero(Cond.getOperand(1)) &&
17906                    isAllOnes(Cond.getOperand(2)) &&
17907                    isAllOnes(Cond.getOperand(3)));
17908
17909         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17910             isAllOnes(Cond.getOperand(1)) &&
17911             isZero(Cond.getOperand(2)) &&
17912             isZero(Cond.getOperand(3))) {
17913           CanFold = true;
17914           std::swap(LHS, RHS);
17915         }
17916
17917         if (CanFold) {
17918           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17919           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17920           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17921           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17922                                                 NewB, DAG);
17923           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17924         }
17925       }
17926     }
17927   }
17928
17929   // If we know that this node is legal then we know that it is going to be
17930   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17931   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17932   // to simplify previous instructions.
17933   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17934       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17935     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17936
17937     // Don't optimize vector selects that map to mask-registers.
17938     if (BitWidth == 1)
17939       return SDValue();
17940
17941     // Check all uses of that condition operand to check whether it will be
17942     // consumed by non-BLEND instructions, which may depend on all bits are set
17943     // properly.
17944     for (SDNode::use_iterator I = Cond->use_begin(),
17945                               E = Cond->use_end(); I != E; ++I)
17946       if (I->getOpcode() != ISD::VSELECT)
17947         // TODO: Add other opcodes eventually lowered into BLEND.
17948         return SDValue();
17949
17950     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17951     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17952
17953     APInt KnownZero, KnownOne;
17954     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17955                                           DCI.isBeforeLegalizeOps());
17956     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17957         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17958       DCI.CommitTargetLoweringOpt(TLO);
17959   }
17960
17961   return SDValue();
17962 }
17963
17964 // Check whether a boolean test is testing a boolean value generated by
17965 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17966 // code.
17967 //
17968 // Simplify the following patterns:
17969 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17970 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17971 // to (Op EFLAGS Cond)
17972 //
17973 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17974 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17975 // to (Op EFLAGS !Cond)
17976 //
17977 // where Op could be BRCOND or CMOV.
17978 //
17979 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17980   // Quit if not CMP and SUB with its value result used.
17981   if (Cmp.getOpcode() != X86ISD::CMP &&
17982       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17983       return SDValue();
17984
17985   // Quit if not used as a boolean value.
17986   if (CC != X86::COND_E && CC != X86::COND_NE)
17987     return SDValue();
17988
17989   // Check CMP operands. One of them should be 0 or 1 and the other should be
17990   // an SetCC or extended from it.
17991   SDValue Op1 = Cmp.getOperand(0);
17992   SDValue Op2 = Cmp.getOperand(1);
17993
17994   SDValue SetCC;
17995   const ConstantSDNode* C = nullptr;
17996   bool needOppositeCond = (CC == X86::COND_E);
17997   bool checkAgainstTrue = false; // Is it a comparison against 1?
17998
17999   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18000     SetCC = Op2;
18001   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18002     SetCC = Op1;
18003   else // Quit if all operands are not constants.
18004     return SDValue();
18005
18006   if (C->getZExtValue() == 1) {
18007     needOppositeCond = !needOppositeCond;
18008     checkAgainstTrue = true;
18009   } else if (C->getZExtValue() != 0)
18010     // Quit if the constant is neither 0 or 1.
18011     return SDValue();
18012
18013   bool truncatedToBoolWithAnd = false;
18014   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18015   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18016          SetCC.getOpcode() == ISD::TRUNCATE ||
18017          SetCC.getOpcode() == ISD::AND) {
18018     if (SetCC.getOpcode() == ISD::AND) {
18019       int OpIdx = -1;
18020       ConstantSDNode *CS;
18021       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18022           CS->getZExtValue() == 1)
18023         OpIdx = 1;
18024       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18025           CS->getZExtValue() == 1)
18026         OpIdx = 0;
18027       if (OpIdx == -1)
18028         break;
18029       SetCC = SetCC.getOperand(OpIdx);
18030       truncatedToBoolWithAnd = true;
18031     } else
18032       SetCC = SetCC.getOperand(0);
18033   }
18034
18035   switch (SetCC.getOpcode()) {
18036   case X86ISD::SETCC_CARRY:
18037     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18038     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18039     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18040     // truncated to i1 using 'and'.
18041     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18042       break;
18043     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18044            "Invalid use of SETCC_CARRY!");
18045     // FALL THROUGH
18046   case X86ISD::SETCC:
18047     // Set the condition code or opposite one if necessary.
18048     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18049     if (needOppositeCond)
18050       CC = X86::GetOppositeBranchCondition(CC);
18051     return SetCC.getOperand(1);
18052   case X86ISD::CMOV: {
18053     // Check whether false/true value has canonical one, i.e. 0 or 1.
18054     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18055     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18056     // Quit if true value is not a constant.
18057     if (!TVal)
18058       return SDValue();
18059     // Quit if false value is not a constant.
18060     if (!FVal) {
18061       SDValue Op = SetCC.getOperand(0);
18062       // Skip 'zext' or 'trunc' node.
18063       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18064           Op.getOpcode() == ISD::TRUNCATE)
18065         Op = Op.getOperand(0);
18066       // A special case for rdrand/rdseed, where 0 is set if false cond is
18067       // found.
18068       if ((Op.getOpcode() != X86ISD::RDRAND &&
18069            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18070         return SDValue();
18071     }
18072     // Quit if false value is not the constant 0 or 1.
18073     bool FValIsFalse = true;
18074     if (FVal && FVal->getZExtValue() != 0) {
18075       if (FVal->getZExtValue() != 1)
18076         return SDValue();
18077       // If FVal is 1, opposite cond is needed.
18078       needOppositeCond = !needOppositeCond;
18079       FValIsFalse = false;
18080     }
18081     // Quit if TVal is not the constant opposite of FVal.
18082     if (FValIsFalse && TVal->getZExtValue() != 1)
18083       return SDValue();
18084     if (!FValIsFalse && TVal->getZExtValue() != 0)
18085       return SDValue();
18086     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18087     if (needOppositeCond)
18088       CC = X86::GetOppositeBranchCondition(CC);
18089     return SetCC.getOperand(3);
18090   }
18091   }
18092
18093   return SDValue();
18094 }
18095
18096 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18097 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18098                                   TargetLowering::DAGCombinerInfo &DCI,
18099                                   const X86Subtarget *Subtarget) {
18100   SDLoc DL(N);
18101
18102   // If the flag operand isn't dead, don't touch this CMOV.
18103   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18104     return SDValue();
18105
18106   SDValue FalseOp = N->getOperand(0);
18107   SDValue TrueOp = N->getOperand(1);
18108   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18109   SDValue Cond = N->getOperand(3);
18110
18111   if (CC == X86::COND_E || CC == X86::COND_NE) {
18112     switch (Cond.getOpcode()) {
18113     default: break;
18114     case X86ISD::BSR:
18115     case X86ISD::BSF:
18116       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18117       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18118         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18119     }
18120   }
18121
18122   SDValue Flags;
18123
18124   Flags = checkBoolTestSetCCCombine(Cond, CC);
18125   if (Flags.getNode() &&
18126       // Extra check as FCMOV only supports a subset of X86 cond.
18127       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18128     SDValue Ops[] = { FalseOp, TrueOp,
18129                       DAG.getConstant(CC, MVT::i8), Flags };
18130     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18131                        Ops, array_lengthof(Ops));
18132   }
18133
18134   // If this is a select between two integer constants, try to do some
18135   // optimizations.  Note that the operands are ordered the opposite of SELECT
18136   // operands.
18137   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18138     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18139       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18140       // larger than FalseC (the false value).
18141       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18142         CC = X86::GetOppositeBranchCondition(CC);
18143         std::swap(TrueC, FalseC);
18144         std::swap(TrueOp, FalseOp);
18145       }
18146
18147       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18148       // This is efficient for any integer data type (including i8/i16) and
18149       // shift amount.
18150       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18151         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18152                            DAG.getConstant(CC, MVT::i8), Cond);
18153
18154         // Zero extend the condition if needed.
18155         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18156
18157         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18158         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18159                            DAG.getConstant(ShAmt, MVT::i8));
18160         if (N->getNumValues() == 2)  // Dead flag value?
18161           return DCI.CombineTo(N, Cond, SDValue());
18162         return Cond;
18163       }
18164
18165       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18166       // for any integer data type, including i8/i16.
18167       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18168         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18169                            DAG.getConstant(CC, MVT::i8), Cond);
18170
18171         // Zero extend the condition if needed.
18172         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18173                            FalseC->getValueType(0), Cond);
18174         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18175                            SDValue(FalseC, 0));
18176
18177         if (N->getNumValues() == 2)  // Dead flag value?
18178           return DCI.CombineTo(N, Cond, SDValue());
18179         return Cond;
18180       }
18181
18182       // Optimize cases that will turn into an LEA instruction.  This requires
18183       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18184       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18185         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18186         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18187
18188         bool isFastMultiplier = false;
18189         if (Diff < 10) {
18190           switch ((unsigned char)Diff) {
18191           default: break;
18192           case 1:  // result = add base, cond
18193           case 2:  // result = lea base(    , cond*2)
18194           case 3:  // result = lea base(cond, cond*2)
18195           case 4:  // result = lea base(    , cond*4)
18196           case 5:  // result = lea base(cond, cond*4)
18197           case 8:  // result = lea base(    , cond*8)
18198           case 9:  // result = lea base(cond, cond*8)
18199             isFastMultiplier = true;
18200             break;
18201           }
18202         }
18203
18204         if (isFastMultiplier) {
18205           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18206           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18207                              DAG.getConstant(CC, MVT::i8), Cond);
18208           // Zero extend the condition if needed.
18209           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18210                              Cond);
18211           // Scale the condition by the difference.
18212           if (Diff != 1)
18213             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18214                                DAG.getConstant(Diff, Cond.getValueType()));
18215
18216           // Add the base if non-zero.
18217           if (FalseC->getAPIntValue() != 0)
18218             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18219                                SDValue(FalseC, 0));
18220           if (N->getNumValues() == 2)  // Dead flag value?
18221             return DCI.CombineTo(N, Cond, SDValue());
18222           return Cond;
18223         }
18224       }
18225     }
18226   }
18227
18228   // Handle these cases:
18229   //   (select (x != c), e, c) -> select (x != c), e, x),
18230   //   (select (x == c), c, e) -> select (x == c), x, e)
18231   // where the c is an integer constant, and the "select" is the combination
18232   // of CMOV and CMP.
18233   //
18234   // The rationale for this change is that the conditional-move from a constant
18235   // needs two instructions, however, conditional-move from a register needs
18236   // only one instruction.
18237   //
18238   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18239   //  some instruction-combining opportunities. This opt needs to be
18240   //  postponed as late as possible.
18241   //
18242   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18243     // the DCI.xxxx conditions are provided to postpone the optimization as
18244     // late as possible.
18245
18246     ConstantSDNode *CmpAgainst = nullptr;
18247     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18248         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18249         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18250
18251       if (CC == X86::COND_NE &&
18252           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18253         CC = X86::GetOppositeBranchCondition(CC);
18254         std::swap(TrueOp, FalseOp);
18255       }
18256
18257       if (CC == X86::COND_E &&
18258           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18259         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18260                           DAG.getConstant(CC, MVT::i8), Cond };
18261         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18262                            array_lengthof(Ops));
18263       }
18264     }
18265   }
18266
18267   return SDValue();
18268 }
18269
18270 /// PerformMulCombine - Optimize a single multiply with constant into two
18271 /// in order to implement it with two cheaper instructions, e.g.
18272 /// LEA + SHL, LEA + LEA.
18273 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18274                                  TargetLowering::DAGCombinerInfo &DCI) {
18275   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18276     return SDValue();
18277
18278   EVT VT = N->getValueType(0);
18279   if (VT != MVT::i64)
18280     return SDValue();
18281
18282   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18283   if (!C)
18284     return SDValue();
18285   uint64_t MulAmt = C->getZExtValue();
18286   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18287     return SDValue();
18288
18289   uint64_t MulAmt1 = 0;
18290   uint64_t MulAmt2 = 0;
18291   if ((MulAmt % 9) == 0) {
18292     MulAmt1 = 9;
18293     MulAmt2 = MulAmt / 9;
18294   } else if ((MulAmt % 5) == 0) {
18295     MulAmt1 = 5;
18296     MulAmt2 = MulAmt / 5;
18297   } else if ((MulAmt % 3) == 0) {
18298     MulAmt1 = 3;
18299     MulAmt2 = MulAmt / 3;
18300   }
18301   if (MulAmt2 &&
18302       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18303     SDLoc DL(N);
18304
18305     if (isPowerOf2_64(MulAmt2) &&
18306         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18307       // If second multiplifer is pow2, issue it first. We want the multiply by
18308       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18309       // is an add.
18310       std::swap(MulAmt1, MulAmt2);
18311
18312     SDValue NewMul;
18313     if (isPowerOf2_64(MulAmt1))
18314       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18315                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18316     else
18317       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18318                            DAG.getConstant(MulAmt1, VT));
18319
18320     if (isPowerOf2_64(MulAmt2))
18321       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18322                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18323     else
18324       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18325                            DAG.getConstant(MulAmt2, VT));
18326
18327     // Do not add new nodes to DAG combiner worklist.
18328     DCI.CombineTo(N, NewMul, false);
18329   }
18330   return SDValue();
18331 }
18332
18333 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18334   SDValue N0 = N->getOperand(0);
18335   SDValue N1 = N->getOperand(1);
18336   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18337   EVT VT = N0.getValueType();
18338
18339   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18340   // since the result of setcc_c is all zero's or all ones.
18341   if (VT.isInteger() && !VT.isVector() &&
18342       N1C && N0.getOpcode() == ISD::AND &&
18343       N0.getOperand(1).getOpcode() == ISD::Constant) {
18344     SDValue N00 = N0.getOperand(0);
18345     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18346         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18347           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18348          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18349       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18350       APInt ShAmt = N1C->getAPIntValue();
18351       Mask = Mask.shl(ShAmt);
18352       if (Mask != 0)
18353         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18354                            N00, DAG.getConstant(Mask, VT));
18355     }
18356   }
18357
18358   // Hardware support for vector shifts is sparse which makes us scalarize the
18359   // vector operations in many cases. Also, on sandybridge ADD is faster than
18360   // shl.
18361   // (shl V, 1) -> add V,V
18362   if (isSplatVector(N1.getNode())) {
18363     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18364     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18365     // We shift all of the values by one. In many cases we do not have
18366     // hardware support for this operation. This is better expressed as an ADD
18367     // of two values.
18368     if (N1C && (1 == N1C->getZExtValue())) {
18369       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18370     }
18371   }
18372
18373   return SDValue();
18374 }
18375
18376 /// \brief Returns a vector of 0s if the node in input is a vector logical
18377 /// shift by a constant amount which is known to be bigger than or equal
18378 /// to the vector element size in bits.
18379 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18380                                       const X86Subtarget *Subtarget) {
18381   EVT VT = N->getValueType(0);
18382
18383   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18384       (!Subtarget->hasInt256() ||
18385        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18386     return SDValue();
18387
18388   SDValue Amt = N->getOperand(1);
18389   SDLoc DL(N);
18390   if (isSplatVector(Amt.getNode())) {
18391     SDValue SclrAmt = Amt->getOperand(0);
18392     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18393       APInt ShiftAmt = C->getAPIntValue();
18394       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18395
18396       // SSE2/AVX2 logical shifts always return a vector of 0s
18397       // if the shift amount is bigger than or equal to
18398       // the element size. The constant shift amount will be
18399       // encoded as a 8-bit immediate.
18400       if (ShiftAmt.trunc(8).uge(MaxAmount))
18401         return getZeroVector(VT, Subtarget, DAG, DL);
18402     }
18403   }
18404
18405   return SDValue();
18406 }
18407
18408 /// PerformShiftCombine - Combine shifts.
18409 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18410                                    TargetLowering::DAGCombinerInfo &DCI,
18411                                    const X86Subtarget *Subtarget) {
18412   if (N->getOpcode() == ISD::SHL) {
18413     SDValue V = PerformSHLCombine(N, DAG);
18414     if (V.getNode()) return V;
18415   }
18416
18417   if (N->getOpcode() != ISD::SRA) {
18418     // Try to fold this logical shift into a zero vector.
18419     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18420     if (V.getNode()) return V;
18421   }
18422
18423   return SDValue();
18424 }
18425
18426 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18427 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18428 // and friends.  Likewise for OR -> CMPNEQSS.
18429 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18430                             TargetLowering::DAGCombinerInfo &DCI,
18431                             const X86Subtarget *Subtarget) {
18432   unsigned opcode;
18433
18434   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18435   // we're requiring SSE2 for both.
18436   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18437     SDValue N0 = N->getOperand(0);
18438     SDValue N1 = N->getOperand(1);
18439     SDValue CMP0 = N0->getOperand(1);
18440     SDValue CMP1 = N1->getOperand(1);
18441     SDLoc DL(N);
18442
18443     // The SETCCs should both refer to the same CMP.
18444     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18445       return SDValue();
18446
18447     SDValue CMP00 = CMP0->getOperand(0);
18448     SDValue CMP01 = CMP0->getOperand(1);
18449     EVT     VT    = CMP00.getValueType();
18450
18451     if (VT == MVT::f32 || VT == MVT::f64) {
18452       bool ExpectingFlags = false;
18453       // Check for any users that want flags:
18454       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18455            !ExpectingFlags && UI != UE; ++UI)
18456         switch (UI->getOpcode()) {
18457         default:
18458         case ISD::BR_CC:
18459         case ISD::BRCOND:
18460         case ISD::SELECT:
18461           ExpectingFlags = true;
18462           break;
18463         case ISD::CopyToReg:
18464         case ISD::SIGN_EXTEND:
18465         case ISD::ZERO_EXTEND:
18466         case ISD::ANY_EXTEND:
18467           break;
18468         }
18469
18470       if (!ExpectingFlags) {
18471         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18472         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18473
18474         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18475           X86::CondCode tmp = cc0;
18476           cc0 = cc1;
18477           cc1 = tmp;
18478         }
18479
18480         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18481             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18482           // FIXME: need symbolic constants for these magic numbers.
18483           // See X86ATTInstPrinter.cpp:printSSECC().
18484           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18485           if (Subtarget->hasAVX512()) {
18486             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18487                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18488             if (N->getValueType(0) != MVT::i1)
18489               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18490                                  FSetCC);
18491             return FSetCC;
18492           }
18493           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18494                                               CMP00.getValueType(), CMP00, CMP01,
18495                                               DAG.getConstant(x86cc, MVT::i8));
18496
18497           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18498           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18499
18500           if (is64BitFP && !Subtarget->is64Bit()) {
18501             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18502             // 64-bit integer, since that's not a legal type. Since
18503             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18504             // bits, but can do this little dance to extract the lowest 32 bits
18505             // and work with those going forward.
18506             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18507                                            OnesOrZeroesF);
18508             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18509                                            Vector64);
18510             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18511                                         Vector32, DAG.getIntPtrConstant(0));
18512             IntVT = MVT::i32;
18513           }
18514
18515           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18516           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18517                                       DAG.getConstant(1, IntVT));
18518           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18519           return OneBitOfTruth;
18520         }
18521       }
18522     }
18523   }
18524   return SDValue();
18525 }
18526
18527 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18528 /// so it can be folded inside ANDNP.
18529 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18530   EVT VT = N->getValueType(0);
18531
18532   // Match direct AllOnes for 128 and 256-bit vectors
18533   if (ISD::isBuildVectorAllOnes(N))
18534     return true;
18535
18536   // Look through a bit convert.
18537   if (N->getOpcode() == ISD::BITCAST)
18538     N = N->getOperand(0).getNode();
18539
18540   // Sometimes the operand may come from a insert_subvector building a 256-bit
18541   // allones vector
18542   if (VT.is256BitVector() &&
18543       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18544     SDValue V1 = N->getOperand(0);
18545     SDValue V2 = N->getOperand(1);
18546
18547     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18548         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18549         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18550         ISD::isBuildVectorAllOnes(V2.getNode()))
18551       return true;
18552   }
18553
18554   return false;
18555 }
18556
18557 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18558 // register. In most cases we actually compare or select YMM-sized registers
18559 // and mixing the two types creates horrible code. This method optimizes
18560 // some of the transition sequences.
18561 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18562                                  TargetLowering::DAGCombinerInfo &DCI,
18563                                  const X86Subtarget *Subtarget) {
18564   EVT VT = N->getValueType(0);
18565   if (!VT.is256BitVector())
18566     return SDValue();
18567
18568   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18569           N->getOpcode() == ISD::ZERO_EXTEND ||
18570           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18571
18572   SDValue Narrow = N->getOperand(0);
18573   EVT NarrowVT = Narrow->getValueType(0);
18574   if (!NarrowVT.is128BitVector())
18575     return SDValue();
18576
18577   if (Narrow->getOpcode() != ISD::XOR &&
18578       Narrow->getOpcode() != ISD::AND &&
18579       Narrow->getOpcode() != ISD::OR)
18580     return SDValue();
18581
18582   SDValue N0  = Narrow->getOperand(0);
18583   SDValue N1  = Narrow->getOperand(1);
18584   SDLoc DL(Narrow);
18585
18586   // The Left side has to be a trunc.
18587   if (N0.getOpcode() != ISD::TRUNCATE)
18588     return SDValue();
18589
18590   // The type of the truncated inputs.
18591   EVT WideVT = N0->getOperand(0)->getValueType(0);
18592   if (WideVT != VT)
18593     return SDValue();
18594
18595   // The right side has to be a 'trunc' or a constant vector.
18596   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18597   bool RHSConst = (isSplatVector(N1.getNode()) &&
18598                    isa<ConstantSDNode>(N1->getOperand(0)));
18599   if (!RHSTrunc && !RHSConst)
18600     return SDValue();
18601
18602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18603
18604   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18605     return SDValue();
18606
18607   // Set N0 and N1 to hold the inputs to the new wide operation.
18608   N0 = N0->getOperand(0);
18609   if (RHSConst) {
18610     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18611                      N1->getOperand(0));
18612     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18613     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18614   } else if (RHSTrunc) {
18615     N1 = N1->getOperand(0);
18616   }
18617
18618   // Generate the wide operation.
18619   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18620   unsigned Opcode = N->getOpcode();
18621   switch (Opcode) {
18622   case ISD::ANY_EXTEND:
18623     return Op;
18624   case ISD::ZERO_EXTEND: {
18625     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18626     APInt Mask = APInt::getAllOnesValue(InBits);
18627     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18628     return DAG.getNode(ISD::AND, DL, VT,
18629                        Op, DAG.getConstant(Mask, VT));
18630   }
18631   case ISD::SIGN_EXTEND:
18632     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18633                        Op, DAG.getValueType(NarrowVT));
18634   default:
18635     llvm_unreachable("Unexpected opcode");
18636   }
18637 }
18638
18639 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18640                                  TargetLowering::DAGCombinerInfo &DCI,
18641                                  const X86Subtarget *Subtarget) {
18642   EVT VT = N->getValueType(0);
18643   if (DCI.isBeforeLegalizeOps())
18644     return SDValue();
18645
18646   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18647   if (R.getNode())
18648     return R;
18649
18650   // Create BEXTR instructions
18651   // BEXTR is ((X >> imm) & (2**size-1))
18652   if (VT == MVT::i32 || VT == MVT::i64) {
18653     SDValue N0 = N->getOperand(0);
18654     SDValue N1 = N->getOperand(1);
18655     SDLoc DL(N);
18656
18657     // Check for BEXTR.
18658     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18659         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18660       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18661       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18662       if (MaskNode && ShiftNode) {
18663         uint64_t Mask = MaskNode->getZExtValue();
18664         uint64_t Shift = ShiftNode->getZExtValue();
18665         if (isMask_64(Mask)) {
18666           uint64_t MaskSize = CountPopulation_64(Mask);
18667           if (Shift + MaskSize <= VT.getSizeInBits())
18668             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18669                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18670         }
18671       }
18672     } // BEXTR
18673
18674     return SDValue();
18675   }
18676
18677   // Want to form ANDNP nodes:
18678   // 1) In the hopes of then easily combining them with OR and AND nodes
18679   //    to form PBLEND/PSIGN.
18680   // 2) To match ANDN packed intrinsics
18681   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18682     return SDValue();
18683
18684   SDValue N0 = N->getOperand(0);
18685   SDValue N1 = N->getOperand(1);
18686   SDLoc DL(N);
18687
18688   // Check LHS for vnot
18689   if (N0.getOpcode() == ISD::XOR &&
18690       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18691       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18692     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18693
18694   // Check RHS for vnot
18695   if (N1.getOpcode() == ISD::XOR &&
18696       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18697       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18698     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18699
18700   return SDValue();
18701 }
18702
18703 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18704                                 TargetLowering::DAGCombinerInfo &DCI,
18705                                 const X86Subtarget *Subtarget) {
18706   if (DCI.isBeforeLegalizeOps())
18707     return SDValue();
18708
18709   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18710   if (R.getNode())
18711     return R;
18712
18713   SDValue N0 = N->getOperand(0);
18714   SDValue N1 = N->getOperand(1);
18715   EVT VT = N->getValueType(0);
18716
18717   // look for psign/blend
18718   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18719     if (!Subtarget->hasSSSE3() ||
18720         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18721       return SDValue();
18722
18723     // Canonicalize pandn to RHS
18724     if (N0.getOpcode() == X86ISD::ANDNP)
18725       std::swap(N0, N1);
18726     // or (and (m, y), (pandn m, x))
18727     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18728       SDValue Mask = N1.getOperand(0);
18729       SDValue X    = N1.getOperand(1);
18730       SDValue Y;
18731       if (N0.getOperand(0) == Mask)
18732         Y = N0.getOperand(1);
18733       if (N0.getOperand(1) == Mask)
18734         Y = N0.getOperand(0);
18735
18736       // Check to see if the mask appeared in both the AND and ANDNP and
18737       if (!Y.getNode())
18738         return SDValue();
18739
18740       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18741       // Look through mask bitcast.
18742       if (Mask.getOpcode() == ISD::BITCAST)
18743         Mask = Mask.getOperand(0);
18744       if (X.getOpcode() == ISD::BITCAST)
18745         X = X.getOperand(0);
18746       if (Y.getOpcode() == ISD::BITCAST)
18747         Y = Y.getOperand(0);
18748
18749       EVT MaskVT = Mask.getValueType();
18750
18751       // Validate that the Mask operand is a vector sra node.
18752       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18753       // there is no psrai.b
18754       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18755       unsigned SraAmt = ~0;
18756       if (Mask.getOpcode() == ISD::SRA) {
18757         SDValue Amt = Mask.getOperand(1);
18758         if (isSplatVector(Amt.getNode())) {
18759           SDValue SclrAmt = Amt->getOperand(0);
18760           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18761             SraAmt = C->getZExtValue();
18762         }
18763       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18764         SDValue SraC = Mask.getOperand(1);
18765         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18766       }
18767       if ((SraAmt + 1) != EltBits)
18768         return SDValue();
18769
18770       SDLoc DL(N);
18771
18772       // Now we know we at least have a plendvb with the mask val.  See if
18773       // we can form a psignb/w/d.
18774       // psign = x.type == y.type == mask.type && y = sub(0, x);
18775       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18776           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18777           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18778         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18779                "Unsupported VT for PSIGN");
18780         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18781         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18782       }
18783       // PBLENDVB only available on SSE 4.1
18784       if (!Subtarget->hasSSE41())
18785         return SDValue();
18786
18787       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18788
18789       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18790       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18791       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18792       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18793       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18794     }
18795   }
18796
18797   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18798     return SDValue();
18799
18800   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18801   MachineFunction &MF = DAG.getMachineFunction();
18802   bool OptForSize = MF.getFunction()->getAttributes().
18803     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18804
18805   // SHLD/SHRD instructions have lower register pressure, but on some
18806   // platforms they have higher latency than the equivalent
18807   // series of shifts/or that would otherwise be generated.
18808   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18809   // have higher latencies and we are not optimizing for size.
18810   if (!OptForSize && Subtarget->isSHLDSlow())
18811     return SDValue();
18812
18813   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18814     std::swap(N0, N1);
18815   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18816     return SDValue();
18817   if (!N0.hasOneUse() || !N1.hasOneUse())
18818     return SDValue();
18819
18820   SDValue ShAmt0 = N0.getOperand(1);
18821   if (ShAmt0.getValueType() != MVT::i8)
18822     return SDValue();
18823   SDValue ShAmt1 = N1.getOperand(1);
18824   if (ShAmt1.getValueType() != MVT::i8)
18825     return SDValue();
18826   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18827     ShAmt0 = ShAmt0.getOperand(0);
18828   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18829     ShAmt1 = ShAmt1.getOperand(0);
18830
18831   SDLoc DL(N);
18832   unsigned Opc = X86ISD::SHLD;
18833   SDValue Op0 = N0.getOperand(0);
18834   SDValue Op1 = N1.getOperand(0);
18835   if (ShAmt0.getOpcode() == ISD::SUB) {
18836     Opc = X86ISD::SHRD;
18837     std::swap(Op0, Op1);
18838     std::swap(ShAmt0, ShAmt1);
18839   }
18840
18841   unsigned Bits = VT.getSizeInBits();
18842   if (ShAmt1.getOpcode() == ISD::SUB) {
18843     SDValue Sum = ShAmt1.getOperand(0);
18844     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18845       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18846       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18847         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18848       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18849         return DAG.getNode(Opc, DL, VT,
18850                            Op0, Op1,
18851                            DAG.getNode(ISD::TRUNCATE, DL,
18852                                        MVT::i8, ShAmt0));
18853     }
18854   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18855     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18856     if (ShAmt0C &&
18857         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18858       return DAG.getNode(Opc, DL, VT,
18859                          N0.getOperand(0), N1.getOperand(0),
18860                          DAG.getNode(ISD::TRUNCATE, DL,
18861                                        MVT::i8, ShAmt0));
18862   }
18863
18864   return SDValue();
18865 }
18866
18867 // Generate NEG and CMOV for integer abs.
18868 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18869   EVT VT = N->getValueType(0);
18870
18871   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18872   // 8-bit integer abs to NEG and CMOV.
18873   if (VT.isInteger() && VT.getSizeInBits() == 8)
18874     return SDValue();
18875
18876   SDValue N0 = N->getOperand(0);
18877   SDValue N1 = N->getOperand(1);
18878   SDLoc DL(N);
18879
18880   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18881   // and change it to SUB and CMOV.
18882   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18883       N0.getOpcode() == ISD::ADD &&
18884       N0.getOperand(1) == N1 &&
18885       N1.getOpcode() == ISD::SRA &&
18886       N1.getOperand(0) == N0.getOperand(0))
18887     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18888       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18889         // Generate SUB & CMOV.
18890         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18891                                   DAG.getConstant(0, VT), N0.getOperand(0));
18892
18893         SDValue Ops[] = { N0.getOperand(0), Neg,
18894                           DAG.getConstant(X86::COND_GE, MVT::i8),
18895                           SDValue(Neg.getNode(), 1) };
18896         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18897                            Ops, array_lengthof(Ops));
18898       }
18899   return SDValue();
18900 }
18901
18902 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18903 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18904                                  TargetLowering::DAGCombinerInfo &DCI,
18905                                  const X86Subtarget *Subtarget) {
18906   if (DCI.isBeforeLegalizeOps())
18907     return SDValue();
18908
18909   if (Subtarget->hasCMov()) {
18910     SDValue RV = performIntegerAbsCombine(N, DAG);
18911     if (RV.getNode())
18912       return RV;
18913   }
18914
18915   return SDValue();
18916 }
18917
18918 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18919 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18920                                   TargetLowering::DAGCombinerInfo &DCI,
18921                                   const X86Subtarget *Subtarget) {
18922   LoadSDNode *Ld = cast<LoadSDNode>(N);
18923   EVT RegVT = Ld->getValueType(0);
18924   EVT MemVT = Ld->getMemoryVT();
18925   SDLoc dl(Ld);
18926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18927   unsigned RegSz = RegVT.getSizeInBits();
18928
18929   // On Sandybridge unaligned 256bit loads are inefficient.
18930   ISD::LoadExtType Ext = Ld->getExtensionType();
18931   unsigned Alignment = Ld->getAlignment();
18932   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18933   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18934       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18935     unsigned NumElems = RegVT.getVectorNumElements();
18936     if (NumElems < 2)
18937       return SDValue();
18938
18939     SDValue Ptr = Ld->getBasePtr();
18940     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18941
18942     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18943                                   NumElems/2);
18944     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18945                                 Ld->getPointerInfo(), Ld->isVolatile(),
18946                                 Ld->isNonTemporal(), Ld->isInvariant(),
18947                                 Alignment);
18948     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18949     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18950                                 Ld->getPointerInfo(), Ld->isVolatile(),
18951                                 Ld->isNonTemporal(), Ld->isInvariant(),
18952                                 std::min(16U, Alignment));
18953     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18954                              Load1.getValue(1),
18955                              Load2.getValue(1));
18956
18957     SDValue NewVec = DAG.getUNDEF(RegVT);
18958     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18959     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18960     return DCI.CombineTo(N, NewVec, TF, true);
18961   }
18962
18963   // If this is a vector EXT Load then attempt to optimize it using a
18964   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18965   // expansion is still better than scalar code.
18966   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18967   // emit a shuffle and a arithmetic shift.
18968   // TODO: It is possible to support ZExt by zeroing the undef values
18969   // during the shuffle phase or after the shuffle.
18970   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18971       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18972     assert(MemVT != RegVT && "Cannot extend to the same type");
18973     assert(MemVT.isVector() && "Must load a vector from memory");
18974
18975     unsigned NumElems = RegVT.getVectorNumElements();
18976     unsigned MemSz = MemVT.getSizeInBits();
18977     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18978
18979     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18980       return SDValue();
18981
18982     // All sizes must be a power of two.
18983     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18984       return SDValue();
18985
18986     // Attempt to load the original value using scalar loads.
18987     // Find the largest scalar type that divides the total loaded size.
18988     MVT SclrLoadTy = MVT::i8;
18989     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18990          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18991       MVT Tp = (MVT::SimpleValueType)tp;
18992       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18993         SclrLoadTy = Tp;
18994       }
18995     }
18996
18997     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18998     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18999         (64 <= MemSz))
19000       SclrLoadTy = MVT::f64;
19001
19002     // Calculate the number of scalar loads that we need to perform
19003     // in order to load our vector from memory.
19004     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19005     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19006       return SDValue();
19007
19008     unsigned loadRegZize = RegSz;
19009     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19010       loadRegZize /= 2;
19011
19012     // Represent our vector as a sequence of elements which are the
19013     // largest scalar that we can load.
19014     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19015       loadRegZize/SclrLoadTy.getSizeInBits());
19016
19017     // Represent the data using the same element type that is stored in
19018     // memory. In practice, we ''widen'' MemVT.
19019     EVT WideVecVT =
19020           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19021                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19022
19023     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19024       "Invalid vector type");
19025
19026     // We can't shuffle using an illegal type.
19027     if (!TLI.isTypeLegal(WideVecVT))
19028       return SDValue();
19029
19030     SmallVector<SDValue, 8> Chains;
19031     SDValue Ptr = Ld->getBasePtr();
19032     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19033                                         TLI.getPointerTy());
19034     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19035
19036     for (unsigned i = 0; i < NumLoads; ++i) {
19037       // Perform a single load.
19038       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19039                                        Ptr, Ld->getPointerInfo(),
19040                                        Ld->isVolatile(), Ld->isNonTemporal(),
19041                                        Ld->isInvariant(), Ld->getAlignment());
19042       Chains.push_back(ScalarLoad.getValue(1));
19043       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19044       // another round of DAGCombining.
19045       if (i == 0)
19046         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19047       else
19048         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19049                           ScalarLoad, DAG.getIntPtrConstant(i));
19050
19051       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19052     }
19053
19054     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19055                                Chains.size());
19056
19057     // Bitcast the loaded value to a vector of the original element type, in
19058     // the size of the target vector type.
19059     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19060     unsigned SizeRatio = RegSz/MemSz;
19061
19062     if (Ext == ISD::SEXTLOAD) {
19063       // If we have SSE4.1 we can directly emit a VSEXT node.
19064       if (Subtarget->hasSSE41()) {
19065         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19066         return DCI.CombineTo(N, Sext, TF, true);
19067       }
19068
19069       // Otherwise we'll shuffle the small elements in the high bits of the
19070       // larger type and perform an arithmetic shift. If the shift is not legal
19071       // it's better to scalarize.
19072       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19073         return SDValue();
19074
19075       // Redistribute the loaded elements into the different locations.
19076       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19077       for (unsigned i = 0; i != NumElems; ++i)
19078         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19079
19080       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19081                                            DAG.getUNDEF(WideVecVT),
19082                                            &ShuffleVec[0]);
19083
19084       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19085
19086       // Build the arithmetic shift.
19087       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19088                      MemVT.getVectorElementType().getSizeInBits();
19089       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19090                           DAG.getConstant(Amt, RegVT));
19091
19092       return DCI.CombineTo(N, Shuff, TF, true);
19093     }
19094
19095     // Redistribute the loaded elements into the different locations.
19096     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19097     for (unsigned i = 0; i != NumElems; ++i)
19098       ShuffleVec[i*SizeRatio] = i;
19099
19100     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19101                                          DAG.getUNDEF(WideVecVT),
19102                                          &ShuffleVec[0]);
19103
19104     // Bitcast to the requested type.
19105     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19106     // Replace the original load with the new sequence
19107     // and return the new chain.
19108     return DCI.CombineTo(N, Shuff, TF, true);
19109   }
19110
19111   return SDValue();
19112 }
19113
19114 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19115 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19116                                    const X86Subtarget *Subtarget) {
19117   StoreSDNode *St = cast<StoreSDNode>(N);
19118   EVT VT = St->getValue().getValueType();
19119   EVT StVT = St->getMemoryVT();
19120   SDLoc dl(St);
19121   SDValue StoredVal = St->getOperand(1);
19122   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19123
19124   // If we are saving a concatenation of two XMM registers, perform two stores.
19125   // On Sandy Bridge, 256-bit memory operations are executed by two
19126   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19127   // memory  operation.
19128   unsigned Alignment = St->getAlignment();
19129   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19130   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19131       StVT == VT && !IsAligned) {
19132     unsigned NumElems = VT.getVectorNumElements();
19133     if (NumElems < 2)
19134       return SDValue();
19135
19136     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19137     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19138
19139     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19140     SDValue Ptr0 = St->getBasePtr();
19141     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19142
19143     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19144                                 St->getPointerInfo(), St->isVolatile(),
19145                                 St->isNonTemporal(), Alignment);
19146     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19147                                 St->getPointerInfo(), St->isVolatile(),
19148                                 St->isNonTemporal(),
19149                                 std::min(16U, Alignment));
19150     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19151   }
19152
19153   // Optimize trunc store (of multiple scalars) to shuffle and store.
19154   // First, pack all of the elements in one place. Next, store to memory
19155   // in fewer chunks.
19156   if (St->isTruncatingStore() && VT.isVector()) {
19157     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19158     unsigned NumElems = VT.getVectorNumElements();
19159     assert(StVT != VT && "Cannot truncate to the same type");
19160     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19161     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19162
19163     // From, To sizes and ElemCount must be pow of two
19164     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19165     // We are going to use the original vector elt for storing.
19166     // Accumulated smaller vector elements must be a multiple of the store size.
19167     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19168
19169     unsigned SizeRatio  = FromSz / ToSz;
19170
19171     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19172
19173     // Create a type on which we perform the shuffle
19174     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19175             StVT.getScalarType(), NumElems*SizeRatio);
19176
19177     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19178
19179     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19180     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19181     for (unsigned i = 0; i != NumElems; ++i)
19182       ShuffleVec[i] = i * SizeRatio;
19183
19184     // Can't shuffle using an illegal type.
19185     if (!TLI.isTypeLegal(WideVecVT))
19186       return SDValue();
19187
19188     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19189                                          DAG.getUNDEF(WideVecVT),
19190                                          &ShuffleVec[0]);
19191     // At this point all of the data is stored at the bottom of the
19192     // register. We now need to save it to mem.
19193
19194     // Find the largest store unit
19195     MVT StoreType = MVT::i8;
19196     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19197          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19198       MVT Tp = (MVT::SimpleValueType)tp;
19199       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19200         StoreType = Tp;
19201     }
19202
19203     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19204     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19205         (64 <= NumElems * ToSz))
19206       StoreType = MVT::f64;
19207
19208     // Bitcast the original vector into a vector of store-size units
19209     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19210             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19211     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19212     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19213     SmallVector<SDValue, 8> Chains;
19214     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19215                                         TLI.getPointerTy());
19216     SDValue Ptr = St->getBasePtr();
19217
19218     // Perform one or more big stores into memory.
19219     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19220       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19221                                    StoreType, ShuffWide,
19222                                    DAG.getIntPtrConstant(i));
19223       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19224                                 St->getPointerInfo(), St->isVolatile(),
19225                                 St->isNonTemporal(), St->getAlignment());
19226       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19227       Chains.push_back(Ch);
19228     }
19229
19230     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19231                                Chains.size());
19232   }
19233
19234   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19235   // the FP state in cases where an emms may be missing.
19236   // A preferable solution to the general problem is to figure out the right
19237   // places to insert EMMS.  This qualifies as a quick hack.
19238
19239   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19240   if (VT.getSizeInBits() != 64)
19241     return SDValue();
19242
19243   const Function *F = DAG.getMachineFunction().getFunction();
19244   bool NoImplicitFloatOps = F->getAttributes().
19245     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19246   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19247                      && Subtarget->hasSSE2();
19248   if ((VT.isVector() ||
19249        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19250       isa<LoadSDNode>(St->getValue()) &&
19251       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19252       St->getChain().hasOneUse() && !St->isVolatile()) {
19253     SDNode* LdVal = St->getValue().getNode();
19254     LoadSDNode *Ld = nullptr;
19255     int TokenFactorIndex = -1;
19256     SmallVector<SDValue, 8> Ops;
19257     SDNode* ChainVal = St->getChain().getNode();
19258     // Must be a store of a load.  We currently handle two cases:  the load
19259     // is a direct child, and it's under an intervening TokenFactor.  It is
19260     // possible to dig deeper under nested TokenFactors.
19261     if (ChainVal == LdVal)
19262       Ld = cast<LoadSDNode>(St->getChain());
19263     else if (St->getValue().hasOneUse() &&
19264              ChainVal->getOpcode() == ISD::TokenFactor) {
19265       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19266         if (ChainVal->getOperand(i).getNode() == LdVal) {
19267           TokenFactorIndex = i;
19268           Ld = cast<LoadSDNode>(St->getValue());
19269         } else
19270           Ops.push_back(ChainVal->getOperand(i));
19271       }
19272     }
19273
19274     if (!Ld || !ISD::isNormalLoad(Ld))
19275       return SDValue();
19276
19277     // If this is not the MMX case, i.e. we are just turning i64 load/store
19278     // into f64 load/store, avoid the transformation if there are multiple
19279     // uses of the loaded value.
19280     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19281       return SDValue();
19282
19283     SDLoc LdDL(Ld);
19284     SDLoc StDL(N);
19285     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19286     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19287     // pair instead.
19288     if (Subtarget->is64Bit() || F64IsLegal) {
19289       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19290       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19291                                   Ld->getPointerInfo(), Ld->isVolatile(),
19292                                   Ld->isNonTemporal(), Ld->isInvariant(),
19293                                   Ld->getAlignment());
19294       SDValue NewChain = NewLd.getValue(1);
19295       if (TokenFactorIndex != -1) {
19296         Ops.push_back(NewChain);
19297         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19298                                Ops.size());
19299       }
19300       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19301                           St->getPointerInfo(),
19302                           St->isVolatile(), St->isNonTemporal(),
19303                           St->getAlignment());
19304     }
19305
19306     // Otherwise, lower to two pairs of 32-bit loads / stores.
19307     SDValue LoAddr = Ld->getBasePtr();
19308     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19309                                  DAG.getConstant(4, MVT::i32));
19310
19311     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19312                                Ld->getPointerInfo(),
19313                                Ld->isVolatile(), Ld->isNonTemporal(),
19314                                Ld->isInvariant(), Ld->getAlignment());
19315     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19316                                Ld->getPointerInfo().getWithOffset(4),
19317                                Ld->isVolatile(), Ld->isNonTemporal(),
19318                                Ld->isInvariant(),
19319                                MinAlign(Ld->getAlignment(), 4));
19320
19321     SDValue NewChain = LoLd.getValue(1);
19322     if (TokenFactorIndex != -1) {
19323       Ops.push_back(LoLd);
19324       Ops.push_back(HiLd);
19325       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19326                              Ops.size());
19327     }
19328
19329     LoAddr = St->getBasePtr();
19330     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19331                          DAG.getConstant(4, MVT::i32));
19332
19333     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19334                                 St->getPointerInfo(),
19335                                 St->isVolatile(), St->isNonTemporal(),
19336                                 St->getAlignment());
19337     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19338                                 St->getPointerInfo().getWithOffset(4),
19339                                 St->isVolatile(),
19340                                 St->isNonTemporal(),
19341                                 MinAlign(St->getAlignment(), 4));
19342     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19343   }
19344   return SDValue();
19345 }
19346
19347 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19348 /// and return the operands for the horizontal operation in LHS and RHS.  A
19349 /// horizontal operation performs the binary operation on successive elements
19350 /// of its first operand, then on successive elements of its second operand,
19351 /// returning the resulting values in a vector.  For example, if
19352 ///   A = < float a0, float a1, float a2, float a3 >
19353 /// and
19354 ///   B = < float b0, float b1, float b2, float b3 >
19355 /// then the result of doing a horizontal operation on A and B is
19356 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19357 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19358 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19359 /// set to A, RHS to B, and the routine returns 'true'.
19360 /// Note that the binary operation should have the property that if one of the
19361 /// operands is UNDEF then the result is UNDEF.
19362 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19363   // Look for the following pattern: if
19364   //   A = < float a0, float a1, float a2, float a3 >
19365   //   B = < float b0, float b1, float b2, float b3 >
19366   // and
19367   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19368   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19369   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19370   // which is A horizontal-op B.
19371
19372   // At least one of the operands should be a vector shuffle.
19373   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19374       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19375     return false;
19376
19377   MVT VT = LHS.getSimpleValueType();
19378
19379   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19380          "Unsupported vector type for horizontal add/sub");
19381
19382   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19383   // operate independently on 128-bit lanes.
19384   unsigned NumElts = VT.getVectorNumElements();
19385   unsigned NumLanes = VT.getSizeInBits()/128;
19386   unsigned NumLaneElts = NumElts / NumLanes;
19387   assert((NumLaneElts % 2 == 0) &&
19388          "Vector type should have an even number of elements in each lane");
19389   unsigned HalfLaneElts = NumLaneElts/2;
19390
19391   // View LHS in the form
19392   //   LHS = VECTOR_SHUFFLE A, B, LMask
19393   // If LHS is not a shuffle then pretend it is the shuffle
19394   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19395   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19396   // type VT.
19397   SDValue A, B;
19398   SmallVector<int, 16> LMask(NumElts);
19399   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19400     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19401       A = LHS.getOperand(0);
19402     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19403       B = LHS.getOperand(1);
19404     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19405     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19406   } else {
19407     if (LHS.getOpcode() != ISD::UNDEF)
19408       A = LHS;
19409     for (unsigned i = 0; i != NumElts; ++i)
19410       LMask[i] = i;
19411   }
19412
19413   // Likewise, view RHS in the form
19414   //   RHS = VECTOR_SHUFFLE C, D, RMask
19415   SDValue C, D;
19416   SmallVector<int, 16> RMask(NumElts);
19417   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19418     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19419       C = RHS.getOperand(0);
19420     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19421       D = RHS.getOperand(1);
19422     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19423     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19424   } else {
19425     if (RHS.getOpcode() != ISD::UNDEF)
19426       C = RHS;
19427     for (unsigned i = 0; i != NumElts; ++i)
19428       RMask[i] = i;
19429   }
19430
19431   // Check that the shuffles are both shuffling the same vectors.
19432   if (!(A == C && B == D) && !(A == D && B == C))
19433     return false;
19434
19435   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19436   if (!A.getNode() && !B.getNode())
19437     return false;
19438
19439   // If A and B occur in reverse order in RHS, then "swap" them (which means
19440   // rewriting the mask).
19441   if (A != C)
19442     CommuteVectorShuffleMask(RMask, NumElts);
19443
19444   // At this point LHS and RHS are equivalent to
19445   //   LHS = VECTOR_SHUFFLE A, B, LMask
19446   //   RHS = VECTOR_SHUFFLE A, B, RMask
19447   // Check that the masks correspond to performing a horizontal operation.
19448   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19449     for (unsigned i = 0; i != NumLaneElts; ++i) {
19450       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19451
19452       // Ignore any UNDEF components.
19453       if (LIdx < 0 || RIdx < 0 ||
19454           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19455           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19456         continue;
19457
19458       // Check that successive elements are being operated on.  If not, this is
19459       // not a horizontal operation.
19460       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19461       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19462       if (!(LIdx == Index && RIdx == Index + 1) &&
19463           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19464         return false;
19465     }
19466   }
19467
19468   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19469   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19470   return true;
19471 }
19472
19473 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19474 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19475                                   const X86Subtarget *Subtarget) {
19476   EVT VT = N->getValueType(0);
19477   SDValue LHS = N->getOperand(0);
19478   SDValue RHS = N->getOperand(1);
19479
19480   // Try to synthesize horizontal adds from adds of shuffles.
19481   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19482        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19483       isHorizontalBinOp(LHS, RHS, true))
19484     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19485   return SDValue();
19486 }
19487
19488 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19489 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19490                                   const X86Subtarget *Subtarget) {
19491   EVT VT = N->getValueType(0);
19492   SDValue LHS = N->getOperand(0);
19493   SDValue RHS = N->getOperand(1);
19494
19495   // Try to synthesize horizontal subs from subs of shuffles.
19496   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19497        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19498       isHorizontalBinOp(LHS, RHS, false))
19499     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19500   return SDValue();
19501 }
19502
19503 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19504 /// X86ISD::FXOR nodes.
19505 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19506   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19507   // F[X]OR(0.0, x) -> x
19508   // F[X]OR(x, 0.0) -> x
19509   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19510     if (C->getValueAPF().isPosZero())
19511       return N->getOperand(1);
19512   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19513     if (C->getValueAPF().isPosZero())
19514       return N->getOperand(0);
19515   return SDValue();
19516 }
19517
19518 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19519 /// X86ISD::FMAX nodes.
19520 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19521   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19522
19523   // Only perform optimizations if UnsafeMath is used.
19524   if (!DAG.getTarget().Options.UnsafeFPMath)
19525     return SDValue();
19526
19527   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19528   // into FMINC and FMAXC, which are Commutative operations.
19529   unsigned NewOp = 0;
19530   switch (N->getOpcode()) {
19531     default: llvm_unreachable("unknown opcode");
19532     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19533     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19534   }
19535
19536   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19537                      N->getOperand(0), N->getOperand(1));
19538 }
19539
19540 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19541 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19542   // FAND(0.0, x) -> 0.0
19543   // FAND(x, 0.0) -> 0.0
19544   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19545     if (C->getValueAPF().isPosZero())
19546       return N->getOperand(0);
19547   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19548     if (C->getValueAPF().isPosZero())
19549       return N->getOperand(1);
19550   return SDValue();
19551 }
19552
19553 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19554 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19555   // FANDN(x, 0.0) -> 0.0
19556   // FANDN(0.0, x) -> x
19557   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19558     if (C->getValueAPF().isPosZero())
19559       return N->getOperand(1);
19560   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19561     if (C->getValueAPF().isPosZero())
19562       return N->getOperand(1);
19563   return SDValue();
19564 }
19565
19566 static SDValue PerformBTCombine(SDNode *N,
19567                                 SelectionDAG &DAG,
19568                                 TargetLowering::DAGCombinerInfo &DCI) {
19569   // BT ignores high bits in the bit index operand.
19570   SDValue Op1 = N->getOperand(1);
19571   if (Op1.hasOneUse()) {
19572     unsigned BitWidth = Op1.getValueSizeInBits();
19573     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19574     APInt KnownZero, KnownOne;
19575     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19576                                           !DCI.isBeforeLegalizeOps());
19577     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19578     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19579         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19580       DCI.CommitTargetLoweringOpt(TLO);
19581   }
19582   return SDValue();
19583 }
19584
19585 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19586   SDValue Op = N->getOperand(0);
19587   if (Op.getOpcode() == ISD::BITCAST)
19588     Op = Op.getOperand(0);
19589   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19590   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19591       VT.getVectorElementType().getSizeInBits() ==
19592       OpVT.getVectorElementType().getSizeInBits()) {
19593     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19594   }
19595   return SDValue();
19596 }
19597
19598 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19599                                                const X86Subtarget *Subtarget) {
19600   EVT VT = N->getValueType(0);
19601   if (!VT.isVector())
19602     return SDValue();
19603
19604   SDValue N0 = N->getOperand(0);
19605   SDValue N1 = N->getOperand(1);
19606   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19607   SDLoc dl(N);
19608
19609   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19610   // both SSE and AVX2 since there is no sign-extended shift right
19611   // operation on a vector with 64-bit elements.
19612   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19613   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19614   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19615       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19616     SDValue N00 = N0.getOperand(0);
19617
19618     // EXTLOAD has a better solution on AVX2,
19619     // it may be replaced with X86ISD::VSEXT node.
19620     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19621       if (!ISD::isNormalLoad(N00.getNode()))
19622         return SDValue();
19623
19624     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19625         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19626                                   N00, N1);
19627       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19628     }
19629   }
19630   return SDValue();
19631 }
19632
19633 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19634                                   TargetLowering::DAGCombinerInfo &DCI,
19635                                   const X86Subtarget *Subtarget) {
19636   if (!DCI.isBeforeLegalizeOps())
19637     return SDValue();
19638
19639   if (!Subtarget->hasFp256())
19640     return SDValue();
19641
19642   EVT VT = N->getValueType(0);
19643   if (VT.isVector() && VT.getSizeInBits() == 256) {
19644     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19645     if (R.getNode())
19646       return R;
19647   }
19648
19649   return SDValue();
19650 }
19651
19652 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19653                                  const X86Subtarget* Subtarget) {
19654   SDLoc dl(N);
19655   EVT VT = N->getValueType(0);
19656
19657   // Let legalize expand this if it isn't a legal type yet.
19658   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19659     return SDValue();
19660
19661   EVT ScalarVT = VT.getScalarType();
19662   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19663       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19664     return SDValue();
19665
19666   SDValue A = N->getOperand(0);
19667   SDValue B = N->getOperand(1);
19668   SDValue C = N->getOperand(2);
19669
19670   bool NegA = (A.getOpcode() == ISD::FNEG);
19671   bool NegB = (B.getOpcode() == ISD::FNEG);
19672   bool NegC = (C.getOpcode() == ISD::FNEG);
19673
19674   // Negative multiplication when NegA xor NegB
19675   bool NegMul = (NegA != NegB);
19676   if (NegA)
19677     A = A.getOperand(0);
19678   if (NegB)
19679     B = B.getOperand(0);
19680   if (NegC)
19681     C = C.getOperand(0);
19682
19683   unsigned Opcode;
19684   if (!NegMul)
19685     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19686   else
19687     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19688
19689   return DAG.getNode(Opcode, dl, VT, A, B, C);
19690 }
19691
19692 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19693                                   TargetLowering::DAGCombinerInfo &DCI,
19694                                   const X86Subtarget *Subtarget) {
19695   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19696   //           (and (i32 x86isd::setcc_carry), 1)
19697   // This eliminates the zext. This transformation is necessary because
19698   // ISD::SETCC is always legalized to i8.
19699   SDLoc dl(N);
19700   SDValue N0 = N->getOperand(0);
19701   EVT VT = N->getValueType(0);
19702
19703   if (N0.getOpcode() == ISD::AND &&
19704       N0.hasOneUse() &&
19705       N0.getOperand(0).hasOneUse()) {
19706     SDValue N00 = N0.getOperand(0);
19707     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19708       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19709       if (!C || C->getZExtValue() != 1)
19710         return SDValue();
19711       return DAG.getNode(ISD::AND, dl, VT,
19712                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19713                                      N00.getOperand(0), N00.getOperand(1)),
19714                          DAG.getConstant(1, VT));
19715     }
19716   }
19717
19718   if (N0.getOpcode() == ISD::TRUNCATE &&
19719       N0.hasOneUse() &&
19720       N0.getOperand(0).hasOneUse()) {
19721     SDValue N00 = N0.getOperand(0);
19722     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19723       return DAG.getNode(ISD::AND, dl, VT,
19724                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19725                                      N00.getOperand(0), N00.getOperand(1)),
19726                          DAG.getConstant(1, VT));
19727     }
19728   }
19729   if (VT.is256BitVector()) {
19730     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19731     if (R.getNode())
19732       return R;
19733   }
19734
19735   return SDValue();
19736 }
19737
19738 // Optimize x == -y --> x+y == 0
19739 //          x != -y --> x+y != 0
19740 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19741                                       const X86Subtarget* Subtarget) {
19742   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19743   SDValue LHS = N->getOperand(0);
19744   SDValue RHS = N->getOperand(1);
19745   EVT VT = N->getValueType(0);
19746   SDLoc DL(N);
19747
19748   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19749     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19750       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19751         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19752                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19753         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19754                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19755       }
19756   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19757     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19758       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19759         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19760                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19761         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19762                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19763       }
19764
19765   if (VT.getScalarType() == MVT::i1) {
19766     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19767       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19768     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19769     if (!IsSEXT0 && !IsVZero0)
19770       return SDValue();
19771     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19772       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19773     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19774
19775     if (!IsSEXT1 && !IsVZero1)
19776       return SDValue();
19777
19778     if (IsSEXT0 && IsVZero1) {
19779       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19780       if (CC == ISD::SETEQ)
19781         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19782       return LHS.getOperand(0);
19783     }
19784     if (IsSEXT1 && IsVZero0) {
19785       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19786       if (CC == ISD::SETEQ)
19787         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19788       return RHS.getOperand(0);
19789     }
19790   }
19791
19792   return SDValue();
19793 }
19794
19795 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19796 // as "sbb reg,reg", since it can be extended without zext and produces
19797 // an all-ones bit which is more useful than 0/1 in some cases.
19798 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19799                                MVT VT) {
19800   if (VT == MVT::i8)
19801     return DAG.getNode(ISD::AND, DL, VT,
19802                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19803                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19804                        DAG.getConstant(1, VT));
19805   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19806   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19807                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19808                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19809 }
19810
19811 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19812 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19813                                    TargetLowering::DAGCombinerInfo &DCI,
19814                                    const X86Subtarget *Subtarget) {
19815   SDLoc DL(N);
19816   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19817   SDValue EFLAGS = N->getOperand(1);
19818
19819   if (CC == X86::COND_A) {
19820     // Try to convert COND_A into COND_B in an attempt to facilitate
19821     // materializing "setb reg".
19822     //
19823     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19824     // cannot take an immediate as its first operand.
19825     //
19826     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19827         EFLAGS.getValueType().isInteger() &&
19828         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19829       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19830                                    EFLAGS.getNode()->getVTList(),
19831                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19832       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19833       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19834     }
19835   }
19836
19837   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19838   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19839   // cases.
19840   if (CC == X86::COND_B)
19841     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19842
19843   SDValue Flags;
19844
19845   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19846   if (Flags.getNode()) {
19847     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19848     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19849   }
19850
19851   return SDValue();
19852 }
19853
19854 // Optimize branch condition evaluation.
19855 //
19856 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19857                                     TargetLowering::DAGCombinerInfo &DCI,
19858                                     const X86Subtarget *Subtarget) {
19859   SDLoc DL(N);
19860   SDValue Chain = N->getOperand(0);
19861   SDValue Dest = N->getOperand(1);
19862   SDValue EFLAGS = N->getOperand(3);
19863   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19864
19865   SDValue Flags;
19866
19867   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19868   if (Flags.getNode()) {
19869     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19870     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19871                        Flags);
19872   }
19873
19874   return SDValue();
19875 }
19876
19877 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19878                                         const X86TargetLowering *XTLI) {
19879   SDValue Op0 = N->getOperand(0);
19880   EVT InVT = Op0->getValueType(0);
19881
19882   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19883   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19884     SDLoc dl(N);
19885     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19886     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19887     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19888   }
19889
19890   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19891   // a 32-bit target where SSE doesn't support i64->FP operations.
19892   if (Op0.getOpcode() == ISD::LOAD) {
19893     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19894     EVT VT = Ld->getValueType(0);
19895     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19896         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19897         !XTLI->getSubtarget()->is64Bit() &&
19898         VT == MVT::i64) {
19899       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19900                                           Ld->getChain(), Op0, DAG);
19901       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19902       return FILDChain;
19903     }
19904   }
19905   return SDValue();
19906 }
19907
19908 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19909 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19910                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19911   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19912   // the result is either zero or one (depending on the input carry bit).
19913   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19914   if (X86::isZeroNode(N->getOperand(0)) &&
19915       X86::isZeroNode(N->getOperand(1)) &&
19916       // We don't have a good way to replace an EFLAGS use, so only do this when
19917       // dead right now.
19918       SDValue(N, 1).use_empty()) {
19919     SDLoc DL(N);
19920     EVT VT = N->getValueType(0);
19921     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19922     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19923                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19924                                            DAG.getConstant(X86::COND_B,MVT::i8),
19925                                            N->getOperand(2)),
19926                                DAG.getConstant(1, VT));
19927     return DCI.CombineTo(N, Res1, CarryOut);
19928   }
19929
19930   return SDValue();
19931 }
19932
19933 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19934 //      (add Y, (setne X, 0)) -> sbb -1, Y
19935 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19936 //      (sub (setne X, 0), Y) -> adc -1, Y
19937 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19938   SDLoc DL(N);
19939
19940   // Look through ZExts.
19941   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19942   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19943     return SDValue();
19944
19945   SDValue SetCC = Ext.getOperand(0);
19946   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19947     return SDValue();
19948
19949   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19950   if (CC != X86::COND_E && CC != X86::COND_NE)
19951     return SDValue();
19952
19953   SDValue Cmp = SetCC.getOperand(1);
19954   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19955       !X86::isZeroNode(Cmp.getOperand(1)) ||
19956       !Cmp.getOperand(0).getValueType().isInteger())
19957     return SDValue();
19958
19959   SDValue CmpOp0 = Cmp.getOperand(0);
19960   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19961                                DAG.getConstant(1, CmpOp0.getValueType()));
19962
19963   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19964   if (CC == X86::COND_NE)
19965     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19966                        DL, OtherVal.getValueType(), OtherVal,
19967                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19968   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19969                      DL, OtherVal.getValueType(), OtherVal,
19970                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19971 }
19972
19973 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19974 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19975                                  const X86Subtarget *Subtarget) {
19976   EVT VT = N->getValueType(0);
19977   SDValue Op0 = N->getOperand(0);
19978   SDValue Op1 = N->getOperand(1);
19979
19980   // Try to synthesize horizontal adds from adds of shuffles.
19981   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19982        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19983       isHorizontalBinOp(Op0, Op1, true))
19984     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19985
19986   return OptimizeConditionalInDecrement(N, DAG);
19987 }
19988
19989 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19990                                  const X86Subtarget *Subtarget) {
19991   SDValue Op0 = N->getOperand(0);
19992   SDValue Op1 = N->getOperand(1);
19993
19994   // X86 can't encode an immediate LHS of a sub. See if we can push the
19995   // negation into a preceding instruction.
19996   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19997     // If the RHS of the sub is a XOR with one use and a constant, invert the
19998     // immediate. Then add one to the LHS of the sub so we can turn
19999     // X-Y -> X+~Y+1, saving one register.
20000     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20001         isa<ConstantSDNode>(Op1.getOperand(1))) {
20002       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20003       EVT VT = Op0.getValueType();
20004       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20005                                    Op1.getOperand(0),
20006                                    DAG.getConstant(~XorC, VT));
20007       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20008                          DAG.getConstant(C->getAPIntValue()+1, VT));
20009     }
20010   }
20011
20012   // Try to synthesize horizontal adds from adds of shuffles.
20013   EVT VT = N->getValueType(0);
20014   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20015        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20016       isHorizontalBinOp(Op0, Op1, true))
20017     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20018
20019   return OptimizeConditionalInDecrement(N, DAG);
20020 }
20021
20022 /// performVZEXTCombine - Performs build vector combines
20023 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20024                                         TargetLowering::DAGCombinerInfo &DCI,
20025                                         const X86Subtarget *Subtarget) {
20026   // (vzext (bitcast (vzext (x)) -> (vzext x)
20027   SDValue In = N->getOperand(0);
20028   while (In.getOpcode() == ISD::BITCAST)
20029     In = In.getOperand(0);
20030
20031   if (In.getOpcode() != X86ISD::VZEXT)
20032     return SDValue();
20033
20034   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20035                      In.getOperand(0));
20036 }
20037
20038 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20039                                              DAGCombinerInfo &DCI) const {
20040   SelectionDAG &DAG = DCI.DAG;
20041   switch (N->getOpcode()) {
20042   default: break;
20043   case ISD::EXTRACT_VECTOR_ELT:
20044     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20045   case ISD::VSELECT:
20046   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20047   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20048   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20049   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20050   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20051   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20052   case ISD::SHL:
20053   case ISD::SRA:
20054   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20055   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20056   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20057   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20058   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20059   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20060   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20061   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20062   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20063   case X86ISD::FXOR:
20064   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20065   case X86ISD::FMIN:
20066   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20067   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20068   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20069   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20070   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20071   case ISD::ANY_EXTEND:
20072   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20073   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20074   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20075   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20076   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20077   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20078   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20079   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20080   case X86ISD::SHUFP:       // Handle all target specific shuffles
20081   case X86ISD::PALIGNR:
20082   case X86ISD::UNPCKH:
20083   case X86ISD::UNPCKL:
20084   case X86ISD::MOVHLPS:
20085   case X86ISD::MOVLHPS:
20086   case X86ISD::PSHUFD:
20087   case X86ISD::PSHUFHW:
20088   case X86ISD::PSHUFLW:
20089   case X86ISD::MOVSS:
20090   case X86ISD::MOVSD:
20091   case X86ISD::VPERMILP:
20092   case X86ISD::VPERM2X128:
20093   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20094   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20095   }
20096
20097   return SDValue();
20098 }
20099
20100 /// isTypeDesirableForOp - Return true if the target has native support for
20101 /// the specified value type and it is 'desirable' to use the type for the
20102 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20103 /// instruction encodings are longer and some i16 instructions are slow.
20104 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20105   if (!isTypeLegal(VT))
20106     return false;
20107   if (VT != MVT::i16)
20108     return true;
20109
20110   switch (Opc) {
20111   default:
20112     return true;
20113   case ISD::LOAD:
20114   case ISD::SIGN_EXTEND:
20115   case ISD::ZERO_EXTEND:
20116   case ISD::ANY_EXTEND:
20117   case ISD::SHL:
20118   case ISD::SRL:
20119   case ISD::SUB:
20120   case ISD::ADD:
20121   case ISD::MUL:
20122   case ISD::AND:
20123   case ISD::OR:
20124   case ISD::XOR:
20125     return false;
20126   }
20127 }
20128
20129 /// IsDesirableToPromoteOp - This method query the target whether it is
20130 /// beneficial for dag combiner to promote the specified node. If true, it
20131 /// should return the desired promotion type by reference.
20132 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20133   EVT VT = Op.getValueType();
20134   if (VT != MVT::i16)
20135     return false;
20136
20137   bool Promote = false;
20138   bool Commute = false;
20139   switch (Op.getOpcode()) {
20140   default: break;
20141   case ISD::LOAD: {
20142     LoadSDNode *LD = cast<LoadSDNode>(Op);
20143     // If the non-extending load has a single use and it's not live out, then it
20144     // might be folded.
20145     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20146                                                      Op.hasOneUse()*/) {
20147       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20148              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20149         // The only case where we'd want to promote LOAD (rather then it being
20150         // promoted as an operand is when it's only use is liveout.
20151         if (UI->getOpcode() != ISD::CopyToReg)
20152           return false;
20153       }
20154     }
20155     Promote = true;
20156     break;
20157   }
20158   case ISD::SIGN_EXTEND:
20159   case ISD::ZERO_EXTEND:
20160   case ISD::ANY_EXTEND:
20161     Promote = true;
20162     break;
20163   case ISD::SHL:
20164   case ISD::SRL: {
20165     SDValue N0 = Op.getOperand(0);
20166     // Look out for (store (shl (load), x)).
20167     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20168       return false;
20169     Promote = true;
20170     break;
20171   }
20172   case ISD::ADD:
20173   case ISD::MUL:
20174   case ISD::AND:
20175   case ISD::OR:
20176   case ISD::XOR:
20177     Commute = true;
20178     // fallthrough
20179   case ISD::SUB: {
20180     SDValue N0 = Op.getOperand(0);
20181     SDValue N1 = Op.getOperand(1);
20182     if (!Commute && MayFoldLoad(N1))
20183       return false;
20184     // Avoid disabling potential load folding opportunities.
20185     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20186       return false;
20187     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20188       return false;
20189     Promote = true;
20190   }
20191   }
20192
20193   PVT = MVT::i32;
20194   return Promote;
20195 }
20196
20197 //===----------------------------------------------------------------------===//
20198 //                           X86 Inline Assembly Support
20199 //===----------------------------------------------------------------------===//
20200
20201 namespace {
20202   // Helper to match a string separated by whitespace.
20203   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20204     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20205
20206     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20207       StringRef piece(*args[i]);
20208       if (!s.startswith(piece)) // Check if the piece matches.
20209         return false;
20210
20211       s = s.substr(piece.size());
20212       StringRef::size_type pos = s.find_first_not_of(" \t");
20213       if (pos == 0) // We matched a prefix.
20214         return false;
20215
20216       s = s.substr(pos);
20217     }
20218
20219     return s.empty();
20220   }
20221   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20222 }
20223
20224 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20225
20226   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20227     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20228         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20229         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20230
20231       if (AsmPieces.size() == 3)
20232         return true;
20233       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20234         return true;
20235     }
20236   }
20237   return false;
20238 }
20239
20240 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20241   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20242
20243   std::string AsmStr = IA->getAsmString();
20244
20245   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20246   if (!Ty || Ty->getBitWidth() % 16 != 0)
20247     return false;
20248
20249   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20250   SmallVector<StringRef, 4> AsmPieces;
20251   SplitString(AsmStr, AsmPieces, ";\n");
20252
20253   switch (AsmPieces.size()) {
20254   default: return false;
20255   case 1:
20256     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20257     // we will turn this bswap into something that will be lowered to logical
20258     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20259     // lower so don't worry about this.
20260     // bswap $0
20261     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20262         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20263         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20264         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20265         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20266         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20267       // No need to check constraints, nothing other than the equivalent of
20268       // "=r,0" would be valid here.
20269       return IntrinsicLowering::LowerToByteSwap(CI);
20270     }
20271
20272     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20273     if (CI->getType()->isIntegerTy(16) &&
20274         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20275         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20276          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20277       AsmPieces.clear();
20278       const std::string &ConstraintsStr = IA->getConstraintString();
20279       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20280       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20281       if (clobbersFlagRegisters(AsmPieces))
20282         return IntrinsicLowering::LowerToByteSwap(CI);
20283     }
20284     break;
20285   case 3:
20286     if (CI->getType()->isIntegerTy(32) &&
20287         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20288         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20289         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20290         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20291       AsmPieces.clear();
20292       const std::string &ConstraintsStr = IA->getConstraintString();
20293       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20294       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20295       if (clobbersFlagRegisters(AsmPieces))
20296         return IntrinsicLowering::LowerToByteSwap(CI);
20297     }
20298
20299     if (CI->getType()->isIntegerTy(64)) {
20300       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20301       if (Constraints.size() >= 2 &&
20302           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20303           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20304         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20305         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20306             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20307             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20308           return IntrinsicLowering::LowerToByteSwap(CI);
20309       }
20310     }
20311     break;
20312   }
20313   return false;
20314 }
20315
20316 /// getConstraintType - Given a constraint letter, return the type of
20317 /// constraint it is for this target.
20318 X86TargetLowering::ConstraintType
20319 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20320   if (Constraint.size() == 1) {
20321     switch (Constraint[0]) {
20322     case 'R':
20323     case 'q':
20324     case 'Q':
20325     case 'f':
20326     case 't':
20327     case 'u':
20328     case 'y':
20329     case 'x':
20330     case 'Y':
20331     case 'l':
20332       return C_RegisterClass;
20333     case 'a':
20334     case 'b':
20335     case 'c':
20336     case 'd':
20337     case 'S':
20338     case 'D':
20339     case 'A':
20340       return C_Register;
20341     case 'I':
20342     case 'J':
20343     case 'K':
20344     case 'L':
20345     case 'M':
20346     case 'N':
20347     case 'G':
20348     case 'C':
20349     case 'e':
20350     case 'Z':
20351       return C_Other;
20352     default:
20353       break;
20354     }
20355   }
20356   return TargetLowering::getConstraintType(Constraint);
20357 }
20358
20359 /// Examine constraint type and operand type and determine a weight value.
20360 /// This object must already have been set up with the operand type
20361 /// and the current alternative constraint selected.
20362 TargetLowering::ConstraintWeight
20363   X86TargetLowering::getSingleConstraintMatchWeight(
20364     AsmOperandInfo &info, const char *constraint) const {
20365   ConstraintWeight weight = CW_Invalid;
20366   Value *CallOperandVal = info.CallOperandVal;
20367     // If we don't have a value, we can't do a match,
20368     // but allow it at the lowest weight.
20369   if (!CallOperandVal)
20370     return CW_Default;
20371   Type *type = CallOperandVal->getType();
20372   // Look at the constraint type.
20373   switch (*constraint) {
20374   default:
20375     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20376   case 'R':
20377   case 'q':
20378   case 'Q':
20379   case 'a':
20380   case 'b':
20381   case 'c':
20382   case 'd':
20383   case 'S':
20384   case 'D':
20385   case 'A':
20386     if (CallOperandVal->getType()->isIntegerTy())
20387       weight = CW_SpecificReg;
20388     break;
20389   case 'f':
20390   case 't':
20391   case 'u':
20392     if (type->isFloatingPointTy())
20393       weight = CW_SpecificReg;
20394     break;
20395   case 'y':
20396     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20397       weight = CW_SpecificReg;
20398     break;
20399   case 'x':
20400   case 'Y':
20401     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20402         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20403       weight = CW_Register;
20404     break;
20405   case 'I':
20406     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20407       if (C->getZExtValue() <= 31)
20408         weight = CW_Constant;
20409     }
20410     break;
20411   case 'J':
20412     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20413       if (C->getZExtValue() <= 63)
20414         weight = CW_Constant;
20415     }
20416     break;
20417   case 'K':
20418     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20419       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20420         weight = CW_Constant;
20421     }
20422     break;
20423   case 'L':
20424     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20425       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20426         weight = CW_Constant;
20427     }
20428     break;
20429   case 'M':
20430     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20431       if (C->getZExtValue() <= 3)
20432         weight = CW_Constant;
20433     }
20434     break;
20435   case 'N':
20436     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20437       if (C->getZExtValue() <= 0xff)
20438         weight = CW_Constant;
20439     }
20440     break;
20441   case 'G':
20442   case 'C':
20443     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20444       weight = CW_Constant;
20445     }
20446     break;
20447   case 'e':
20448     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20449       if ((C->getSExtValue() >= -0x80000000LL) &&
20450           (C->getSExtValue() <= 0x7fffffffLL))
20451         weight = CW_Constant;
20452     }
20453     break;
20454   case 'Z':
20455     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20456       if (C->getZExtValue() <= 0xffffffff)
20457         weight = CW_Constant;
20458     }
20459     break;
20460   }
20461   return weight;
20462 }
20463
20464 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20465 /// with another that has more specific requirements based on the type of the
20466 /// corresponding operand.
20467 const char *X86TargetLowering::
20468 LowerXConstraint(EVT ConstraintVT) const {
20469   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20470   // 'f' like normal targets.
20471   if (ConstraintVT.isFloatingPoint()) {
20472     if (Subtarget->hasSSE2())
20473       return "Y";
20474     if (Subtarget->hasSSE1())
20475       return "x";
20476   }
20477
20478   return TargetLowering::LowerXConstraint(ConstraintVT);
20479 }
20480
20481 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20482 /// vector.  If it is invalid, don't add anything to Ops.
20483 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20484                                                      std::string &Constraint,
20485                                                      std::vector<SDValue>&Ops,
20486                                                      SelectionDAG &DAG) const {
20487   SDValue Result;
20488
20489   // Only support length 1 constraints for now.
20490   if (Constraint.length() > 1) return;
20491
20492   char ConstraintLetter = Constraint[0];
20493   switch (ConstraintLetter) {
20494   default: break;
20495   case 'I':
20496     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20497       if (C->getZExtValue() <= 31) {
20498         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20499         break;
20500       }
20501     }
20502     return;
20503   case 'J':
20504     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20505       if (C->getZExtValue() <= 63) {
20506         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20507         break;
20508       }
20509     }
20510     return;
20511   case 'K':
20512     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20513       if (isInt<8>(C->getSExtValue())) {
20514         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20515         break;
20516       }
20517     }
20518     return;
20519   case 'N':
20520     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20521       if (C->getZExtValue() <= 255) {
20522         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20523         break;
20524       }
20525     }
20526     return;
20527   case 'e': {
20528     // 32-bit signed value
20529     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20530       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20531                                            C->getSExtValue())) {
20532         // Widen to 64 bits here to get it sign extended.
20533         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20534         break;
20535       }
20536     // FIXME gcc accepts some relocatable values here too, but only in certain
20537     // memory models; it's complicated.
20538     }
20539     return;
20540   }
20541   case 'Z': {
20542     // 32-bit unsigned value
20543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20544       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20545                                            C->getZExtValue())) {
20546         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20547         break;
20548       }
20549     }
20550     // FIXME gcc accepts some relocatable values here too, but only in certain
20551     // memory models; it's complicated.
20552     return;
20553   }
20554   case 'i': {
20555     // Literal immediates are always ok.
20556     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20557       // Widen to 64 bits here to get it sign extended.
20558       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20559       break;
20560     }
20561
20562     // In any sort of PIC mode addresses need to be computed at runtime by
20563     // adding in a register or some sort of table lookup.  These can't
20564     // be used as immediates.
20565     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20566       return;
20567
20568     // If we are in non-pic codegen mode, we allow the address of a global (with
20569     // an optional displacement) to be used with 'i'.
20570     GlobalAddressSDNode *GA = nullptr;
20571     int64_t Offset = 0;
20572
20573     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20574     while (1) {
20575       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20576         Offset += GA->getOffset();
20577         break;
20578       } else if (Op.getOpcode() == ISD::ADD) {
20579         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20580           Offset += C->getZExtValue();
20581           Op = Op.getOperand(0);
20582           continue;
20583         }
20584       } else if (Op.getOpcode() == ISD::SUB) {
20585         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20586           Offset += -C->getZExtValue();
20587           Op = Op.getOperand(0);
20588           continue;
20589         }
20590       }
20591
20592       // Otherwise, this isn't something we can handle, reject it.
20593       return;
20594     }
20595
20596     const GlobalValue *GV = GA->getGlobal();
20597     // If we require an extra load to get this address, as in PIC mode, we
20598     // can't accept it.
20599     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20600                                                         getTargetMachine())))
20601       return;
20602
20603     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20604                                         GA->getValueType(0), Offset);
20605     break;
20606   }
20607   }
20608
20609   if (Result.getNode()) {
20610     Ops.push_back(Result);
20611     return;
20612   }
20613   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20614 }
20615
20616 std::pair<unsigned, const TargetRegisterClass*>
20617 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20618                                                 MVT VT) const {
20619   // First, see if this is a constraint that directly corresponds to an LLVM
20620   // register class.
20621   if (Constraint.size() == 1) {
20622     // GCC Constraint Letters
20623     switch (Constraint[0]) {
20624     default: break;
20625       // TODO: Slight differences here in allocation order and leaving
20626       // RIP in the class. Do they matter any more here than they do
20627       // in the normal allocation?
20628     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20629       if (Subtarget->is64Bit()) {
20630         if (VT == MVT::i32 || VT == MVT::f32)
20631           return std::make_pair(0U, &X86::GR32RegClass);
20632         if (VT == MVT::i16)
20633           return std::make_pair(0U, &X86::GR16RegClass);
20634         if (VT == MVT::i8 || VT == MVT::i1)
20635           return std::make_pair(0U, &X86::GR8RegClass);
20636         if (VT == MVT::i64 || VT == MVT::f64)
20637           return std::make_pair(0U, &X86::GR64RegClass);
20638         break;
20639       }
20640       // 32-bit fallthrough
20641     case 'Q':   // Q_REGS
20642       if (VT == MVT::i32 || VT == MVT::f32)
20643         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20644       if (VT == MVT::i16)
20645         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20646       if (VT == MVT::i8 || VT == MVT::i1)
20647         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20648       if (VT == MVT::i64)
20649         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20650       break;
20651     case 'r':   // GENERAL_REGS
20652     case 'l':   // INDEX_REGS
20653       if (VT == MVT::i8 || VT == MVT::i1)
20654         return std::make_pair(0U, &X86::GR8RegClass);
20655       if (VT == MVT::i16)
20656         return std::make_pair(0U, &X86::GR16RegClass);
20657       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20658         return std::make_pair(0U, &X86::GR32RegClass);
20659       return std::make_pair(0U, &X86::GR64RegClass);
20660     case 'R':   // LEGACY_REGS
20661       if (VT == MVT::i8 || VT == MVT::i1)
20662         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20663       if (VT == MVT::i16)
20664         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20665       if (VT == MVT::i32 || !Subtarget->is64Bit())
20666         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20667       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20668     case 'f':  // FP Stack registers.
20669       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20670       // value to the correct fpstack register class.
20671       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20672         return std::make_pair(0U, &X86::RFP32RegClass);
20673       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20674         return std::make_pair(0U, &X86::RFP64RegClass);
20675       return std::make_pair(0U, &X86::RFP80RegClass);
20676     case 'y':   // MMX_REGS if MMX allowed.
20677       if (!Subtarget->hasMMX()) break;
20678       return std::make_pair(0U, &X86::VR64RegClass);
20679     case 'Y':   // SSE_REGS if SSE2 allowed
20680       if (!Subtarget->hasSSE2()) break;
20681       // FALL THROUGH.
20682     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20683       if (!Subtarget->hasSSE1()) break;
20684
20685       switch (VT.SimpleTy) {
20686       default: break;
20687       // Scalar SSE types.
20688       case MVT::f32:
20689       case MVT::i32:
20690         return std::make_pair(0U, &X86::FR32RegClass);
20691       case MVT::f64:
20692       case MVT::i64:
20693         return std::make_pair(0U, &X86::FR64RegClass);
20694       // Vector types.
20695       case MVT::v16i8:
20696       case MVT::v8i16:
20697       case MVT::v4i32:
20698       case MVT::v2i64:
20699       case MVT::v4f32:
20700       case MVT::v2f64:
20701         return std::make_pair(0U, &X86::VR128RegClass);
20702       // AVX types.
20703       case MVT::v32i8:
20704       case MVT::v16i16:
20705       case MVT::v8i32:
20706       case MVT::v4i64:
20707       case MVT::v8f32:
20708       case MVT::v4f64:
20709         return std::make_pair(0U, &X86::VR256RegClass);
20710       case MVT::v8f64:
20711       case MVT::v16f32:
20712       case MVT::v16i32:
20713       case MVT::v8i64:
20714         return std::make_pair(0U, &X86::VR512RegClass);
20715       }
20716       break;
20717     }
20718   }
20719
20720   // Use the default implementation in TargetLowering to convert the register
20721   // constraint into a member of a register class.
20722   std::pair<unsigned, const TargetRegisterClass*> Res;
20723   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20724
20725   // Not found as a standard register?
20726   if (!Res.second) {
20727     // Map st(0) -> st(7) -> ST0
20728     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20729         tolower(Constraint[1]) == 's' &&
20730         tolower(Constraint[2]) == 't' &&
20731         Constraint[3] == '(' &&
20732         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20733         Constraint[5] == ')' &&
20734         Constraint[6] == '}') {
20735
20736       Res.first = X86::ST0+Constraint[4]-'0';
20737       Res.second = &X86::RFP80RegClass;
20738       return Res;
20739     }
20740
20741     // GCC allows "st(0)" to be called just plain "st".
20742     if (StringRef("{st}").equals_lower(Constraint)) {
20743       Res.first = X86::ST0;
20744       Res.second = &X86::RFP80RegClass;
20745       return Res;
20746     }
20747
20748     // flags -> EFLAGS
20749     if (StringRef("{flags}").equals_lower(Constraint)) {
20750       Res.first = X86::EFLAGS;
20751       Res.second = &X86::CCRRegClass;
20752       return Res;
20753     }
20754
20755     // 'A' means EAX + EDX.
20756     if (Constraint == "A") {
20757       Res.first = X86::EAX;
20758       Res.second = &X86::GR32_ADRegClass;
20759       return Res;
20760     }
20761     return Res;
20762   }
20763
20764   // Otherwise, check to see if this is a register class of the wrong value
20765   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20766   // turn into {ax},{dx}.
20767   if (Res.second->hasType(VT))
20768     return Res;   // Correct type already, nothing to do.
20769
20770   // All of the single-register GCC register classes map their values onto
20771   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20772   // really want an 8-bit or 32-bit register, map to the appropriate register
20773   // class and return the appropriate register.
20774   if (Res.second == &X86::GR16RegClass) {
20775     if (VT == MVT::i8 || VT == MVT::i1) {
20776       unsigned DestReg = 0;
20777       switch (Res.first) {
20778       default: break;
20779       case X86::AX: DestReg = X86::AL; break;
20780       case X86::DX: DestReg = X86::DL; break;
20781       case X86::CX: DestReg = X86::CL; break;
20782       case X86::BX: DestReg = X86::BL; break;
20783       }
20784       if (DestReg) {
20785         Res.first = DestReg;
20786         Res.second = &X86::GR8RegClass;
20787       }
20788     } else if (VT == MVT::i32 || VT == MVT::f32) {
20789       unsigned DestReg = 0;
20790       switch (Res.first) {
20791       default: break;
20792       case X86::AX: DestReg = X86::EAX; break;
20793       case X86::DX: DestReg = X86::EDX; break;
20794       case X86::CX: DestReg = X86::ECX; break;
20795       case X86::BX: DestReg = X86::EBX; break;
20796       case X86::SI: DestReg = X86::ESI; break;
20797       case X86::DI: DestReg = X86::EDI; break;
20798       case X86::BP: DestReg = X86::EBP; break;
20799       case X86::SP: DestReg = X86::ESP; break;
20800       }
20801       if (DestReg) {
20802         Res.first = DestReg;
20803         Res.second = &X86::GR32RegClass;
20804       }
20805     } else if (VT == MVT::i64 || VT == MVT::f64) {
20806       unsigned DestReg = 0;
20807       switch (Res.first) {
20808       default: break;
20809       case X86::AX: DestReg = X86::RAX; break;
20810       case X86::DX: DestReg = X86::RDX; break;
20811       case X86::CX: DestReg = X86::RCX; break;
20812       case X86::BX: DestReg = X86::RBX; break;
20813       case X86::SI: DestReg = X86::RSI; break;
20814       case X86::DI: DestReg = X86::RDI; break;
20815       case X86::BP: DestReg = X86::RBP; break;
20816       case X86::SP: DestReg = X86::RSP; break;
20817       }
20818       if (DestReg) {
20819         Res.first = DestReg;
20820         Res.second = &X86::GR64RegClass;
20821       }
20822     }
20823   } else if (Res.second == &X86::FR32RegClass ||
20824              Res.second == &X86::FR64RegClass ||
20825              Res.second == &X86::VR128RegClass ||
20826              Res.second == &X86::VR256RegClass ||
20827              Res.second == &X86::FR32XRegClass ||
20828              Res.second == &X86::FR64XRegClass ||
20829              Res.second == &X86::VR128XRegClass ||
20830              Res.second == &X86::VR256XRegClass ||
20831              Res.second == &X86::VR512RegClass) {
20832     // Handle references to XMM physical registers that got mapped into the
20833     // wrong class.  This can happen with constraints like {xmm0} where the
20834     // target independent register mapper will just pick the first match it can
20835     // find, ignoring the required type.
20836
20837     if (VT == MVT::f32 || VT == MVT::i32)
20838       Res.second = &X86::FR32RegClass;
20839     else if (VT == MVT::f64 || VT == MVT::i64)
20840       Res.second = &X86::FR64RegClass;
20841     else if (X86::VR128RegClass.hasType(VT))
20842       Res.second = &X86::VR128RegClass;
20843     else if (X86::VR256RegClass.hasType(VT))
20844       Res.second = &X86::VR256RegClass;
20845     else if (X86::VR512RegClass.hasType(VT))
20846       Res.second = &X86::VR512RegClass;
20847   }
20848
20849   return Res;
20850 }
20851
20852 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20853                                             Type *Ty) const {
20854   // Scaling factors are not free at all.
20855   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20856   // will take 2 allocations instead of 1 for plain addressing mode,
20857   // i.e. inst (reg1).
20858   if (isLegalAddressingMode(AM, Ty))
20859     // Scale represents reg2 * scale, thus account for 1
20860     // as soon as we use a second register.
20861     return AM.Scale != 0;
20862   return -1;
20863 }