X86: Custom lower v4i32 UMUL_LOHI into 2 pmuludqs.
[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::SUB,                MVT::v16i8, Legal);
945     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
947     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
948     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
949     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
954     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
955     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
956
957     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
961
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
963     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
967
968     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
969     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
970       MVT VT = (MVT::SimpleValueType)i;
971       // Do not attempt to custom lower non-power-of-2 vectors
972       if (!isPowerOf2_32(VT.getVectorNumElements()))
973         continue;
974       // Do not attempt to custom lower non-128-bit vectors
975       if (!VT.is128BitVector())
976         continue;
977       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
978       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
979       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
980     }
981
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
983     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
985     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
988
989     if (Subtarget->is64Bit()) {
990       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
991       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
992     }
993
994     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
995     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996       MVT VT = (MVT::SimpleValueType)i;
997
998       // Do not attempt to promote non-128-bit vectors
999       if (!VT.is128BitVector())
1000         continue;
1001
1002       setOperationAction(ISD::AND,    VT, Promote);
1003       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1004       setOperationAction(ISD::OR,     VT, Promote);
1005       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1006       setOperationAction(ISD::XOR,    VT, Promote);
1007       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1008       setOperationAction(ISD::LOAD,   VT, Promote);
1009       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1010       setOperationAction(ISD::SELECT, VT, Promote);
1011       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1012     }
1013
1014     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1015
1016     // Custom lower v2i64 and v2f64 selects.
1017     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1019     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1020     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1021
1022     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1023     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1024
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1026     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1027     // As there is no 64-bit GPR available, we need build a special custom
1028     // sequence to convert from v2i32 to v2f32.
1029     if (!Subtarget->is64Bit())
1030       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1031
1032     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1033     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1034
1035     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1036   }
1037
1038   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1039     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1040     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1041     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1042     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1043     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1047     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1049
1050     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1051     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1052     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1053     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1054     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1055     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1056     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1057     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1058     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1059     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1060
1061     // FIXME: Do we need to handle scalar-to-vector here?
1062     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1063
1064     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1069
1070     // i8 and i16 vectors are custom , because the source register and source
1071     // source memory operand types are not the same width.  f32 vectors are
1072     // custom since the immediate controlling the insert encodes additional
1073     // information.
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1078
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1083
1084     // FIXME: these should be Legal but thats only for the case where
1085     // the index is constant.  For now custom expand to deal with that.
1086     if (Subtarget->is64Bit()) {
1087       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1088       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089     }
1090   }
1091
1092   if (Subtarget->hasSSE2()) {
1093     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1101
1102     // In the customized shift lowering, the legal cases in AVX2 will be
1103     // recognized.
1104     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1105     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1106
1107     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1111
1112     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1113     setOperationAction(ISD::SDIV,              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::SDIV,              MVT::v16i16, Custom);
1179
1180     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1184
1185     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1187     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1193
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1198     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1199     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1200     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1201     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1202     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1203     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1204     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1205     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1206
1207     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1208       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1210       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1212       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1213       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1214     }
1215
1216     if (Subtarget->hasInt256()) {
1217       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1218       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1219       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1220       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1221
1222       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1223       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1224       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1225       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1226
1227       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1228       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1229       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1230       // Don't lower v32i8 because there is no 128-bit byte mul
1231
1232       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1233
1234       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1235
1236       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1237     } else {
1238       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1240       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1241       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1242
1243       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1244       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1245       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1246       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1247
1248       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1249       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1250       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1251       // Don't lower v32i8 because there is no 128-bit byte mul
1252     }
1253
1254     // In the customized shift lowering, the legal cases in AVX2 will be
1255     // recognized.
1256     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1257     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1258
1259     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1261
1262     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1263
1264     // Custom lower several nodes for 256-bit types.
1265     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1266              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1267       MVT VT = (MVT::SimpleValueType)i;
1268
1269       // Extract subvector is special because the value type
1270       // (result) is 128-bit but the source is 256-bit wide.
1271       if (VT.is128BitVector())
1272         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1273
1274       // Do not attempt to custom lower other non-256-bit vectors
1275       if (!VT.is256BitVector())
1276         continue;
1277
1278       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1279       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1280       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1281       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1282       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1283       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1284       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1285     }
1286
1287     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1288     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1289       MVT VT = (MVT::SimpleValueType)i;
1290
1291       // Do not attempt to promote non-256-bit vectors
1292       if (!VT.is256BitVector())
1293         continue;
1294
1295       setOperationAction(ISD::AND,    VT, Promote);
1296       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1297       setOperationAction(ISD::OR,     VT, Promote);
1298       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1299       setOperationAction(ISD::XOR,    VT, Promote);
1300       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1301       setOperationAction(ISD::LOAD,   VT, Promote);
1302       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1303       setOperationAction(ISD::SELECT, VT, Promote);
1304       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1305     }
1306   }
1307
1308   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1309     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1310     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1311     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1312     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1313
1314     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1315     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1316     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1317
1318     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1319     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1320     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1321     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1322     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1323     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1327     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1329
1330     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1333     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1335     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1336
1337     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1338     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1340     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1342     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1343     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1344     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1345     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1346
1347     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1348     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1349     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1350     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1351     if (Subtarget->is64Bit()) {
1352       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1353       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1354       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1355       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1356     }
1357     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1359     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1361     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1363     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1364     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1365     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1366     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1367
1368     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1369     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1370     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1372     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1373     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1374     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1375     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1376     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1377     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1378     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1379     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1380     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1381
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1383     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1388
1389     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1390     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1391
1392     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1393
1394     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1395     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1396     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1397     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1398     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1399     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1400     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1401     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1403
1404     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1405     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1406
1407     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1408     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1409
1410     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1411
1412     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1413     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1414
1415     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1416     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1417
1418     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1419     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1420
1421     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1422     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1423     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1424     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1425     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1426     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1427
1428     // Custom lower several nodes.
1429     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1430              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1431       MVT VT = (MVT::SimpleValueType)i;
1432
1433       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1434       // Extract subvector is special because the value type
1435       // (result) is 256/128-bit but the source is 512-bit wide.
1436       if (VT.is128BitVector() || VT.is256BitVector())
1437         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1438
1439       if (VT.getVectorElementType() == MVT::i1)
1440         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1441
1442       // Do not attempt to custom lower other non-512-bit vectors
1443       if (!VT.is512BitVector())
1444         continue;
1445
1446       if ( EltSize >= 32) {
1447         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1448         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1449         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1450         setOperationAction(ISD::VSELECT,             VT, Legal);
1451         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1452         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1453         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1454       }
1455     }
1456     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1457       MVT VT = (MVT::SimpleValueType)i;
1458
1459       // Do not attempt to promote non-256-bit vectors
1460       if (!VT.is512BitVector())
1461         continue;
1462
1463       setOperationAction(ISD::SELECT, VT, Promote);
1464       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1465     }
1466   }// has  AVX-512
1467
1468   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1469   // of this type with custom code.
1470   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1471            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1472     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1473                        Custom);
1474   }
1475
1476   // We want to custom lower some of our intrinsics.
1477   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1478   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1479   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1480   if (!Subtarget->is64Bit())
1481     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1482
1483   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1484   // handle type legalization for these operations here.
1485   //
1486   // FIXME: We really should do custom legalization for addition and
1487   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1488   // than generic legalization for 64-bit multiplication-with-overflow, though.
1489   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1490     // Add/Sub/Mul with overflow operations are custom lowered.
1491     MVT VT = IntVTs[i];
1492     setOperationAction(ISD::SADDO, VT, Custom);
1493     setOperationAction(ISD::UADDO, VT, Custom);
1494     setOperationAction(ISD::SSUBO, VT, Custom);
1495     setOperationAction(ISD::USUBO, VT, Custom);
1496     setOperationAction(ISD::SMULO, VT, Custom);
1497     setOperationAction(ISD::UMULO, VT, Custom);
1498   }
1499
1500   // There are no 8-bit 3-address imul/mul instructions
1501   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1502   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1503
1504   if (!Subtarget->is64Bit()) {
1505     // These libcalls are not available in 32-bit.
1506     setLibcallName(RTLIB::SHL_I128, nullptr);
1507     setLibcallName(RTLIB::SRL_I128, nullptr);
1508     setLibcallName(RTLIB::SRA_I128, nullptr);
1509   }
1510
1511   // Combine sin / cos into one node or libcall if possible.
1512   if (Subtarget->hasSinCos()) {
1513     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1514     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1515     if (Subtarget->isTargetDarwin()) {
1516       // For MacOSX, we don't want to the normal expansion of a libcall to
1517       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1518       // traffic.
1519       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1520       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1521     }
1522   }
1523
1524   // We have target-specific dag combine patterns for the following nodes:
1525   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1526   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1527   setTargetDAGCombine(ISD::VSELECT);
1528   setTargetDAGCombine(ISD::SELECT);
1529   setTargetDAGCombine(ISD::SHL);
1530   setTargetDAGCombine(ISD::SRA);
1531   setTargetDAGCombine(ISD::SRL);
1532   setTargetDAGCombine(ISD::OR);
1533   setTargetDAGCombine(ISD::AND);
1534   setTargetDAGCombine(ISD::ADD);
1535   setTargetDAGCombine(ISD::FADD);
1536   setTargetDAGCombine(ISD::FSUB);
1537   setTargetDAGCombine(ISD::FMA);
1538   setTargetDAGCombine(ISD::SUB);
1539   setTargetDAGCombine(ISD::LOAD);
1540   setTargetDAGCombine(ISD::STORE);
1541   setTargetDAGCombine(ISD::ZERO_EXTEND);
1542   setTargetDAGCombine(ISD::ANY_EXTEND);
1543   setTargetDAGCombine(ISD::SIGN_EXTEND);
1544   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1545   setTargetDAGCombine(ISD::TRUNCATE);
1546   setTargetDAGCombine(ISD::SINT_TO_FP);
1547   setTargetDAGCombine(ISD::SETCC);
1548   if (Subtarget->is64Bit())
1549     setTargetDAGCombine(ISD::MUL);
1550   setTargetDAGCombine(ISD::XOR);
1551
1552   computeRegisterProperties();
1553
1554   // On Darwin, -Os means optimize for size without hurting performance,
1555   // do not reduce the limit.
1556   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1557   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1558   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1559   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1560   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1561   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1562   setPrefLoopAlignment(4); // 2^4 bytes.
1563
1564   // Predictable cmov don't hurt on atom because it's in-order.
1565   PredictableSelectIsExpensive = !Subtarget->isAtom();
1566
1567   setPrefFunctionAlignment(4); // 2^4 bytes.
1568 }
1569
1570 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1571   if (!VT.isVector())
1572     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1573
1574   if (Subtarget->hasAVX512())
1575     switch(VT.getVectorNumElements()) {
1576     case  8: return MVT::v8i1;
1577     case 16: return MVT::v16i1;
1578   }
1579
1580   return VT.changeVectorElementTypeToInteger();
1581 }
1582
1583 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1584 /// the desired ByVal argument alignment.
1585 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1586   if (MaxAlign == 16)
1587     return;
1588   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1589     if (VTy->getBitWidth() == 128)
1590       MaxAlign = 16;
1591   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1592     unsigned EltAlign = 0;
1593     getMaxByValAlign(ATy->getElementType(), EltAlign);
1594     if (EltAlign > MaxAlign)
1595       MaxAlign = EltAlign;
1596   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1597     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1598       unsigned EltAlign = 0;
1599       getMaxByValAlign(STy->getElementType(i), EltAlign);
1600       if (EltAlign > MaxAlign)
1601         MaxAlign = EltAlign;
1602       if (MaxAlign == 16)
1603         break;
1604     }
1605   }
1606 }
1607
1608 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1609 /// function arguments in the caller parameter area. For X86, aggregates
1610 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1611 /// are at 4-byte boundaries.
1612 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1613   if (Subtarget->is64Bit()) {
1614     // Max of 8 and alignment of type.
1615     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1616     if (TyAlign > 8)
1617       return TyAlign;
1618     return 8;
1619   }
1620
1621   unsigned Align = 4;
1622   if (Subtarget->hasSSE1())
1623     getMaxByValAlign(Ty, Align);
1624   return Align;
1625 }
1626
1627 /// getOptimalMemOpType - Returns the target specific optimal type for load
1628 /// and store operations as a result of memset, memcpy, and memmove
1629 /// lowering. If DstAlign is zero that means it's safe to destination
1630 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1631 /// means there isn't a need to check it against alignment requirement,
1632 /// probably because the source does not need to be loaded. If 'IsMemset' is
1633 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1634 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1635 /// source is constant so it does not need to be loaded.
1636 /// It returns EVT::Other if the type should be determined using generic
1637 /// target-independent logic.
1638 EVT
1639 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1640                                        unsigned DstAlign, unsigned SrcAlign,
1641                                        bool IsMemset, bool ZeroMemset,
1642                                        bool MemcpyStrSrc,
1643                                        MachineFunction &MF) const {
1644   const Function *F = MF.getFunction();
1645   if ((!IsMemset || ZeroMemset) &&
1646       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1647                                        Attribute::NoImplicitFloat)) {
1648     if (Size >= 16 &&
1649         (Subtarget->isUnalignedMemAccessFast() ||
1650          ((DstAlign == 0 || DstAlign >= 16) &&
1651           (SrcAlign == 0 || SrcAlign >= 16)))) {
1652       if (Size >= 32) {
1653         if (Subtarget->hasInt256())
1654           return MVT::v8i32;
1655         if (Subtarget->hasFp256())
1656           return MVT::v8f32;
1657       }
1658       if (Subtarget->hasSSE2())
1659         return MVT::v4i32;
1660       if (Subtarget->hasSSE1())
1661         return MVT::v4f32;
1662     } else if (!MemcpyStrSrc && Size >= 8 &&
1663                !Subtarget->is64Bit() &&
1664                Subtarget->hasSSE2()) {
1665       // Do not use f64 to lower memcpy if source is string constant. It's
1666       // better to use i32 to avoid the loads.
1667       return MVT::f64;
1668     }
1669   }
1670   if (Subtarget->is64Bit() && Size >= 8)
1671     return MVT::i64;
1672   return MVT::i32;
1673 }
1674
1675 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1676   if (VT == MVT::f32)
1677     return X86ScalarSSEf32;
1678   else if (VT == MVT::f64)
1679     return X86ScalarSSEf64;
1680   return true;
1681 }
1682
1683 bool
1684 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1685                                                  unsigned,
1686                                                  bool *Fast) const {
1687   if (Fast)
1688     *Fast = Subtarget->isUnalignedMemAccessFast();
1689   return true;
1690 }
1691
1692 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1693 /// current function.  The returned value is a member of the
1694 /// MachineJumpTableInfo::JTEntryKind enum.
1695 unsigned X86TargetLowering::getJumpTableEncoding() const {
1696   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1697   // symbol.
1698   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1699       Subtarget->isPICStyleGOT())
1700     return MachineJumpTableInfo::EK_Custom32;
1701
1702   // Otherwise, use the normal jump table encoding heuristics.
1703   return TargetLowering::getJumpTableEncoding();
1704 }
1705
1706 const MCExpr *
1707 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1708                                              const MachineBasicBlock *MBB,
1709                                              unsigned uid,MCContext &Ctx) const{
1710   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1711          Subtarget->isPICStyleGOT());
1712   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1713   // entries.
1714   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1715                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1716 }
1717
1718 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1719 /// jumptable.
1720 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1721                                                     SelectionDAG &DAG) const {
1722   if (!Subtarget->is64Bit())
1723     // This doesn't have SDLoc associated with it, but is not really the
1724     // same as a Register.
1725     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1726   return Table;
1727 }
1728
1729 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1730 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1731 /// MCExpr.
1732 const MCExpr *X86TargetLowering::
1733 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1734                              MCContext &Ctx) const {
1735   // X86-64 uses RIP relative addressing based on the jump table label.
1736   if (Subtarget->isPICStyleRIPRel())
1737     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1738
1739   // Otherwise, the reference is relative to the PIC base.
1740   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1741 }
1742
1743 // FIXME: Why this routine is here? Move to RegInfo!
1744 std::pair<const TargetRegisterClass*, uint8_t>
1745 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1746   const TargetRegisterClass *RRC = nullptr;
1747   uint8_t Cost = 1;
1748   switch (VT.SimpleTy) {
1749   default:
1750     return TargetLowering::findRepresentativeClass(VT);
1751   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1752     RRC = Subtarget->is64Bit() ?
1753       (const TargetRegisterClass*)&X86::GR64RegClass :
1754       (const TargetRegisterClass*)&X86::GR32RegClass;
1755     break;
1756   case MVT::x86mmx:
1757     RRC = &X86::VR64RegClass;
1758     break;
1759   case MVT::f32: case MVT::f64:
1760   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1761   case MVT::v4f32: case MVT::v2f64:
1762   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1763   case MVT::v4f64:
1764     RRC = &X86::VR128RegClass;
1765     break;
1766   }
1767   return std::make_pair(RRC, Cost);
1768 }
1769
1770 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1771                                                unsigned &Offset) const {
1772   if (!Subtarget->isTargetLinux())
1773     return false;
1774
1775   if (Subtarget->is64Bit()) {
1776     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1777     Offset = 0x28;
1778     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1779       AddressSpace = 256;
1780     else
1781       AddressSpace = 257;
1782   } else {
1783     // %gs:0x14 on i386
1784     Offset = 0x14;
1785     AddressSpace = 256;
1786   }
1787   return true;
1788 }
1789
1790 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1791                                             unsigned DestAS) const {
1792   assert(SrcAS != DestAS && "Expected different address spaces!");
1793
1794   return SrcAS < 256 && DestAS < 256;
1795 }
1796
1797 //===----------------------------------------------------------------------===//
1798 //               Return Value Calling Convention Implementation
1799 //===----------------------------------------------------------------------===//
1800
1801 #include "X86GenCallingConv.inc"
1802
1803 bool
1804 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1805                                   MachineFunction &MF, bool isVarArg,
1806                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1807                         LLVMContext &Context) const {
1808   SmallVector<CCValAssign, 16> RVLocs;
1809   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1810                  RVLocs, Context);
1811   return CCInfo.CheckReturn(Outs, RetCC_X86);
1812 }
1813
1814 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1815   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1816   return ScratchRegs;
1817 }
1818
1819 SDValue
1820 X86TargetLowering::LowerReturn(SDValue Chain,
1821                                CallingConv::ID CallConv, bool isVarArg,
1822                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1823                                const SmallVectorImpl<SDValue> &OutVals,
1824                                SDLoc dl, SelectionDAG &DAG) const {
1825   MachineFunction &MF = DAG.getMachineFunction();
1826   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1827
1828   SmallVector<CCValAssign, 16> RVLocs;
1829   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1830                  RVLocs, *DAG.getContext());
1831   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1832
1833   SDValue Flag;
1834   SmallVector<SDValue, 6> RetOps;
1835   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1836   // Operand #1 = Bytes To Pop
1837   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1838                    MVT::i16));
1839
1840   // Copy the result values into the output registers.
1841   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1842     CCValAssign &VA = RVLocs[i];
1843     assert(VA.isRegLoc() && "Can only return in registers!");
1844     SDValue ValToCopy = OutVals[i];
1845     EVT ValVT = ValToCopy.getValueType();
1846
1847     // Promote values to the appropriate types
1848     if (VA.getLocInfo() == CCValAssign::SExt)
1849       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1850     else if (VA.getLocInfo() == CCValAssign::ZExt)
1851       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1852     else if (VA.getLocInfo() == CCValAssign::AExt)
1853       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1854     else if (VA.getLocInfo() == CCValAssign::BCvt)
1855       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1856
1857     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1858            "Unexpected FP-extend for return value.");  
1859
1860     // If this is x86-64, and we disabled SSE, we can't return FP values,
1861     // or SSE or MMX vectors.
1862     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1863          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1864           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1865       report_fatal_error("SSE register return with SSE disabled");
1866     }
1867     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1868     // llvm-gcc has never done it right and no one has noticed, so this
1869     // should be OK for now.
1870     if (ValVT == MVT::f64 &&
1871         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1872       report_fatal_error("SSE2 register return with SSE2 disabled");
1873
1874     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1875     // the RET instruction and handled by the FP Stackifier.
1876     if (VA.getLocReg() == X86::ST0 ||
1877         VA.getLocReg() == X86::ST1) {
1878       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1879       // change the value to the FP stack register class.
1880       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1881         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1882       RetOps.push_back(ValToCopy);
1883       // Don't emit a copytoreg.
1884       continue;
1885     }
1886
1887     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1888     // which is returned in RAX / RDX.
1889     if (Subtarget->is64Bit()) {
1890       if (ValVT == MVT::x86mmx) {
1891         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1892           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1893           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1894                                   ValToCopy);
1895           // If we don't have SSE2 available, convert to v4f32 so the generated
1896           // register is legal.
1897           if (!Subtarget->hasSSE2())
1898             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1899         }
1900       }
1901     }
1902
1903     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1904     Flag = Chain.getValue(1);
1905     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1906   }
1907
1908   // The x86-64 ABIs require that for returning structs by value we copy
1909   // the sret argument into %rax/%eax (depending on ABI) for the return.
1910   // Win32 requires us to put the sret argument to %eax as well.
1911   // We saved the argument into a virtual register in the entry block,
1912   // so now we copy the value out and into %rax/%eax.
1913   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1914       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1915     MachineFunction &MF = DAG.getMachineFunction();
1916     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1917     unsigned Reg = FuncInfo->getSRetReturnReg();
1918     assert(Reg &&
1919            "SRetReturnReg should have been set in LowerFormalArguments().");
1920     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1921
1922     unsigned RetValReg
1923         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1924           X86::RAX : X86::EAX;
1925     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1926     Flag = Chain.getValue(1);
1927
1928     // RAX/EAX now acts like a return value.
1929     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1930   }
1931
1932   RetOps[0] = Chain;  // Update chain.
1933
1934   // Add the flag if we have it.
1935   if (Flag.getNode())
1936     RetOps.push_back(Flag);
1937
1938   return DAG.getNode(X86ISD::RET_FLAG, dl,
1939                      MVT::Other, &RetOps[0], RetOps.size());
1940 }
1941
1942 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1943   if (N->getNumValues() != 1)
1944     return false;
1945   if (!N->hasNUsesOfValue(1, 0))
1946     return false;
1947
1948   SDValue TCChain = Chain;
1949   SDNode *Copy = *N->use_begin();
1950   if (Copy->getOpcode() == ISD::CopyToReg) {
1951     // If the copy has a glue operand, we conservatively assume it isn't safe to
1952     // perform a tail call.
1953     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1954       return false;
1955     TCChain = Copy->getOperand(0);
1956   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1957     return false;
1958
1959   bool HasRet = false;
1960   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1961        UI != UE; ++UI) {
1962     if (UI->getOpcode() != X86ISD::RET_FLAG)
1963       return false;
1964     HasRet = true;
1965   }
1966
1967   if (!HasRet)
1968     return false;
1969
1970   Chain = TCChain;
1971   return true;
1972 }
1973
1974 MVT
1975 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1976                                             ISD::NodeType ExtendKind) const {
1977   MVT ReturnMVT;
1978   // TODO: Is this also valid on 32-bit?
1979   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1980     ReturnMVT = MVT::i8;
1981   else
1982     ReturnMVT = MVT::i32;
1983
1984   MVT MinVT = getRegisterType(ReturnMVT);
1985   return VT.bitsLT(MinVT) ? MinVT : VT;
1986 }
1987
1988 /// LowerCallResult - Lower the result values of a call into the
1989 /// appropriate copies out of appropriate physical registers.
1990 ///
1991 SDValue
1992 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1993                                    CallingConv::ID CallConv, bool isVarArg,
1994                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1995                                    SDLoc dl, SelectionDAG &DAG,
1996                                    SmallVectorImpl<SDValue> &InVals) const {
1997
1998   // Assign locations to each value returned by this call.
1999   SmallVector<CCValAssign, 16> RVLocs;
2000   bool Is64Bit = Subtarget->is64Bit();
2001   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2002                  getTargetMachine(), RVLocs, *DAG.getContext());
2003   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2004
2005   // Copy all of the result registers out of their specified physreg.
2006   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2007     CCValAssign &VA = RVLocs[i];
2008     EVT CopyVT = VA.getValVT();
2009
2010     // If this is x86-64, and we disabled SSE, we can't return FP values
2011     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2012         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2013       report_fatal_error("SSE register return with SSE disabled");
2014     }
2015
2016     SDValue Val;
2017
2018     // If this is a call to a function that returns an fp value on the floating
2019     // point stack, we must guarantee the value is popped from the stack, so
2020     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2021     // if the return value is not used. We use the FpPOP_RETVAL instruction
2022     // instead.
2023     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2024       // If we prefer to use the value in xmm registers, copy it out as f80 and
2025       // use a truncate to move it from fp stack reg to xmm reg.
2026       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2027       SDValue Ops[] = { Chain, InFlag };
2028       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2029                                          MVT::Other, MVT::Glue, Ops), 1);
2030       Val = Chain.getValue(0);
2031
2032       // Round the f80 to the right size, which also moves it to the appropriate
2033       // xmm register.
2034       if (CopyVT != VA.getValVT())
2035         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2036                           // This truncation won't change the value.
2037                           DAG.getIntPtrConstant(1));
2038     } else {
2039       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2040                                  CopyVT, InFlag).getValue(1);
2041       Val = Chain.getValue(0);
2042     }
2043     InFlag = Chain.getValue(2);
2044     InVals.push_back(Val);
2045   }
2046
2047   return Chain;
2048 }
2049
2050 //===----------------------------------------------------------------------===//
2051 //                C & StdCall & Fast Calling Convention implementation
2052 //===----------------------------------------------------------------------===//
2053 //  StdCall calling convention seems to be standard for many Windows' API
2054 //  routines and around. It differs from C calling convention just a little:
2055 //  callee should clean up the stack, not caller. Symbols should be also
2056 //  decorated in some fancy way :) It doesn't support any vector arguments.
2057 //  For info on fast calling convention see Fast Calling Convention (tail call)
2058 //  implementation LowerX86_32FastCCCallTo.
2059
2060 /// CallIsStructReturn - Determines whether a call uses struct return
2061 /// semantics.
2062 enum StructReturnType {
2063   NotStructReturn,
2064   RegStructReturn,
2065   StackStructReturn
2066 };
2067 static StructReturnType
2068 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2069   if (Outs.empty())
2070     return NotStructReturn;
2071
2072   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2073   if (!Flags.isSRet())
2074     return NotStructReturn;
2075   if (Flags.isInReg())
2076     return RegStructReturn;
2077   return StackStructReturn;
2078 }
2079
2080 /// ArgsAreStructReturn - Determines whether a function uses struct
2081 /// return semantics.
2082 static StructReturnType
2083 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2084   if (Ins.empty())
2085     return NotStructReturn;
2086
2087   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2088   if (!Flags.isSRet())
2089     return NotStructReturn;
2090   if (Flags.isInReg())
2091     return RegStructReturn;
2092   return StackStructReturn;
2093 }
2094
2095 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2096 /// by "Src" to address "Dst" with size and alignment information specified by
2097 /// the specific parameter attribute. The copy will be passed as a byval
2098 /// function parameter.
2099 static SDValue
2100 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2101                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2102                           SDLoc dl) {
2103   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2104
2105   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2106                        /*isVolatile*/false, /*AlwaysInline=*/true,
2107                        MachinePointerInfo(), MachinePointerInfo());
2108 }
2109
2110 /// IsTailCallConvention - Return true if the calling convention is one that
2111 /// supports tail call optimization.
2112 static bool IsTailCallConvention(CallingConv::ID CC) {
2113   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2114           CC == CallingConv::HiPE);
2115 }
2116
2117 /// \brief Return true if the calling convention is a C calling convention.
2118 static bool IsCCallConvention(CallingConv::ID CC) {
2119   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2120           CC == CallingConv::X86_64_SysV);
2121 }
2122
2123 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2124   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2125     return false;
2126
2127   CallSite CS(CI);
2128   CallingConv::ID CalleeCC = CS.getCallingConv();
2129   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2130     return false;
2131
2132   return true;
2133 }
2134
2135 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2136 /// a tailcall target by changing its ABI.
2137 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2138                                    bool GuaranteedTailCallOpt) {
2139   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2140 }
2141
2142 SDValue
2143 X86TargetLowering::LowerMemArgument(SDValue Chain,
2144                                     CallingConv::ID CallConv,
2145                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2146                                     SDLoc dl, SelectionDAG &DAG,
2147                                     const CCValAssign &VA,
2148                                     MachineFrameInfo *MFI,
2149                                     unsigned i) const {
2150   // Create the nodes corresponding to a load from this parameter slot.
2151   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2152   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2153                               getTargetMachine().Options.GuaranteedTailCallOpt);
2154   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2155   EVT ValVT;
2156
2157   // If value is passed by pointer we have address passed instead of the value
2158   // itself.
2159   if (VA.getLocInfo() == CCValAssign::Indirect)
2160     ValVT = VA.getLocVT();
2161   else
2162     ValVT = VA.getValVT();
2163
2164   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2165   // changed with more analysis.
2166   // In case of tail call optimization mark all arguments mutable. Since they
2167   // could be overwritten by lowering of arguments in case of a tail call.
2168   if (Flags.isByVal()) {
2169     unsigned Bytes = Flags.getByValSize();
2170     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2171     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2172     return DAG.getFrameIndex(FI, getPointerTy());
2173   } else {
2174     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2175                                     VA.getLocMemOffset(), isImmutable);
2176     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2177     return DAG.getLoad(ValVT, dl, Chain, FIN,
2178                        MachinePointerInfo::getFixedStack(FI),
2179                        false, false, false, 0);
2180   }
2181 }
2182
2183 SDValue
2184 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2185                                         CallingConv::ID CallConv,
2186                                         bool isVarArg,
2187                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2188                                         SDLoc dl,
2189                                         SelectionDAG &DAG,
2190                                         SmallVectorImpl<SDValue> &InVals)
2191                                           const {
2192   MachineFunction &MF = DAG.getMachineFunction();
2193   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2194
2195   const Function* Fn = MF.getFunction();
2196   if (Fn->hasExternalLinkage() &&
2197       Subtarget->isTargetCygMing() &&
2198       Fn->getName() == "main")
2199     FuncInfo->setForceFramePointer(true);
2200
2201   MachineFrameInfo *MFI = MF.getFrameInfo();
2202   bool Is64Bit = Subtarget->is64Bit();
2203   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2204
2205   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2206          "Var args not supported with calling convention fastcc, ghc or hipe");
2207
2208   // Assign locations to all of the incoming arguments.
2209   SmallVector<CCValAssign, 16> ArgLocs;
2210   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2211                  ArgLocs, *DAG.getContext());
2212
2213   // Allocate shadow area for Win64
2214   if (IsWin64)
2215     CCInfo.AllocateStack(32, 8);
2216
2217   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2218
2219   unsigned LastVal = ~0U;
2220   SDValue ArgValue;
2221   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2222     CCValAssign &VA = ArgLocs[i];
2223     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2224     // places.
2225     assert(VA.getValNo() != LastVal &&
2226            "Don't support value assigned to multiple locs yet");
2227     (void)LastVal;
2228     LastVal = VA.getValNo();
2229
2230     if (VA.isRegLoc()) {
2231       EVT RegVT = VA.getLocVT();
2232       const TargetRegisterClass *RC;
2233       if (RegVT == MVT::i32)
2234         RC = &X86::GR32RegClass;
2235       else if (Is64Bit && RegVT == MVT::i64)
2236         RC = &X86::GR64RegClass;
2237       else if (RegVT == MVT::f32)
2238         RC = &X86::FR32RegClass;
2239       else if (RegVT == MVT::f64)
2240         RC = &X86::FR64RegClass;
2241       else if (RegVT.is512BitVector())
2242         RC = &X86::VR512RegClass;
2243       else if (RegVT.is256BitVector())
2244         RC = &X86::VR256RegClass;
2245       else if (RegVT.is128BitVector())
2246         RC = &X86::VR128RegClass;
2247       else if (RegVT == MVT::x86mmx)
2248         RC = &X86::VR64RegClass;
2249       else if (RegVT == MVT::i1)
2250         RC = &X86::VK1RegClass;
2251       else if (RegVT == MVT::v8i1)
2252         RC = &X86::VK8RegClass;
2253       else if (RegVT == MVT::v16i1)
2254         RC = &X86::VK16RegClass;
2255       else
2256         llvm_unreachable("Unknown argument type!");
2257
2258       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2259       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2260
2261       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2262       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2263       // right size.
2264       if (VA.getLocInfo() == CCValAssign::SExt)
2265         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2266                                DAG.getValueType(VA.getValVT()));
2267       else if (VA.getLocInfo() == CCValAssign::ZExt)
2268         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2269                                DAG.getValueType(VA.getValVT()));
2270       else if (VA.getLocInfo() == CCValAssign::BCvt)
2271         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2272
2273       if (VA.isExtInLoc()) {
2274         // Handle MMX values passed in XMM regs.
2275         if (RegVT.isVector())
2276           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2277         else
2278           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2279       }
2280     } else {
2281       assert(VA.isMemLoc());
2282       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2283     }
2284
2285     // If value is passed via pointer - do a load.
2286     if (VA.getLocInfo() == CCValAssign::Indirect)
2287       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2288                              MachinePointerInfo(), false, false, false, 0);
2289
2290     InVals.push_back(ArgValue);
2291   }
2292
2293   // The x86-64 ABIs require that for returning structs by value we copy
2294   // the sret argument into %rax/%eax (depending on ABI) for the return.
2295   // Win32 requires us to put the sret argument to %eax as well.
2296   // Save the argument into a virtual register so that we can access it
2297   // from the return points.
2298   if (MF.getFunction()->hasStructRetAttr() &&
2299       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2300     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2301     unsigned Reg = FuncInfo->getSRetReturnReg();
2302     if (!Reg) {
2303       MVT PtrTy = getPointerTy();
2304       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2305       FuncInfo->setSRetReturnReg(Reg);
2306     }
2307     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2308     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2309   }
2310
2311   unsigned StackSize = CCInfo.getNextStackOffset();
2312   // Align stack specially for tail calls.
2313   if (FuncIsMadeTailCallSafe(CallConv,
2314                              MF.getTarget().Options.GuaranteedTailCallOpt))
2315     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2316
2317   // If the function takes variable number of arguments, make a frame index for
2318   // the start of the first vararg value... for expansion of llvm.va_start.
2319   if (isVarArg) {
2320     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2321                     CallConv != CallingConv::X86_ThisCall)) {
2322       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2323     }
2324     if (Is64Bit) {
2325       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2326
2327       // FIXME: We should really autogenerate these arrays
2328       static const MCPhysReg GPR64ArgRegsWin64[] = {
2329         X86::RCX, X86::RDX, X86::R8,  X86::R9
2330       };
2331       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2332         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2333       };
2334       static const MCPhysReg XMMArgRegs64Bit[] = {
2335         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2336         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2337       };
2338       const MCPhysReg *GPR64ArgRegs;
2339       unsigned NumXMMRegs = 0;
2340
2341       if (IsWin64) {
2342         // The XMM registers which might contain var arg parameters are shadowed
2343         // in their paired GPR.  So we only need to save the GPR to their home
2344         // slots.
2345         TotalNumIntRegs = 4;
2346         GPR64ArgRegs = GPR64ArgRegsWin64;
2347       } else {
2348         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2349         GPR64ArgRegs = GPR64ArgRegs64Bit;
2350
2351         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2352                                                 TotalNumXMMRegs);
2353       }
2354       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2355                                                        TotalNumIntRegs);
2356
2357       bool NoImplicitFloatOps = Fn->getAttributes().
2358         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2359       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2360              "SSE register cannot be used when SSE is disabled!");
2361       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2362                NoImplicitFloatOps) &&
2363              "SSE register cannot be used when SSE is disabled!");
2364       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2365           !Subtarget->hasSSE1())
2366         // Kernel mode asks for SSE to be disabled, so don't push them
2367         // on the stack.
2368         TotalNumXMMRegs = 0;
2369
2370       if (IsWin64) {
2371         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2372         // Get to the caller-allocated home save location.  Add 8 to account
2373         // for the return address.
2374         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2375         FuncInfo->setRegSaveFrameIndex(
2376           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2377         // Fixup to set vararg frame on shadow area (4 x i64).
2378         if (NumIntRegs < 4)
2379           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2380       } else {
2381         // For X86-64, if there are vararg parameters that are passed via
2382         // registers, then we must store them to their spots on the stack so
2383         // they may be loaded by deferencing the result of va_next.
2384         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2385         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2386         FuncInfo->setRegSaveFrameIndex(
2387           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2388                                false));
2389       }
2390
2391       // Store the integer parameter registers.
2392       SmallVector<SDValue, 8> MemOps;
2393       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2394                                         getPointerTy());
2395       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2396       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2397         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2398                                   DAG.getIntPtrConstant(Offset));
2399         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2400                                      &X86::GR64RegClass);
2401         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2402         SDValue Store =
2403           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2404                        MachinePointerInfo::getFixedStack(
2405                          FuncInfo->getRegSaveFrameIndex(), Offset),
2406                        false, false, 0);
2407         MemOps.push_back(Store);
2408         Offset += 8;
2409       }
2410
2411       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2412         // Now store the XMM (fp + vector) parameter registers.
2413         SmallVector<SDValue, 11> SaveXMMOps;
2414         SaveXMMOps.push_back(Chain);
2415
2416         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2417         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2418         SaveXMMOps.push_back(ALVal);
2419
2420         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421                                FuncInfo->getRegSaveFrameIndex()));
2422         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2423                                FuncInfo->getVarArgsFPOffset()));
2424
2425         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2426           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2427                                        &X86::VR128RegClass);
2428           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2429           SaveXMMOps.push_back(Val);
2430         }
2431         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2432                                      MVT::Other,
2433                                      &SaveXMMOps[0], SaveXMMOps.size()));
2434       }
2435
2436       if (!MemOps.empty())
2437         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2438                             &MemOps[0], MemOps.size());
2439     }
2440   }
2441
2442   // Some CCs need callee pop.
2443   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2444                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2445     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2446   } else {
2447     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2448     // If this is an sret function, the return should pop the hidden pointer.
2449     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2450         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2451         argsAreStructReturn(Ins) == StackStructReturn)
2452       FuncInfo->setBytesToPopOnReturn(4);
2453   }
2454
2455   if (!Is64Bit) {
2456     // RegSaveFrameIndex is X86-64 only.
2457     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2458     if (CallConv == CallingConv::X86_FastCall ||
2459         CallConv == CallingConv::X86_ThisCall)
2460       // fastcc functions can't have varargs.
2461       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2462   }
2463
2464   FuncInfo->setArgumentStackSize(StackSize);
2465
2466   return Chain;
2467 }
2468
2469 SDValue
2470 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2471                                     SDValue StackPtr, SDValue Arg,
2472                                     SDLoc dl, SelectionDAG &DAG,
2473                                     const CCValAssign &VA,
2474                                     ISD::ArgFlagsTy Flags) const {
2475   unsigned LocMemOffset = VA.getLocMemOffset();
2476   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2477   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2478   if (Flags.isByVal())
2479     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2480
2481   return DAG.getStore(Chain, dl, Arg, PtrOff,
2482                       MachinePointerInfo::getStack(LocMemOffset),
2483                       false, false, 0);
2484 }
2485
2486 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2487 /// optimization is performed and it is required.
2488 SDValue
2489 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2490                                            SDValue &OutRetAddr, SDValue Chain,
2491                                            bool IsTailCall, bool Is64Bit,
2492                                            int FPDiff, SDLoc dl) const {
2493   // Adjust the Return address stack slot.
2494   EVT VT = getPointerTy();
2495   OutRetAddr = getReturnAddressFrameIndex(DAG);
2496
2497   // Load the "old" Return address.
2498   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2499                            false, false, false, 0);
2500   return SDValue(OutRetAddr.getNode(), 1);
2501 }
2502
2503 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2504 /// optimization is performed and it is required (FPDiff!=0).
2505 static SDValue
2506 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2507                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2508                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2509   // Store the return address to the appropriate stack slot.
2510   if (!FPDiff) return Chain;
2511   // Calculate the new stack slot for the return address.
2512   int NewReturnAddrFI =
2513     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2514                                          false);
2515   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2516   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2517                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2518                        false, false, 0);
2519   return Chain;
2520 }
2521
2522 SDValue
2523 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2524                              SmallVectorImpl<SDValue> &InVals) const {
2525   SelectionDAG &DAG                     = CLI.DAG;
2526   SDLoc &dl                             = CLI.DL;
2527   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2528   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2529   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2530   SDValue Chain                         = CLI.Chain;
2531   SDValue Callee                        = CLI.Callee;
2532   CallingConv::ID CallConv              = CLI.CallConv;
2533   bool &isTailCall                      = CLI.IsTailCall;
2534   bool isVarArg                         = CLI.IsVarArg;
2535
2536   MachineFunction &MF = DAG.getMachineFunction();
2537   bool Is64Bit        = Subtarget->is64Bit();
2538   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2539   StructReturnType SR = callIsStructReturn(Outs);
2540   bool IsSibcall      = false;
2541
2542   if (MF.getTarget().Options.DisableTailCalls)
2543     isTailCall = false;
2544
2545   if (isTailCall) {
2546     // Check if it's really possible to do a tail call.
2547     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2548                     isVarArg, SR != NotStructReturn,
2549                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2550                     Outs, OutVals, Ins, DAG);
2551
2552     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2553       report_fatal_error("failed to perform tail call elimination on a call "
2554                          "site marked musttail");
2555
2556     // Sibcalls are automatically detected tailcalls which do not require
2557     // ABI changes.
2558     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2559       IsSibcall = true;
2560
2561     if (isTailCall)
2562       ++NumTailCalls;
2563   }
2564
2565   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2566          "Var args not supported with calling convention fastcc, ghc or hipe");
2567
2568   // Analyze operands of the call, assigning locations to each operand.
2569   SmallVector<CCValAssign, 16> ArgLocs;
2570   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2571                  ArgLocs, *DAG.getContext());
2572
2573   // Allocate shadow area for Win64
2574   if (IsWin64)
2575     CCInfo.AllocateStack(32, 8);
2576
2577   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2578
2579   // Get a count of how many bytes are to be pushed on the stack.
2580   unsigned NumBytes = CCInfo.getNextStackOffset();
2581   if (IsSibcall)
2582     // This is a sibcall. The memory operands are available in caller's
2583     // own caller's stack.
2584     NumBytes = 0;
2585   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2586            IsTailCallConvention(CallConv))
2587     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2588
2589   int FPDiff = 0;
2590   if (isTailCall && !IsSibcall) {
2591     // Lower arguments at fp - stackoffset + fpdiff.
2592     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2593     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2594
2595     FPDiff = NumBytesCallerPushed - NumBytes;
2596
2597     // Set the delta of movement of the returnaddr stackslot.
2598     // But only set if delta is greater than previous delta.
2599     if (FPDiff < X86Info->getTCReturnAddrDelta())
2600       X86Info->setTCReturnAddrDelta(FPDiff);
2601   }
2602
2603   unsigned NumBytesToPush = NumBytes;
2604   unsigned NumBytesToPop = NumBytes;
2605
2606   // If we have an inalloca argument, all stack space has already been allocated
2607   // for us and be right at the top of the stack.  We don't support multiple
2608   // arguments passed in memory when using inalloca.
2609   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2610     NumBytesToPush = 0;
2611     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2612            "an inalloca argument must be the only memory argument");
2613   }
2614
2615   if (!IsSibcall)
2616     Chain = DAG.getCALLSEQ_START(
2617         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2618
2619   SDValue RetAddrFrIdx;
2620   // Load return address for tail calls.
2621   if (isTailCall && FPDiff)
2622     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2623                                     Is64Bit, FPDiff, dl);
2624
2625   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2626   SmallVector<SDValue, 8> MemOpChains;
2627   SDValue StackPtr;
2628
2629   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2630   // of tail call optimization arguments are handle later.
2631   const X86RegisterInfo *RegInfo =
2632     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2633   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2634     // Skip inalloca arguments, they have already been written.
2635     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2636     if (Flags.isInAlloca())
2637       continue;
2638
2639     CCValAssign &VA = ArgLocs[i];
2640     EVT RegVT = VA.getLocVT();
2641     SDValue Arg = OutVals[i];
2642     bool isByVal = Flags.isByVal();
2643
2644     // Promote the value if needed.
2645     switch (VA.getLocInfo()) {
2646     default: llvm_unreachable("Unknown loc info!");
2647     case CCValAssign::Full: break;
2648     case CCValAssign::SExt:
2649       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2650       break;
2651     case CCValAssign::ZExt:
2652       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2653       break;
2654     case CCValAssign::AExt:
2655       if (RegVT.is128BitVector()) {
2656         // Special case: passing MMX values in XMM registers.
2657         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2658         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2659         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2660       } else
2661         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2662       break;
2663     case CCValAssign::BCvt:
2664       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2665       break;
2666     case CCValAssign::Indirect: {
2667       // Store the argument.
2668       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2669       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2670       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2671                            MachinePointerInfo::getFixedStack(FI),
2672                            false, false, 0);
2673       Arg = SpillSlot;
2674       break;
2675     }
2676     }
2677
2678     if (VA.isRegLoc()) {
2679       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2680       if (isVarArg && IsWin64) {
2681         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2682         // shadow reg if callee is a varargs function.
2683         unsigned ShadowReg = 0;
2684         switch (VA.getLocReg()) {
2685         case X86::XMM0: ShadowReg = X86::RCX; break;
2686         case X86::XMM1: ShadowReg = X86::RDX; break;
2687         case X86::XMM2: ShadowReg = X86::R8; break;
2688         case X86::XMM3: ShadowReg = X86::R9; break;
2689         }
2690         if (ShadowReg)
2691           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2692       }
2693     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2694       assert(VA.isMemLoc());
2695       if (!StackPtr.getNode())
2696         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2697                                       getPointerTy());
2698       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2699                                              dl, DAG, VA, Flags));
2700     }
2701   }
2702
2703   if (!MemOpChains.empty())
2704     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2705                         &MemOpChains[0], MemOpChains.size());
2706
2707   if (Subtarget->isPICStyleGOT()) {
2708     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2709     // GOT pointer.
2710     if (!isTailCall) {
2711       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2712                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2713     } else {
2714       // If we are tail calling and generating PIC/GOT style code load the
2715       // address of the callee into ECX. The value in ecx is used as target of
2716       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2717       // for tail calls on PIC/GOT architectures. Normally we would just put the
2718       // address of GOT into ebx and then call target@PLT. But for tail calls
2719       // ebx would be restored (since ebx is callee saved) before jumping to the
2720       // target@PLT.
2721
2722       // Note: The actual moving to ECX is done further down.
2723       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2724       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2725           !G->getGlobal()->hasProtectedVisibility())
2726         Callee = LowerGlobalAddress(Callee, DAG);
2727       else if (isa<ExternalSymbolSDNode>(Callee))
2728         Callee = LowerExternalSymbol(Callee, DAG);
2729     }
2730   }
2731
2732   if (Is64Bit && isVarArg && !IsWin64) {
2733     // From AMD64 ABI document:
2734     // For calls that may call functions that use varargs or stdargs
2735     // (prototype-less calls or calls to functions containing ellipsis (...) in
2736     // the declaration) %al is used as hidden argument to specify the number
2737     // of SSE registers used. The contents of %al do not need to match exactly
2738     // the number of registers, but must be an ubound on the number of SSE
2739     // registers used and is in the range 0 - 8 inclusive.
2740
2741     // Count the number of XMM registers allocated.
2742     static const MCPhysReg XMMArgRegs[] = {
2743       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2744       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2745     };
2746     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2747     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2748            && "SSE registers cannot be used when SSE is disabled");
2749
2750     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2751                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2752   }
2753
2754   // For tail calls lower the arguments to the 'real' stack slot.
2755   if (isTailCall) {
2756     // Force all the incoming stack arguments to be loaded from the stack
2757     // before any new outgoing arguments are stored to the stack, because the
2758     // outgoing stack slots may alias the incoming argument stack slots, and
2759     // the alias isn't otherwise explicit. This is slightly more conservative
2760     // than necessary, because it means that each store effectively depends
2761     // on every argument instead of just those arguments it would clobber.
2762     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2763
2764     SmallVector<SDValue, 8> MemOpChains2;
2765     SDValue FIN;
2766     int FI = 0;
2767     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2768       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2769         CCValAssign &VA = ArgLocs[i];
2770         if (VA.isRegLoc())
2771           continue;
2772         assert(VA.isMemLoc());
2773         SDValue Arg = OutVals[i];
2774         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2775         // Create frame index.
2776         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2777         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2778         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2779         FIN = DAG.getFrameIndex(FI, getPointerTy());
2780
2781         if (Flags.isByVal()) {
2782           // Copy relative to framepointer.
2783           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2784           if (!StackPtr.getNode())
2785             StackPtr = DAG.getCopyFromReg(Chain, dl,
2786                                           RegInfo->getStackRegister(),
2787                                           getPointerTy());
2788           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2789
2790           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2791                                                            ArgChain,
2792                                                            Flags, DAG, dl));
2793         } else {
2794           // Store relative to framepointer.
2795           MemOpChains2.push_back(
2796             DAG.getStore(ArgChain, dl, Arg, FIN,
2797                          MachinePointerInfo::getFixedStack(FI),
2798                          false, false, 0));
2799         }
2800       }
2801     }
2802
2803     if (!MemOpChains2.empty())
2804       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2805                           &MemOpChains2[0], MemOpChains2.size());
2806
2807     // Store the return address to the appropriate stack slot.
2808     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2809                                      getPointerTy(), RegInfo->getSlotSize(),
2810                                      FPDiff, dl);
2811   }
2812
2813   // Build a sequence of copy-to-reg nodes chained together with token chain
2814   // and flag operands which copy the outgoing args into registers.
2815   SDValue InFlag;
2816   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2817     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2818                              RegsToPass[i].second, InFlag);
2819     InFlag = Chain.getValue(1);
2820   }
2821
2822   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2823     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2824     // In the 64-bit large code model, we have to make all calls
2825     // through a register, since the call instruction's 32-bit
2826     // pc-relative offset may not be large enough to hold the whole
2827     // address.
2828   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2829     // If the callee is a GlobalAddress node (quite common, every direct call
2830     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2831     // it.
2832
2833     // We should use extra load for direct calls to dllimported functions in
2834     // non-JIT mode.
2835     const GlobalValue *GV = G->getGlobal();
2836     if (!GV->hasDLLImportStorageClass()) {
2837       unsigned char OpFlags = 0;
2838       bool ExtraLoad = false;
2839       unsigned WrapperKind = ISD::DELETED_NODE;
2840
2841       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2842       // external symbols most go through the PLT in PIC mode.  If the symbol
2843       // has hidden or protected visibility, or if it is static or local, then
2844       // we don't need to use the PLT - we can directly call it.
2845       if (Subtarget->isTargetELF() &&
2846           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2847           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2848         OpFlags = X86II::MO_PLT;
2849       } else if (Subtarget->isPICStyleStubAny() &&
2850                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2851                  (!Subtarget->getTargetTriple().isMacOSX() ||
2852                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2853         // PC-relative references to external symbols should go through $stub,
2854         // unless we're building with the leopard linker or later, which
2855         // automatically synthesizes these stubs.
2856         OpFlags = X86II::MO_DARWIN_STUB;
2857       } else if (Subtarget->isPICStyleRIPRel() &&
2858                  isa<Function>(GV) &&
2859                  cast<Function>(GV)->getAttributes().
2860                    hasAttribute(AttributeSet::FunctionIndex,
2861                                 Attribute::NonLazyBind)) {
2862         // If the function is marked as non-lazy, generate an indirect call
2863         // which loads from the GOT directly. This avoids runtime overhead
2864         // at the cost of eager binding (and one extra byte of encoding).
2865         OpFlags = X86II::MO_GOTPCREL;
2866         WrapperKind = X86ISD::WrapperRIP;
2867         ExtraLoad = true;
2868       }
2869
2870       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2871                                           G->getOffset(), OpFlags);
2872
2873       // Add a wrapper if needed.
2874       if (WrapperKind != ISD::DELETED_NODE)
2875         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2876       // Add extra indirection if needed.
2877       if (ExtraLoad)
2878         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2879                              MachinePointerInfo::getGOT(),
2880                              false, false, false, 0);
2881     }
2882   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2883     unsigned char OpFlags = 0;
2884
2885     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2886     // external symbols should go through the PLT.
2887     if (Subtarget->isTargetELF() &&
2888         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2889       OpFlags = X86II::MO_PLT;
2890     } else if (Subtarget->isPICStyleStubAny() &&
2891                (!Subtarget->getTargetTriple().isMacOSX() ||
2892                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2893       // PC-relative references to external symbols should go through $stub,
2894       // unless we're building with the leopard linker or later, which
2895       // automatically synthesizes these stubs.
2896       OpFlags = X86II::MO_DARWIN_STUB;
2897     }
2898
2899     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2900                                          OpFlags);
2901   }
2902
2903   // Returns a chain & a flag for retval copy to use.
2904   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2905   SmallVector<SDValue, 8> Ops;
2906
2907   if (!IsSibcall && isTailCall) {
2908     Chain = DAG.getCALLSEQ_END(Chain,
2909                                DAG.getIntPtrConstant(NumBytesToPop, true),
2910                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2911     InFlag = Chain.getValue(1);
2912   }
2913
2914   Ops.push_back(Chain);
2915   Ops.push_back(Callee);
2916
2917   if (isTailCall)
2918     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2919
2920   // Add argument registers to the end of the list so that they are known live
2921   // into the call.
2922   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2923     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2924                                   RegsToPass[i].second.getValueType()));
2925
2926   // Add a register mask operand representing the call-preserved registers.
2927   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2928   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2929   assert(Mask && "Missing call preserved mask for calling convention");
2930   Ops.push_back(DAG.getRegisterMask(Mask));
2931
2932   if (InFlag.getNode())
2933     Ops.push_back(InFlag);
2934
2935   if (isTailCall) {
2936     // We used to do:
2937     //// If this is the first return lowered for this function, add the regs
2938     //// to the liveout set for the function.
2939     // This isn't right, although it's probably harmless on x86; liveouts
2940     // should be computed from returns not tail calls.  Consider a void
2941     // function making a tail call to a function returning int.
2942     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2943   }
2944
2945   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2946   InFlag = Chain.getValue(1);
2947
2948   // Create the CALLSEQ_END node.
2949   unsigned NumBytesForCalleeToPop;
2950   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2951                        getTargetMachine().Options.GuaranteedTailCallOpt))
2952     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2953   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2954            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2955            SR == StackStructReturn)
2956     // If this is a call to a struct-return function, the callee
2957     // pops the hidden struct pointer, so we have to push it back.
2958     // This is common for Darwin/X86, Linux & Mingw32 targets.
2959     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2960     NumBytesForCalleeToPop = 4;
2961   else
2962     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2963
2964   // Returns a flag for retval copy to use.
2965   if (!IsSibcall) {
2966     Chain = DAG.getCALLSEQ_END(Chain,
2967                                DAG.getIntPtrConstant(NumBytesToPop, true),
2968                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2969                                                      true),
2970                                InFlag, dl);
2971     InFlag = Chain.getValue(1);
2972   }
2973
2974   // Handle result values, copying them out of physregs into vregs that we
2975   // return.
2976   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2977                          Ins, dl, DAG, InVals);
2978 }
2979
2980 //===----------------------------------------------------------------------===//
2981 //                Fast Calling Convention (tail call) implementation
2982 //===----------------------------------------------------------------------===//
2983
2984 //  Like std call, callee cleans arguments, convention except that ECX is
2985 //  reserved for storing the tail called function address. Only 2 registers are
2986 //  free for argument passing (inreg). Tail call optimization is performed
2987 //  provided:
2988 //                * tailcallopt is enabled
2989 //                * caller/callee are fastcc
2990 //  On X86_64 architecture with GOT-style position independent code only local
2991 //  (within module) calls are supported at the moment.
2992 //  To keep the stack aligned according to platform abi the function
2993 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2994 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2995 //  If a tail called function callee has more arguments than the caller the
2996 //  caller needs to make sure that there is room to move the RETADDR to. This is
2997 //  achieved by reserving an area the size of the argument delta right after the
2998 //  original REtADDR, but before the saved framepointer or the spilled registers
2999 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3000 //  stack layout:
3001 //    arg1
3002 //    arg2
3003 //    RETADDR
3004 //    [ new RETADDR
3005 //      move area ]
3006 //    (possible EBP)
3007 //    ESI
3008 //    EDI
3009 //    local1 ..
3010
3011 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3012 /// for a 16 byte align requirement.
3013 unsigned
3014 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3015                                                SelectionDAG& DAG) const {
3016   MachineFunction &MF = DAG.getMachineFunction();
3017   const TargetMachine &TM = MF.getTarget();
3018   const X86RegisterInfo *RegInfo =
3019     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3020   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3021   unsigned StackAlignment = TFI.getStackAlignment();
3022   uint64_t AlignMask = StackAlignment - 1;
3023   int64_t Offset = StackSize;
3024   unsigned SlotSize = RegInfo->getSlotSize();
3025   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3026     // Number smaller than 12 so just add the difference.
3027     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3028   } else {
3029     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3030     Offset = ((~AlignMask) & Offset) + StackAlignment +
3031       (StackAlignment-SlotSize);
3032   }
3033   return Offset;
3034 }
3035
3036 /// MatchingStackOffset - Return true if the given stack call argument is
3037 /// already available in the same position (relatively) of the caller's
3038 /// incoming argument stack.
3039 static
3040 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3041                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3042                          const X86InstrInfo *TII) {
3043   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3044   int FI = INT_MAX;
3045   if (Arg.getOpcode() == ISD::CopyFromReg) {
3046     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3047     if (!TargetRegisterInfo::isVirtualRegister(VR))
3048       return false;
3049     MachineInstr *Def = MRI->getVRegDef(VR);
3050     if (!Def)
3051       return false;
3052     if (!Flags.isByVal()) {
3053       if (!TII->isLoadFromStackSlot(Def, FI))
3054         return false;
3055     } else {
3056       unsigned Opcode = Def->getOpcode();
3057       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3058           Def->getOperand(1).isFI()) {
3059         FI = Def->getOperand(1).getIndex();
3060         Bytes = Flags.getByValSize();
3061       } else
3062         return false;
3063     }
3064   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3065     if (Flags.isByVal())
3066       // ByVal argument is passed in as a pointer but it's now being
3067       // dereferenced. e.g.
3068       // define @foo(%struct.X* %A) {
3069       //   tail call @bar(%struct.X* byval %A)
3070       // }
3071       return false;
3072     SDValue Ptr = Ld->getBasePtr();
3073     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3074     if (!FINode)
3075       return false;
3076     FI = FINode->getIndex();
3077   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3078     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3079     FI = FINode->getIndex();
3080     Bytes = Flags.getByValSize();
3081   } else
3082     return false;
3083
3084   assert(FI != INT_MAX);
3085   if (!MFI->isFixedObjectIndex(FI))
3086     return false;
3087   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3088 }
3089
3090 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3091 /// for tail call optimization. Targets which want to do tail call
3092 /// optimization should implement this function.
3093 bool
3094 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3095                                                      CallingConv::ID CalleeCC,
3096                                                      bool isVarArg,
3097                                                      bool isCalleeStructRet,
3098                                                      bool isCallerStructRet,
3099                                                      Type *RetTy,
3100                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3101                                     const SmallVectorImpl<SDValue> &OutVals,
3102                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3103                                                      SelectionDAG &DAG) const {
3104   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3105     return false;
3106
3107   // If -tailcallopt is specified, make fastcc functions tail-callable.
3108   const MachineFunction &MF = DAG.getMachineFunction();
3109   const Function *CallerF = MF.getFunction();
3110
3111   // If the function return type is x86_fp80 and the callee return type is not,
3112   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3113   // perform a tailcall optimization here.
3114   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3115     return false;
3116
3117   CallingConv::ID CallerCC = CallerF->getCallingConv();
3118   bool CCMatch = CallerCC == CalleeCC;
3119   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3120   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3121
3122   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3123     if (IsTailCallConvention(CalleeCC) && CCMatch)
3124       return true;
3125     return false;
3126   }
3127
3128   // Look for obvious safe cases to perform tail call optimization that do not
3129   // require ABI changes. This is what gcc calls sibcall.
3130
3131   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3132   // emit a special epilogue.
3133   const X86RegisterInfo *RegInfo =
3134     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3135   if (RegInfo->needsStackRealignment(MF))
3136     return false;
3137
3138   // Also avoid sibcall optimization if either caller or callee uses struct
3139   // return semantics.
3140   if (isCalleeStructRet || isCallerStructRet)
3141     return false;
3142
3143   // An stdcall/thiscall caller is expected to clean up its arguments; the
3144   // callee isn't going to do that.
3145   // FIXME: this is more restrictive than needed. We could produce a tailcall
3146   // when the stack adjustment matches. For example, with a thiscall that takes
3147   // only one argument.
3148   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3149                    CallerCC == CallingConv::X86_ThisCall))
3150     return false;
3151
3152   // Do not sibcall optimize vararg calls unless all arguments are passed via
3153   // registers.
3154   if (isVarArg && !Outs.empty()) {
3155
3156     // Optimizing for varargs on Win64 is unlikely to be safe without
3157     // additional testing.
3158     if (IsCalleeWin64 || IsCallerWin64)
3159       return false;
3160
3161     SmallVector<CCValAssign, 16> ArgLocs;
3162     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3163                    getTargetMachine(), ArgLocs, *DAG.getContext());
3164
3165     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3166     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3167       if (!ArgLocs[i].isRegLoc())
3168         return false;
3169   }
3170
3171   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3172   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3173   // this into a sibcall.
3174   bool Unused = false;
3175   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3176     if (!Ins[i].Used) {
3177       Unused = true;
3178       break;
3179     }
3180   }
3181   if (Unused) {
3182     SmallVector<CCValAssign, 16> RVLocs;
3183     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3184                    getTargetMachine(), RVLocs, *DAG.getContext());
3185     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3186     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3187       CCValAssign &VA = RVLocs[i];
3188       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3189         return false;
3190     }
3191   }
3192
3193   // If the calling conventions do not match, then we'd better make sure the
3194   // results are returned in the same way as what the caller expects.
3195   if (!CCMatch) {
3196     SmallVector<CCValAssign, 16> RVLocs1;
3197     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3198                     getTargetMachine(), RVLocs1, *DAG.getContext());
3199     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3200
3201     SmallVector<CCValAssign, 16> RVLocs2;
3202     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3203                     getTargetMachine(), RVLocs2, *DAG.getContext());
3204     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3205
3206     if (RVLocs1.size() != RVLocs2.size())
3207       return false;
3208     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3209       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3210         return false;
3211       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3212         return false;
3213       if (RVLocs1[i].isRegLoc()) {
3214         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3215           return false;
3216       } else {
3217         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3218           return false;
3219       }
3220     }
3221   }
3222
3223   // If the callee takes no arguments then go on to check the results of the
3224   // call.
3225   if (!Outs.empty()) {
3226     // Check if stack adjustment is needed. For now, do not do this if any
3227     // argument is passed on the stack.
3228     SmallVector<CCValAssign, 16> ArgLocs;
3229     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3230                    getTargetMachine(), ArgLocs, *DAG.getContext());
3231
3232     // Allocate shadow area for Win64
3233     if (IsCalleeWin64)
3234       CCInfo.AllocateStack(32, 8);
3235
3236     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3237     if (CCInfo.getNextStackOffset()) {
3238       MachineFunction &MF = DAG.getMachineFunction();
3239       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3240         return false;
3241
3242       // Check if the arguments are already laid out in the right way as
3243       // the caller's fixed stack objects.
3244       MachineFrameInfo *MFI = MF.getFrameInfo();
3245       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3246       const X86InstrInfo *TII =
3247         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3248       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3249         CCValAssign &VA = ArgLocs[i];
3250         SDValue Arg = OutVals[i];
3251         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3252         if (VA.getLocInfo() == CCValAssign::Indirect)
3253           return false;
3254         if (!VA.isRegLoc()) {
3255           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3256                                    MFI, MRI, TII))
3257             return false;
3258         }
3259       }
3260     }
3261
3262     // If the tailcall address may be in a register, then make sure it's
3263     // possible to register allocate for it. In 32-bit, the call address can
3264     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3265     // callee-saved registers are restored. These happen to be the same
3266     // registers used to pass 'inreg' arguments so watch out for those.
3267     if (!Subtarget->is64Bit() &&
3268         ((!isa<GlobalAddressSDNode>(Callee) &&
3269           !isa<ExternalSymbolSDNode>(Callee)) ||
3270          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3271       unsigned NumInRegs = 0;
3272       // In PIC we need an extra register to formulate the address computation
3273       // for the callee.
3274       unsigned MaxInRegs =
3275           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3276
3277       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3278         CCValAssign &VA = ArgLocs[i];
3279         if (!VA.isRegLoc())
3280           continue;
3281         unsigned Reg = VA.getLocReg();
3282         switch (Reg) {
3283         default: break;
3284         case X86::EAX: case X86::EDX: case X86::ECX:
3285           if (++NumInRegs == MaxInRegs)
3286             return false;
3287           break;
3288         }
3289       }
3290     }
3291   }
3292
3293   return true;
3294 }
3295
3296 FastISel *
3297 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3298                                   const TargetLibraryInfo *libInfo) const {
3299   return X86::createFastISel(funcInfo, libInfo);
3300 }
3301
3302 //===----------------------------------------------------------------------===//
3303 //                           Other Lowering Hooks
3304 //===----------------------------------------------------------------------===//
3305
3306 static bool MayFoldLoad(SDValue Op) {
3307   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3308 }
3309
3310 static bool MayFoldIntoStore(SDValue Op) {
3311   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3312 }
3313
3314 static bool isTargetShuffle(unsigned Opcode) {
3315   switch(Opcode) {
3316   default: return false;
3317   case X86ISD::PSHUFD:
3318   case X86ISD::PSHUFHW:
3319   case X86ISD::PSHUFLW:
3320   case X86ISD::SHUFP:
3321   case X86ISD::PALIGNR:
3322   case X86ISD::MOVLHPS:
3323   case X86ISD::MOVLHPD:
3324   case X86ISD::MOVHLPS:
3325   case X86ISD::MOVLPS:
3326   case X86ISD::MOVLPD:
3327   case X86ISD::MOVSHDUP:
3328   case X86ISD::MOVSLDUP:
3329   case X86ISD::MOVDDUP:
3330   case X86ISD::MOVSS:
3331   case X86ISD::MOVSD:
3332   case X86ISD::UNPCKL:
3333   case X86ISD::UNPCKH:
3334   case X86ISD::VPERMILP:
3335   case X86ISD::VPERM2X128:
3336   case X86ISD::VPERMI:
3337     return true;
3338   }
3339 }
3340
3341 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3342                                     SDValue V1, SelectionDAG &DAG) {
3343   switch(Opc) {
3344   default: llvm_unreachable("Unknown x86 shuffle node");
3345   case X86ISD::MOVSHDUP:
3346   case X86ISD::MOVSLDUP:
3347   case X86ISD::MOVDDUP:
3348     return DAG.getNode(Opc, dl, VT, V1);
3349   }
3350 }
3351
3352 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3353                                     SDValue V1, unsigned TargetMask,
3354                                     SelectionDAG &DAG) {
3355   switch(Opc) {
3356   default: llvm_unreachable("Unknown x86 shuffle node");
3357   case X86ISD::PSHUFD:
3358   case X86ISD::PSHUFHW:
3359   case X86ISD::PSHUFLW:
3360   case X86ISD::VPERMILP:
3361   case X86ISD::VPERMI:
3362     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3363   }
3364 }
3365
3366 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3367                                     SDValue V1, SDValue V2, unsigned TargetMask,
3368                                     SelectionDAG &DAG) {
3369   switch(Opc) {
3370   default: llvm_unreachable("Unknown x86 shuffle node");
3371   case X86ISD::PALIGNR:
3372   case X86ISD::SHUFP:
3373   case X86ISD::VPERM2X128:
3374     return DAG.getNode(Opc, dl, VT, V1, V2,
3375                        DAG.getConstant(TargetMask, MVT::i8));
3376   }
3377 }
3378
3379 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3380                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3381   switch(Opc) {
3382   default: llvm_unreachable("Unknown x86 shuffle node");
3383   case X86ISD::MOVLHPS:
3384   case X86ISD::MOVLHPD:
3385   case X86ISD::MOVHLPS:
3386   case X86ISD::MOVLPS:
3387   case X86ISD::MOVLPD:
3388   case X86ISD::MOVSS:
3389   case X86ISD::MOVSD:
3390   case X86ISD::UNPCKL:
3391   case X86ISD::UNPCKH:
3392     return DAG.getNode(Opc, dl, VT, V1, V2);
3393   }
3394 }
3395
3396 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3397   MachineFunction &MF = DAG.getMachineFunction();
3398   const X86RegisterInfo *RegInfo =
3399     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3400   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3401   int ReturnAddrIndex = FuncInfo->getRAIndex();
3402
3403   if (ReturnAddrIndex == 0) {
3404     // Set up a frame object for the return address.
3405     unsigned SlotSize = RegInfo->getSlotSize();
3406     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3407                                                            -(int64_t)SlotSize,
3408                                                            false);
3409     FuncInfo->setRAIndex(ReturnAddrIndex);
3410   }
3411
3412   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3413 }
3414
3415 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3416                                        bool hasSymbolicDisplacement) {
3417   // Offset should fit into 32 bit immediate field.
3418   if (!isInt<32>(Offset))
3419     return false;
3420
3421   // If we don't have a symbolic displacement - we don't have any extra
3422   // restrictions.
3423   if (!hasSymbolicDisplacement)
3424     return true;
3425
3426   // FIXME: Some tweaks might be needed for medium code model.
3427   if (M != CodeModel::Small && M != CodeModel::Kernel)
3428     return false;
3429
3430   // For small code model we assume that latest object is 16MB before end of 31
3431   // bits boundary. We may also accept pretty large negative constants knowing
3432   // that all objects are in the positive half of address space.
3433   if (M == CodeModel::Small && Offset < 16*1024*1024)
3434     return true;
3435
3436   // For kernel code model we know that all object resist in the negative half
3437   // of 32bits address space. We may not accept negative offsets, since they may
3438   // be just off and we may accept pretty large positive ones.
3439   if (M == CodeModel::Kernel && Offset > 0)
3440     return true;
3441
3442   return false;
3443 }
3444
3445 /// isCalleePop - Determines whether the callee is required to pop its
3446 /// own arguments. Callee pop is necessary to support tail calls.
3447 bool X86::isCalleePop(CallingConv::ID CallingConv,
3448                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3449   if (IsVarArg)
3450     return false;
3451
3452   switch (CallingConv) {
3453   default:
3454     return false;
3455   case CallingConv::X86_StdCall:
3456     return !is64Bit;
3457   case CallingConv::X86_FastCall:
3458     return !is64Bit;
3459   case CallingConv::X86_ThisCall:
3460     return !is64Bit;
3461   case CallingConv::Fast:
3462     return TailCallOpt;
3463   case CallingConv::GHC:
3464     return TailCallOpt;
3465   case CallingConv::HiPE:
3466     return TailCallOpt;
3467   }
3468 }
3469
3470 /// \brief Return true if the condition is an unsigned comparison operation.
3471 static bool isX86CCUnsigned(unsigned X86CC) {
3472   switch (X86CC) {
3473   default: llvm_unreachable("Invalid integer condition!");
3474   case X86::COND_E:     return true;
3475   case X86::COND_G:     return false;
3476   case X86::COND_GE:    return false;
3477   case X86::COND_L:     return false;
3478   case X86::COND_LE:    return false;
3479   case X86::COND_NE:    return true;
3480   case X86::COND_B:     return true;
3481   case X86::COND_A:     return true;
3482   case X86::COND_BE:    return true;
3483   case X86::COND_AE:    return true;
3484   }
3485   llvm_unreachable("covered switch fell through?!");
3486 }
3487
3488 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3489 /// specific condition code, returning the condition code and the LHS/RHS of the
3490 /// comparison to make.
3491 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3492                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3493   if (!isFP) {
3494     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3495       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3496         // X > -1   -> X == 0, jump !sign.
3497         RHS = DAG.getConstant(0, RHS.getValueType());
3498         return X86::COND_NS;
3499       }
3500       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3501         // X < 0   -> X == 0, jump on sign.
3502         return X86::COND_S;
3503       }
3504       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3505         // X < 1   -> X <= 0
3506         RHS = DAG.getConstant(0, RHS.getValueType());
3507         return X86::COND_LE;
3508       }
3509     }
3510
3511     switch (SetCCOpcode) {
3512     default: llvm_unreachable("Invalid integer condition!");
3513     case ISD::SETEQ:  return X86::COND_E;
3514     case ISD::SETGT:  return X86::COND_G;
3515     case ISD::SETGE:  return X86::COND_GE;
3516     case ISD::SETLT:  return X86::COND_L;
3517     case ISD::SETLE:  return X86::COND_LE;
3518     case ISD::SETNE:  return X86::COND_NE;
3519     case ISD::SETULT: return X86::COND_B;
3520     case ISD::SETUGT: return X86::COND_A;
3521     case ISD::SETULE: return X86::COND_BE;
3522     case ISD::SETUGE: return X86::COND_AE;
3523     }
3524   }
3525
3526   // First determine if it is required or is profitable to flip the operands.
3527
3528   // If LHS is a foldable load, but RHS is not, flip the condition.
3529   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3530       !ISD::isNON_EXTLoad(RHS.getNode())) {
3531     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3532     std::swap(LHS, RHS);
3533   }
3534
3535   switch (SetCCOpcode) {
3536   default: break;
3537   case ISD::SETOLT:
3538   case ISD::SETOLE:
3539   case ISD::SETUGT:
3540   case ISD::SETUGE:
3541     std::swap(LHS, RHS);
3542     break;
3543   }
3544
3545   // On a floating point condition, the flags are set as follows:
3546   // ZF  PF  CF   op
3547   //  0 | 0 | 0 | X > Y
3548   //  0 | 0 | 1 | X < Y
3549   //  1 | 0 | 0 | X == Y
3550   //  1 | 1 | 1 | unordered
3551   switch (SetCCOpcode) {
3552   default: llvm_unreachable("Condcode should be pre-legalized away");
3553   case ISD::SETUEQ:
3554   case ISD::SETEQ:   return X86::COND_E;
3555   case ISD::SETOLT:              // flipped
3556   case ISD::SETOGT:
3557   case ISD::SETGT:   return X86::COND_A;
3558   case ISD::SETOLE:              // flipped
3559   case ISD::SETOGE:
3560   case ISD::SETGE:   return X86::COND_AE;
3561   case ISD::SETUGT:              // flipped
3562   case ISD::SETULT:
3563   case ISD::SETLT:   return X86::COND_B;
3564   case ISD::SETUGE:              // flipped
3565   case ISD::SETULE:
3566   case ISD::SETLE:   return X86::COND_BE;
3567   case ISD::SETONE:
3568   case ISD::SETNE:   return X86::COND_NE;
3569   case ISD::SETUO:   return X86::COND_P;
3570   case ISD::SETO:    return X86::COND_NP;
3571   case ISD::SETOEQ:
3572   case ISD::SETUNE:  return X86::COND_INVALID;
3573   }
3574 }
3575
3576 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3577 /// code. Current x86 isa includes the following FP cmov instructions:
3578 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3579 static bool hasFPCMov(unsigned X86CC) {
3580   switch (X86CC) {
3581   default:
3582     return false;
3583   case X86::COND_B:
3584   case X86::COND_BE:
3585   case X86::COND_E:
3586   case X86::COND_P:
3587   case X86::COND_A:
3588   case X86::COND_AE:
3589   case X86::COND_NE:
3590   case X86::COND_NP:
3591     return true;
3592   }
3593 }
3594
3595 /// isFPImmLegal - Returns true if the target can instruction select the
3596 /// specified FP immediate natively. If false, the legalizer will
3597 /// materialize the FP immediate as a load from a constant pool.
3598 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3599   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3600     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3601       return true;
3602   }
3603   return false;
3604 }
3605
3606 /// \brief Returns true if it is beneficial to convert a load of a constant
3607 /// to just the constant itself.
3608 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3609                                                           Type *Ty) const {
3610   assert(Ty->isIntegerTy());
3611
3612   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3613   if (BitSize == 0 || BitSize > 64)
3614     return false;
3615   return true;
3616 }
3617
3618 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3619 /// the specified range (L, H].
3620 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3621   return (Val < 0) || (Val >= Low && Val < Hi);
3622 }
3623
3624 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3625 /// specified value.
3626 static bool isUndefOrEqual(int Val, int CmpVal) {
3627   return (Val < 0 || Val == CmpVal);
3628 }
3629
3630 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3631 /// from position Pos and ending in Pos+Size, falls within the specified
3632 /// sequential range (L, L+Pos]. or is undef.
3633 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3634                                        unsigned Pos, unsigned Size, int Low) {
3635   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3636     if (!isUndefOrEqual(Mask[i], Low))
3637       return false;
3638   return true;
3639 }
3640
3641 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3642 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3643 /// the second operand.
3644 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3645   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3646     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3647   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3648     return (Mask[0] < 2 && Mask[1] < 2);
3649   return false;
3650 }
3651
3652 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3653 /// is suitable for input to PSHUFHW.
3654 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3655   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3656     return false;
3657
3658   // Lower quadword copied in order or undef.
3659   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3660     return false;
3661
3662   // Upper quadword shuffled.
3663   for (unsigned i = 4; i != 8; ++i)
3664     if (!isUndefOrInRange(Mask[i], 4, 8))
3665       return false;
3666
3667   if (VT == MVT::v16i16) {
3668     // Lower quadword copied in order or undef.
3669     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3670       return false;
3671
3672     // Upper quadword shuffled.
3673     for (unsigned i = 12; i != 16; ++i)
3674       if (!isUndefOrInRange(Mask[i], 12, 16))
3675         return false;
3676   }
3677
3678   return true;
3679 }
3680
3681 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3682 /// is suitable for input to PSHUFLW.
3683 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3684   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3685     return false;
3686
3687   // Upper quadword copied in order.
3688   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3689     return false;
3690
3691   // Lower quadword shuffled.
3692   for (unsigned i = 0; i != 4; ++i)
3693     if (!isUndefOrInRange(Mask[i], 0, 4))
3694       return false;
3695
3696   if (VT == MVT::v16i16) {
3697     // Upper quadword copied in order.
3698     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3699       return false;
3700
3701     // Lower quadword shuffled.
3702     for (unsigned i = 8; i != 12; ++i)
3703       if (!isUndefOrInRange(Mask[i], 8, 12))
3704         return false;
3705   }
3706
3707   return true;
3708 }
3709
3710 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3711 /// is suitable for input to PALIGNR.
3712 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3713                           const X86Subtarget *Subtarget) {
3714   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3715       (VT.is256BitVector() && !Subtarget->hasInt256()))
3716     return false;
3717
3718   unsigned NumElts = VT.getVectorNumElements();
3719   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3720   unsigned NumLaneElts = NumElts/NumLanes;
3721
3722   // Do not handle 64-bit element shuffles with palignr.
3723   if (NumLaneElts == 2)
3724     return false;
3725
3726   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3727     unsigned i;
3728     for (i = 0; i != NumLaneElts; ++i) {
3729       if (Mask[i+l] >= 0)
3730         break;
3731     }
3732
3733     // Lane is all undef, go to next lane
3734     if (i == NumLaneElts)
3735       continue;
3736
3737     int Start = Mask[i+l];
3738
3739     // Make sure its in this lane in one of the sources
3740     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3741         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3742       return false;
3743
3744     // If not lane 0, then we must match lane 0
3745     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3746       return false;
3747
3748     // Correct second source to be contiguous with first source
3749     if (Start >= (int)NumElts)
3750       Start -= NumElts - NumLaneElts;
3751
3752     // Make sure we're shifting in the right direction.
3753     if (Start <= (int)(i+l))
3754       return false;
3755
3756     Start -= i;
3757
3758     // Check the rest of the elements to see if they are consecutive.
3759     for (++i; i != NumLaneElts; ++i) {
3760       int Idx = Mask[i+l];
3761
3762       // Make sure its in this lane
3763       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3764           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3765         return false;
3766
3767       // If not lane 0, then we must match lane 0
3768       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3769         return false;
3770
3771       if (Idx >= (int)NumElts)
3772         Idx -= NumElts - NumLaneElts;
3773
3774       if (!isUndefOrEqual(Idx, Start+i))
3775         return false;
3776
3777     }
3778   }
3779
3780   return true;
3781 }
3782
3783 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3784 /// the two vector operands have swapped position.
3785 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3786                                      unsigned NumElems) {
3787   for (unsigned i = 0; i != NumElems; ++i) {
3788     int idx = Mask[i];
3789     if (idx < 0)
3790       continue;
3791     else if (idx < (int)NumElems)
3792       Mask[i] = idx + NumElems;
3793     else
3794       Mask[i] = idx - NumElems;
3795   }
3796 }
3797
3798 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3799 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3800 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3801 /// reverse of what x86 shuffles want.
3802 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3803
3804   unsigned NumElems = VT.getVectorNumElements();
3805   unsigned NumLanes = VT.getSizeInBits()/128;
3806   unsigned NumLaneElems = NumElems/NumLanes;
3807
3808   if (NumLaneElems != 2 && NumLaneElems != 4)
3809     return false;
3810
3811   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3812   bool symetricMaskRequired =
3813     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3814
3815   // VSHUFPSY divides the resulting vector into 4 chunks.
3816   // The sources are also splitted into 4 chunks, and each destination
3817   // chunk must come from a different source chunk.
3818   //
3819   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3820   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3821   //
3822   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3823   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3824   //
3825   // VSHUFPDY divides the resulting vector into 4 chunks.
3826   // The sources are also splitted into 4 chunks, and each destination
3827   // chunk must come from a different source chunk.
3828   //
3829   //  SRC1 =>      X3       X2       X1       X0
3830   //  SRC2 =>      Y3       Y2       Y1       Y0
3831   //
3832   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3833   //
3834   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3835   unsigned HalfLaneElems = NumLaneElems/2;
3836   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3837     for (unsigned i = 0; i != NumLaneElems; ++i) {
3838       int Idx = Mask[i+l];
3839       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3840       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3841         return false;
3842       // For VSHUFPSY, the mask of the second half must be the same as the
3843       // first but with the appropriate offsets. This works in the same way as
3844       // VPERMILPS works with masks.
3845       if (!symetricMaskRequired || Idx < 0)
3846         continue;
3847       if (MaskVal[i] < 0) {
3848         MaskVal[i] = Idx - l;
3849         continue;
3850       }
3851       if ((signed)(Idx - l) != MaskVal[i])
3852         return false;
3853     }
3854   }
3855
3856   return true;
3857 }
3858
3859 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3860 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3861 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3862   if (!VT.is128BitVector())
3863     return false;
3864
3865   unsigned NumElems = VT.getVectorNumElements();
3866
3867   if (NumElems != 4)
3868     return false;
3869
3870   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3871   return isUndefOrEqual(Mask[0], 6) &&
3872          isUndefOrEqual(Mask[1], 7) &&
3873          isUndefOrEqual(Mask[2], 2) &&
3874          isUndefOrEqual(Mask[3], 3);
3875 }
3876
3877 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3878 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3879 /// <2, 3, 2, 3>
3880 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3881   if (!VT.is128BitVector())
3882     return false;
3883
3884   unsigned NumElems = VT.getVectorNumElements();
3885
3886   if (NumElems != 4)
3887     return false;
3888
3889   return isUndefOrEqual(Mask[0], 2) &&
3890          isUndefOrEqual(Mask[1], 3) &&
3891          isUndefOrEqual(Mask[2], 2) &&
3892          isUndefOrEqual(Mask[3], 3);
3893 }
3894
3895 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3896 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3897 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3898   if (!VT.is128BitVector())
3899     return false;
3900
3901   unsigned NumElems = VT.getVectorNumElements();
3902
3903   if (NumElems != 2 && NumElems != 4)
3904     return false;
3905
3906   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3907     if (!isUndefOrEqual(Mask[i], i + NumElems))
3908       return false;
3909
3910   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3911     if (!isUndefOrEqual(Mask[i], i))
3912       return false;
3913
3914   return true;
3915 }
3916
3917 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3918 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3919 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3920   if (!VT.is128BitVector())
3921     return false;
3922
3923   unsigned NumElems = VT.getVectorNumElements();
3924
3925   if (NumElems != 2 && NumElems != 4)
3926     return false;
3927
3928   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3929     if (!isUndefOrEqual(Mask[i], i))
3930       return false;
3931
3932   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3933     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3934       return false;
3935
3936   return true;
3937 }
3938
3939 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3940 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3941 /// i. e: If all but one element come from the same vector.
3942 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3943   // TODO: Deal with AVX's VINSERTPS
3944   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3945     return false;
3946
3947   unsigned CorrectPosV1 = 0;
3948   unsigned CorrectPosV2 = 0;
3949   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3950     if (Mask[i] == i)
3951       ++CorrectPosV1;
3952     else if (Mask[i] == i + 4)
3953       ++CorrectPosV2;
3954
3955   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3956     // We have 3 elements from one vector, and one from another.
3957     return true;
3958
3959   return false;
3960 }
3961
3962 //
3963 // Some special combinations that can be optimized.
3964 //
3965 static
3966 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3967                                SelectionDAG &DAG) {
3968   MVT VT = SVOp->getSimpleValueType(0);
3969   SDLoc dl(SVOp);
3970
3971   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3972     return SDValue();
3973
3974   ArrayRef<int> Mask = SVOp->getMask();
3975
3976   // These are the special masks that may be optimized.
3977   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3978   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3979   bool MatchEvenMask = true;
3980   bool MatchOddMask  = true;
3981   for (int i=0; i<8; ++i) {
3982     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3983       MatchEvenMask = false;
3984     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3985       MatchOddMask = false;
3986   }
3987
3988   if (!MatchEvenMask && !MatchOddMask)
3989     return SDValue();
3990
3991   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3992
3993   SDValue Op0 = SVOp->getOperand(0);
3994   SDValue Op1 = SVOp->getOperand(1);
3995
3996   if (MatchEvenMask) {
3997     // Shift the second operand right to 32 bits.
3998     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3999     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4000   } else {
4001     // Shift the first operand left to 32 bits.
4002     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4003     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4004   }
4005   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4006   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4007 }
4008
4009 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4010 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4011 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4012                          bool HasInt256, bool V2IsSplat = false) {
4013
4014   assert(VT.getSizeInBits() >= 128 &&
4015          "Unsupported vector type for unpckl");
4016
4017   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4018   unsigned NumLanes;
4019   unsigned NumOf256BitLanes;
4020   unsigned NumElts = VT.getVectorNumElements();
4021   if (VT.is256BitVector()) {
4022     if (NumElts != 4 && NumElts != 8 &&
4023         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4024     return false;
4025     NumLanes = 2;
4026     NumOf256BitLanes = 1;
4027   } else if (VT.is512BitVector()) {
4028     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4029            "Unsupported vector type for unpckh");
4030     NumLanes = 2;
4031     NumOf256BitLanes = 2;
4032   } else {
4033     NumLanes = 1;
4034     NumOf256BitLanes = 1;
4035   }
4036
4037   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4038   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4039
4040   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4041     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4042       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4043         int BitI  = Mask[l256*NumEltsInStride+l+i];
4044         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4045         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4046           return false;
4047         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4048           return false;
4049         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4050           return false;
4051       }
4052     }
4053   }
4054   return true;
4055 }
4056
4057 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4058 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4059 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4060                          bool HasInt256, bool V2IsSplat = false) {
4061   assert(VT.getSizeInBits() >= 128 &&
4062          "Unsupported vector type for unpckh");
4063
4064   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4065   unsigned NumLanes;
4066   unsigned NumOf256BitLanes;
4067   unsigned NumElts = VT.getVectorNumElements();
4068   if (VT.is256BitVector()) {
4069     if (NumElts != 4 && NumElts != 8 &&
4070         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4071     return false;
4072     NumLanes = 2;
4073     NumOf256BitLanes = 1;
4074   } else if (VT.is512BitVector()) {
4075     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4076            "Unsupported vector type for unpckh");
4077     NumLanes = 2;
4078     NumOf256BitLanes = 2;
4079   } else {
4080     NumLanes = 1;
4081     NumOf256BitLanes = 1;
4082   }
4083
4084   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4085   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4086
4087   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4088     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4089       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4090         int BitI  = Mask[l256*NumEltsInStride+l+i];
4091         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4092         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4093           return false;
4094         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4095           return false;
4096         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4097           return false;
4098       }
4099     }
4100   }
4101   return true;
4102 }
4103
4104 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4105 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4106 /// <0, 0, 1, 1>
4107 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4108   unsigned NumElts = VT.getVectorNumElements();
4109   bool Is256BitVec = VT.is256BitVector();
4110
4111   if (VT.is512BitVector())
4112     return false;
4113   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4114          "Unsupported vector type for unpckh");
4115
4116   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4117       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4118     return false;
4119
4120   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4121   // FIXME: Need a better way to get rid of this, there's no latency difference
4122   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4123   // the former later. We should also remove the "_undef" special mask.
4124   if (NumElts == 4 && Is256BitVec)
4125     return false;
4126
4127   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4128   // independently on 128-bit lanes.
4129   unsigned NumLanes = VT.getSizeInBits()/128;
4130   unsigned NumLaneElts = NumElts/NumLanes;
4131
4132   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4133     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4134       int BitI  = Mask[l+i];
4135       int BitI1 = Mask[l+i+1];
4136
4137       if (!isUndefOrEqual(BitI, j))
4138         return false;
4139       if (!isUndefOrEqual(BitI1, j))
4140         return false;
4141     }
4142   }
4143
4144   return true;
4145 }
4146
4147 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4148 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4149 /// <2, 2, 3, 3>
4150 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4151   unsigned NumElts = VT.getVectorNumElements();
4152
4153   if (VT.is512BitVector())
4154     return false;
4155
4156   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4157          "Unsupported vector type for unpckh");
4158
4159   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4160       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4161     return false;
4162
4163   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4164   // independently on 128-bit lanes.
4165   unsigned NumLanes = VT.getSizeInBits()/128;
4166   unsigned NumLaneElts = NumElts/NumLanes;
4167
4168   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4169     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4170       int BitI  = Mask[l+i];
4171       int BitI1 = Mask[l+i+1];
4172       if (!isUndefOrEqual(BitI, j))
4173         return false;
4174       if (!isUndefOrEqual(BitI1, j))
4175         return false;
4176     }
4177   }
4178   return true;
4179 }
4180
4181 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4182 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4183 /// MOVSD, and MOVD, i.e. setting the lowest element.
4184 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4185   if (VT.getVectorElementType().getSizeInBits() < 32)
4186     return false;
4187   if (!VT.is128BitVector())
4188     return false;
4189
4190   unsigned NumElts = VT.getVectorNumElements();
4191
4192   if (!isUndefOrEqual(Mask[0], NumElts))
4193     return false;
4194
4195   for (unsigned i = 1; i != NumElts; ++i)
4196     if (!isUndefOrEqual(Mask[i], i))
4197       return false;
4198
4199   return true;
4200 }
4201
4202 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4203 /// as permutations between 128-bit chunks or halves. As an example: this
4204 /// shuffle bellow:
4205 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4206 /// The first half comes from the second half of V1 and the second half from the
4207 /// the second half of V2.
4208 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4209   if (!HasFp256 || !VT.is256BitVector())
4210     return false;
4211
4212   // The shuffle result is divided into half A and half B. In total the two
4213   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4214   // B must come from C, D, E or F.
4215   unsigned HalfSize = VT.getVectorNumElements()/2;
4216   bool MatchA = false, MatchB = false;
4217
4218   // Check if A comes from one of C, D, E, F.
4219   for (unsigned Half = 0; Half != 4; ++Half) {
4220     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4221       MatchA = true;
4222       break;
4223     }
4224   }
4225
4226   // Check if B comes from one of C, D, E, F.
4227   for (unsigned Half = 0; Half != 4; ++Half) {
4228     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4229       MatchB = true;
4230       break;
4231     }
4232   }
4233
4234   return MatchA && MatchB;
4235 }
4236
4237 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4238 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4239 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4240   MVT VT = SVOp->getSimpleValueType(0);
4241
4242   unsigned HalfSize = VT.getVectorNumElements()/2;
4243
4244   unsigned FstHalf = 0, SndHalf = 0;
4245   for (unsigned i = 0; i < HalfSize; ++i) {
4246     if (SVOp->getMaskElt(i) > 0) {
4247       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4248       break;
4249     }
4250   }
4251   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4252     if (SVOp->getMaskElt(i) > 0) {
4253       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4254       break;
4255     }
4256   }
4257
4258   return (FstHalf | (SndHalf << 4));
4259 }
4260
4261 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4262 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4263   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4264   if (EltSize < 32)
4265     return false;
4266
4267   unsigned NumElts = VT.getVectorNumElements();
4268   Imm8 = 0;
4269   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4270     for (unsigned i = 0; i != NumElts; ++i) {
4271       if (Mask[i] < 0)
4272         continue;
4273       Imm8 |= Mask[i] << (i*2);
4274     }
4275     return true;
4276   }
4277
4278   unsigned LaneSize = 4;
4279   SmallVector<int, 4> MaskVal(LaneSize, -1);
4280
4281   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4282     for (unsigned i = 0; i != LaneSize; ++i) {
4283       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4284         return false;
4285       if (Mask[i+l] < 0)
4286         continue;
4287       if (MaskVal[i] < 0) {
4288         MaskVal[i] = Mask[i+l] - l;
4289         Imm8 |= MaskVal[i] << (i*2);
4290         continue;
4291       }
4292       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4293         return false;
4294     }
4295   }
4296   return true;
4297 }
4298
4299 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4300 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4301 /// Note that VPERMIL mask matching is different depending whether theunderlying
4302 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4303 /// to the same elements of the low, but to the higher half of the source.
4304 /// In VPERMILPD the two lanes could be shuffled independently of each other
4305 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4306 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4307   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4308   if (VT.getSizeInBits() < 256 || EltSize < 32)
4309     return false;
4310   bool symetricMaskRequired = (EltSize == 32);
4311   unsigned NumElts = VT.getVectorNumElements();
4312
4313   unsigned NumLanes = VT.getSizeInBits()/128;
4314   unsigned LaneSize = NumElts/NumLanes;
4315   // 2 or 4 elements in one lane
4316
4317   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4318   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4319     for (unsigned i = 0; i != LaneSize; ++i) {
4320       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4321         return false;
4322       if (symetricMaskRequired) {
4323         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4324           ExpectedMaskVal[i] = Mask[i+l] - l;
4325           continue;
4326         }
4327         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4328           return false;
4329       }
4330     }
4331   }
4332   return true;
4333 }
4334
4335 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4336 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4337 /// element of vector 2 and the other elements to come from vector 1 in order.
4338 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4339                                bool V2IsSplat = false, bool V2IsUndef = false) {
4340   if (!VT.is128BitVector())
4341     return false;
4342
4343   unsigned NumOps = VT.getVectorNumElements();
4344   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4345     return false;
4346
4347   if (!isUndefOrEqual(Mask[0], 0))
4348     return false;
4349
4350   for (unsigned i = 1; i != NumOps; ++i)
4351     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4352           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4353           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4354       return false;
4355
4356   return true;
4357 }
4358
4359 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4360 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4361 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4362 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4363                            const X86Subtarget *Subtarget) {
4364   if (!Subtarget->hasSSE3())
4365     return false;
4366
4367   unsigned NumElems = VT.getVectorNumElements();
4368
4369   if ((VT.is128BitVector() && NumElems != 4) ||
4370       (VT.is256BitVector() && NumElems != 8) ||
4371       (VT.is512BitVector() && NumElems != 16))
4372     return false;
4373
4374   // "i+1" is the value the indexed mask element must have
4375   for (unsigned i = 0; i != NumElems; i += 2)
4376     if (!isUndefOrEqual(Mask[i], i+1) ||
4377         !isUndefOrEqual(Mask[i+1], i+1))
4378       return false;
4379
4380   return true;
4381 }
4382
4383 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4384 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4385 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4386 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4387                            const X86Subtarget *Subtarget) {
4388   if (!Subtarget->hasSSE3())
4389     return false;
4390
4391   unsigned NumElems = VT.getVectorNumElements();
4392
4393   if ((VT.is128BitVector() && NumElems != 4) ||
4394       (VT.is256BitVector() && NumElems != 8) ||
4395       (VT.is512BitVector() && NumElems != 16))
4396     return false;
4397
4398   // "i" is the value the indexed mask element must have
4399   for (unsigned i = 0; i != NumElems; i += 2)
4400     if (!isUndefOrEqual(Mask[i], i) ||
4401         !isUndefOrEqual(Mask[i+1], i))
4402       return false;
4403
4404   return true;
4405 }
4406
4407 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4408 /// specifies a shuffle of elements that is suitable for input to 256-bit
4409 /// version of MOVDDUP.
4410 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4411   if (!HasFp256 || !VT.is256BitVector())
4412     return false;
4413
4414   unsigned NumElts = VT.getVectorNumElements();
4415   if (NumElts != 4)
4416     return false;
4417
4418   for (unsigned i = 0; i != NumElts/2; ++i)
4419     if (!isUndefOrEqual(Mask[i], 0))
4420       return false;
4421   for (unsigned i = NumElts/2; i != NumElts; ++i)
4422     if (!isUndefOrEqual(Mask[i], NumElts/2))
4423       return false;
4424   return true;
4425 }
4426
4427 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4428 /// specifies a shuffle of elements that is suitable for input to 128-bit
4429 /// version of MOVDDUP.
4430 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4431   if (!VT.is128BitVector())
4432     return false;
4433
4434   unsigned e = VT.getVectorNumElements() / 2;
4435   for (unsigned i = 0; i != e; ++i)
4436     if (!isUndefOrEqual(Mask[i], i))
4437       return false;
4438   for (unsigned i = 0; i != e; ++i)
4439     if (!isUndefOrEqual(Mask[e+i], i))
4440       return false;
4441   return true;
4442 }
4443
4444 /// isVEXTRACTIndex - Return true if the specified
4445 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4446 /// suitable for instruction that extract 128 or 256 bit vectors
4447 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4448   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4449   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4450     return false;
4451
4452   // The index should be aligned on a vecWidth-bit boundary.
4453   uint64_t Index =
4454     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4455
4456   MVT VT = N->getSimpleValueType(0);
4457   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4458   bool Result = (Index * ElSize) % vecWidth == 0;
4459
4460   return Result;
4461 }
4462
4463 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4464 /// operand specifies a subvector insert that is suitable for input to
4465 /// insertion of 128 or 256-bit subvectors
4466 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4467   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4468   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4469     return false;
4470   // The index should be aligned on a vecWidth-bit boundary.
4471   uint64_t Index =
4472     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4473
4474   MVT VT = N->getSimpleValueType(0);
4475   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4476   bool Result = (Index * ElSize) % vecWidth == 0;
4477
4478   return Result;
4479 }
4480
4481 bool X86::isVINSERT128Index(SDNode *N) {
4482   return isVINSERTIndex(N, 128);
4483 }
4484
4485 bool X86::isVINSERT256Index(SDNode *N) {
4486   return isVINSERTIndex(N, 256);
4487 }
4488
4489 bool X86::isVEXTRACT128Index(SDNode *N) {
4490   return isVEXTRACTIndex(N, 128);
4491 }
4492
4493 bool X86::isVEXTRACT256Index(SDNode *N) {
4494   return isVEXTRACTIndex(N, 256);
4495 }
4496
4497 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4498 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4499 /// Handles 128-bit and 256-bit.
4500 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4501   MVT VT = N->getSimpleValueType(0);
4502
4503   assert((VT.getSizeInBits() >= 128) &&
4504          "Unsupported vector type for PSHUF/SHUFP");
4505
4506   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4507   // independently on 128-bit lanes.
4508   unsigned NumElts = VT.getVectorNumElements();
4509   unsigned NumLanes = VT.getSizeInBits()/128;
4510   unsigned NumLaneElts = NumElts/NumLanes;
4511
4512   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4513          "Only supports 2, 4 or 8 elements per lane");
4514
4515   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4516   unsigned Mask = 0;
4517   for (unsigned i = 0; i != NumElts; ++i) {
4518     int Elt = N->getMaskElt(i);
4519     if (Elt < 0) continue;
4520     Elt &= NumLaneElts - 1;
4521     unsigned ShAmt = (i << Shift) % 8;
4522     Mask |= Elt << ShAmt;
4523   }
4524
4525   return Mask;
4526 }
4527
4528 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4529 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4530 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4531   MVT VT = N->getSimpleValueType(0);
4532
4533   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4534          "Unsupported vector type for PSHUFHW");
4535
4536   unsigned NumElts = VT.getVectorNumElements();
4537
4538   unsigned Mask = 0;
4539   for (unsigned l = 0; l != NumElts; l += 8) {
4540     // 8 nodes per lane, but we only care about the last 4.
4541     for (unsigned i = 0; i < 4; ++i) {
4542       int Elt = N->getMaskElt(l+i+4);
4543       if (Elt < 0) continue;
4544       Elt &= 0x3; // only 2-bits.
4545       Mask |= Elt << (i * 2);
4546     }
4547   }
4548
4549   return Mask;
4550 }
4551
4552 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4553 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4554 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4555   MVT VT = N->getSimpleValueType(0);
4556
4557   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4558          "Unsupported vector type for PSHUFHW");
4559
4560   unsigned NumElts = VT.getVectorNumElements();
4561
4562   unsigned Mask = 0;
4563   for (unsigned l = 0; l != NumElts; l += 8) {
4564     // 8 nodes per lane, but we only care about the first 4.
4565     for (unsigned i = 0; i < 4; ++i) {
4566       int Elt = N->getMaskElt(l+i);
4567       if (Elt < 0) continue;
4568       Elt &= 0x3; // only 2-bits
4569       Mask |= Elt << (i * 2);
4570     }
4571   }
4572
4573   return Mask;
4574 }
4575
4576 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4577 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4578 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4579   MVT VT = SVOp->getSimpleValueType(0);
4580   unsigned EltSize = VT.is512BitVector() ? 1 :
4581     VT.getVectorElementType().getSizeInBits() >> 3;
4582
4583   unsigned NumElts = VT.getVectorNumElements();
4584   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4585   unsigned NumLaneElts = NumElts/NumLanes;
4586
4587   int Val = 0;
4588   unsigned i;
4589   for (i = 0; i != NumElts; ++i) {
4590     Val = SVOp->getMaskElt(i);
4591     if (Val >= 0)
4592       break;
4593   }
4594   if (Val >= (int)NumElts)
4595     Val -= NumElts - NumLaneElts;
4596
4597   assert(Val - i > 0 && "PALIGNR imm should be positive");
4598   return (Val - i) * EltSize;
4599 }
4600
4601 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4602   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4603   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4604     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4605
4606   uint64_t Index =
4607     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4608
4609   MVT VecVT = N->getOperand(0).getSimpleValueType();
4610   MVT ElVT = VecVT.getVectorElementType();
4611
4612   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4613   return Index / NumElemsPerChunk;
4614 }
4615
4616 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4617   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4618   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4619     llvm_unreachable("Illegal insert subvector for VINSERT");
4620
4621   uint64_t Index =
4622     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4623
4624   MVT VecVT = N->getSimpleValueType(0);
4625   MVT ElVT = VecVT.getVectorElementType();
4626
4627   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4628   return Index / NumElemsPerChunk;
4629 }
4630
4631 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4632 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4633 /// and VINSERTI128 instructions.
4634 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4635   return getExtractVEXTRACTImmediate(N, 128);
4636 }
4637
4638 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4639 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4640 /// and VINSERTI64x4 instructions.
4641 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4642   return getExtractVEXTRACTImmediate(N, 256);
4643 }
4644
4645 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4646 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4647 /// and VINSERTI128 instructions.
4648 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4649   return getInsertVINSERTImmediate(N, 128);
4650 }
4651
4652 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4653 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4654 /// and VINSERTI64x4 instructions.
4655 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4656   return getInsertVINSERTImmediate(N, 256);
4657 }
4658
4659 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4660 /// constant +0.0.
4661 bool X86::isZeroNode(SDValue Elt) {
4662   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4663     return CN->isNullValue();
4664   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4665     return CFP->getValueAPF().isPosZero();
4666   return false;
4667 }
4668
4669 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4670 /// their permute mask.
4671 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4672                                     SelectionDAG &DAG) {
4673   MVT VT = SVOp->getSimpleValueType(0);
4674   unsigned NumElems = VT.getVectorNumElements();
4675   SmallVector<int, 8> MaskVec;
4676
4677   for (unsigned i = 0; i != NumElems; ++i) {
4678     int Idx = SVOp->getMaskElt(i);
4679     if (Idx >= 0) {
4680       if (Idx < (int)NumElems)
4681         Idx += NumElems;
4682       else
4683         Idx -= NumElems;
4684     }
4685     MaskVec.push_back(Idx);
4686   }
4687   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4688                               SVOp->getOperand(0), &MaskVec[0]);
4689 }
4690
4691 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4692 /// match movhlps. The lower half elements should come from upper half of
4693 /// V1 (and in order), and the upper half elements should come from the upper
4694 /// half of V2 (and in order).
4695 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4696   if (!VT.is128BitVector())
4697     return false;
4698   if (VT.getVectorNumElements() != 4)
4699     return false;
4700   for (unsigned i = 0, e = 2; i != e; ++i)
4701     if (!isUndefOrEqual(Mask[i], i+2))
4702       return false;
4703   for (unsigned i = 2; i != 4; ++i)
4704     if (!isUndefOrEqual(Mask[i], i+4))
4705       return false;
4706   return true;
4707 }
4708
4709 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4710 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4711 /// required.
4712 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4713   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4714     return false;
4715   N = N->getOperand(0).getNode();
4716   if (!ISD::isNON_EXTLoad(N))
4717     return false;
4718   if (LD)
4719     *LD = cast<LoadSDNode>(N);
4720   return true;
4721 }
4722
4723 // Test whether the given value is a vector value which will be legalized
4724 // into a load.
4725 static bool WillBeConstantPoolLoad(SDNode *N) {
4726   if (N->getOpcode() != ISD::BUILD_VECTOR)
4727     return false;
4728
4729   // Check for any non-constant elements.
4730   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4731     switch (N->getOperand(i).getNode()->getOpcode()) {
4732     case ISD::UNDEF:
4733     case ISD::ConstantFP:
4734     case ISD::Constant:
4735       break;
4736     default:
4737       return false;
4738     }
4739
4740   // Vectors of all-zeros and all-ones are materialized with special
4741   // instructions rather than being loaded.
4742   return !ISD::isBuildVectorAllZeros(N) &&
4743          !ISD::isBuildVectorAllOnes(N);
4744 }
4745
4746 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4747 /// match movlp{s|d}. The lower half elements should come from lower half of
4748 /// V1 (and in order), and the upper half elements should come from the upper
4749 /// half of V2 (and in order). And since V1 will become the source of the
4750 /// MOVLP, it must be either a vector load or a scalar load to vector.
4751 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4752                                ArrayRef<int> Mask, MVT VT) {
4753   if (!VT.is128BitVector())
4754     return false;
4755
4756   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4757     return false;
4758   // Is V2 is a vector load, don't do this transformation. We will try to use
4759   // load folding shufps op.
4760   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4761     return false;
4762
4763   unsigned NumElems = VT.getVectorNumElements();
4764
4765   if (NumElems != 2 && NumElems != 4)
4766     return false;
4767   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4768     if (!isUndefOrEqual(Mask[i], i))
4769       return false;
4770   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4771     if (!isUndefOrEqual(Mask[i], i+NumElems))
4772       return false;
4773   return true;
4774 }
4775
4776 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4777 /// all the same.
4778 static bool isSplatVector(SDNode *N) {
4779   if (N->getOpcode() != ISD::BUILD_VECTOR)
4780     return false;
4781
4782   SDValue SplatValue = N->getOperand(0);
4783   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4784     if (N->getOperand(i) != SplatValue)
4785       return false;
4786   return true;
4787 }
4788
4789 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4790 /// to an zero vector.
4791 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4792 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4793   SDValue V1 = N->getOperand(0);
4794   SDValue V2 = N->getOperand(1);
4795   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4796   for (unsigned i = 0; i != NumElems; ++i) {
4797     int Idx = N->getMaskElt(i);
4798     if (Idx >= (int)NumElems) {
4799       unsigned Opc = V2.getOpcode();
4800       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4801         continue;
4802       if (Opc != ISD::BUILD_VECTOR ||
4803           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4804         return false;
4805     } else if (Idx >= 0) {
4806       unsigned Opc = V1.getOpcode();
4807       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4808         continue;
4809       if (Opc != ISD::BUILD_VECTOR ||
4810           !X86::isZeroNode(V1.getOperand(Idx)))
4811         return false;
4812     }
4813   }
4814   return true;
4815 }
4816
4817 /// getZeroVector - Returns a vector of specified type with all zero elements.
4818 ///
4819 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4820                              SelectionDAG &DAG, SDLoc dl) {
4821   assert(VT.isVector() && "Expected a vector type");
4822
4823   // Always build SSE zero vectors as <4 x i32> bitcasted
4824   // to their dest type. This ensures they get CSE'd.
4825   SDValue Vec;
4826   if (VT.is128BitVector()) {  // SSE
4827     if (Subtarget->hasSSE2()) {  // SSE2
4828       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4829       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4830     } else { // SSE1
4831       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4832       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4833     }
4834   } else if (VT.is256BitVector()) { // AVX
4835     if (Subtarget->hasInt256()) { // AVX2
4836       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4837       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4838       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4839                         array_lengthof(Ops));
4840     } else {
4841       // 256-bit logic and arithmetic instructions in AVX are all
4842       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4843       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4844       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4845       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4846                         array_lengthof(Ops));
4847     }
4848   } else if (VT.is512BitVector()) { // AVX-512
4849       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4850       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4851                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4852       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4853   } else if (VT.getScalarType() == MVT::i1) {
4854     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4855     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4856     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4857                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4858     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4859                        Ops, VT.getVectorNumElements());
4860   } else
4861     llvm_unreachable("Unexpected vector type");
4862
4863   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4864 }
4865
4866 /// getOnesVector - Returns a vector of specified type with all bits set.
4867 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4868 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4869 /// Then bitcast to their original type, ensuring they get CSE'd.
4870 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4871                              SDLoc dl) {
4872   assert(VT.isVector() && "Expected a vector type");
4873
4874   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4875   SDValue Vec;
4876   if (VT.is256BitVector()) {
4877     if (HasInt256) { // AVX2
4878       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4879       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4880                         array_lengthof(Ops));
4881     } else { // AVX
4882       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4883       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4884     }
4885   } else if (VT.is128BitVector()) {
4886     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4887   } else
4888     llvm_unreachable("Unexpected vector type");
4889
4890   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4891 }
4892
4893 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4894 /// that point to V2 points to its first element.
4895 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4896   for (unsigned i = 0; i != NumElems; ++i) {
4897     if (Mask[i] > (int)NumElems) {
4898       Mask[i] = NumElems;
4899     }
4900   }
4901 }
4902
4903 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4904 /// operation of specified width.
4905 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4906                        SDValue V2) {
4907   unsigned NumElems = VT.getVectorNumElements();
4908   SmallVector<int, 8> Mask;
4909   Mask.push_back(NumElems);
4910   for (unsigned i = 1; i != NumElems; ++i)
4911     Mask.push_back(i);
4912   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4913 }
4914
4915 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4916 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4917                           SDValue V2) {
4918   unsigned NumElems = VT.getVectorNumElements();
4919   SmallVector<int, 8> Mask;
4920   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4921     Mask.push_back(i);
4922     Mask.push_back(i + NumElems);
4923   }
4924   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4925 }
4926
4927 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4928 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4929                           SDValue V2) {
4930   unsigned NumElems = VT.getVectorNumElements();
4931   SmallVector<int, 8> Mask;
4932   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4933     Mask.push_back(i + Half);
4934     Mask.push_back(i + NumElems + Half);
4935   }
4936   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4937 }
4938
4939 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4940 // a generic shuffle instruction because the target has no such instructions.
4941 // Generate shuffles which repeat i16 and i8 several times until they can be
4942 // represented by v4f32 and then be manipulated by target suported shuffles.
4943 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4944   MVT VT = V.getSimpleValueType();
4945   int NumElems = VT.getVectorNumElements();
4946   SDLoc dl(V);
4947
4948   while (NumElems > 4) {
4949     if (EltNo < NumElems/2) {
4950       V = getUnpackl(DAG, dl, VT, V, V);
4951     } else {
4952       V = getUnpackh(DAG, dl, VT, V, V);
4953       EltNo -= NumElems/2;
4954     }
4955     NumElems >>= 1;
4956   }
4957   return V;
4958 }
4959
4960 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4961 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4962   MVT VT = V.getSimpleValueType();
4963   SDLoc dl(V);
4964
4965   if (VT.is128BitVector()) {
4966     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4967     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4968     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4969                              &SplatMask[0]);
4970   } else if (VT.is256BitVector()) {
4971     // To use VPERMILPS to splat scalars, the second half of indicies must
4972     // refer to the higher part, which is a duplication of the lower one,
4973     // because VPERMILPS can only handle in-lane permutations.
4974     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4975                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4976
4977     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4978     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4979                              &SplatMask[0]);
4980   } else
4981     llvm_unreachable("Vector size not supported");
4982
4983   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4984 }
4985
4986 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4987 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4988   MVT SrcVT = SV->getSimpleValueType(0);
4989   SDValue V1 = SV->getOperand(0);
4990   SDLoc dl(SV);
4991
4992   int EltNo = SV->getSplatIndex();
4993   int NumElems = SrcVT.getVectorNumElements();
4994   bool Is256BitVec = SrcVT.is256BitVector();
4995
4996   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4997          "Unknown how to promote splat for type");
4998
4999   // Extract the 128-bit part containing the splat element and update
5000   // the splat element index when it refers to the higher register.
5001   if (Is256BitVec) {
5002     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5003     if (EltNo >= NumElems/2)
5004       EltNo -= NumElems/2;
5005   }
5006
5007   // All i16 and i8 vector types can't be used directly by a generic shuffle
5008   // instruction because the target has no such instruction. Generate shuffles
5009   // which repeat i16 and i8 several times until they fit in i32, and then can
5010   // be manipulated by target suported shuffles.
5011   MVT EltVT = SrcVT.getVectorElementType();
5012   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5013     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5014
5015   // Recreate the 256-bit vector and place the same 128-bit vector
5016   // into the low and high part. This is necessary because we want
5017   // to use VPERM* to shuffle the vectors
5018   if (Is256BitVec) {
5019     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5020   }
5021
5022   return getLegalSplat(DAG, V1, EltNo);
5023 }
5024
5025 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5026 /// vector of zero or undef vector.  This produces a shuffle where the low
5027 /// element of V2 is swizzled into the zero/undef vector, landing at element
5028 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5029 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5030                                            bool IsZero,
5031                                            const X86Subtarget *Subtarget,
5032                                            SelectionDAG &DAG) {
5033   MVT VT = V2.getSimpleValueType();
5034   SDValue V1 = IsZero
5035     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5036   unsigned NumElems = VT.getVectorNumElements();
5037   SmallVector<int, 16> MaskVec;
5038   for (unsigned i = 0; i != NumElems; ++i)
5039     // If this is the insertion idx, put the low elt of V2 here.
5040     MaskVec.push_back(i == Idx ? NumElems : i);
5041   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5042 }
5043
5044 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5045 /// target specific opcode. Returns true if the Mask could be calculated.
5046 /// Sets IsUnary to true if only uses one source.
5047 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5048                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5049   unsigned NumElems = VT.getVectorNumElements();
5050   SDValue ImmN;
5051
5052   IsUnary = false;
5053   switch(N->getOpcode()) {
5054   case X86ISD::SHUFP:
5055     ImmN = N->getOperand(N->getNumOperands()-1);
5056     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5057     break;
5058   case X86ISD::UNPCKH:
5059     DecodeUNPCKHMask(VT, Mask);
5060     break;
5061   case X86ISD::UNPCKL:
5062     DecodeUNPCKLMask(VT, Mask);
5063     break;
5064   case X86ISD::MOVHLPS:
5065     DecodeMOVHLPSMask(NumElems, Mask);
5066     break;
5067   case X86ISD::MOVLHPS:
5068     DecodeMOVLHPSMask(NumElems, Mask);
5069     break;
5070   case X86ISD::PALIGNR:
5071     ImmN = N->getOperand(N->getNumOperands()-1);
5072     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5073     break;
5074   case X86ISD::PSHUFD:
5075   case X86ISD::VPERMILP:
5076     ImmN = N->getOperand(N->getNumOperands()-1);
5077     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5078     IsUnary = true;
5079     break;
5080   case X86ISD::PSHUFHW:
5081     ImmN = N->getOperand(N->getNumOperands()-1);
5082     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5083     IsUnary = true;
5084     break;
5085   case X86ISD::PSHUFLW:
5086     ImmN = N->getOperand(N->getNumOperands()-1);
5087     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5088     IsUnary = true;
5089     break;
5090   case X86ISD::VPERMI:
5091     ImmN = N->getOperand(N->getNumOperands()-1);
5092     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5093     IsUnary = true;
5094     break;
5095   case X86ISD::MOVSS:
5096   case X86ISD::MOVSD: {
5097     // The index 0 always comes from the first element of the second source,
5098     // this is why MOVSS and MOVSD are used in the first place. The other
5099     // elements come from the other positions of the first source vector
5100     Mask.push_back(NumElems);
5101     for (unsigned i = 1; i != NumElems; ++i) {
5102       Mask.push_back(i);
5103     }
5104     break;
5105   }
5106   case X86ISD::VPERM2X128:
5107     ImmN = N->getOperand(N->getNumOperands()-1);
5108     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5109     if (Mask.empty()) return false;
5110     break;
5111   case X86ISD::MOVDDUP:
5112   case X86ISD::MOVLHPD:
5113   case X86ISD::MOVLPD:
5114   case X86ISD::MOVLPS:
5115   case X86ISD::MOVSHDUP:
5116   case X86ISD::MOVSLDUP:
5117     // Not yet implemented
5118     return false;
5119   default: llvm_unreachable("unknown target shuffle node");
5120   }
5121
5122   return true;
5123 }
5124
5125 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5126 /// element of the result of the vector shuffle.
5127 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5128                                    unsigned Depth) {
5129   if (Depth == 6)
5130     return SDValue();  // Limit search depth.
5131
5132   SDValue V = SDValue(N, 0);
5133   EVT VT = V.getValueType();
5134   unsigned Opcode = V.getOpcode();
5135
5136   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5137   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5138     int Elt = SV->getMaskElt(Index);
5139
5140     if (Elt < 0)
5141       return DAG.getUNDEF(VT.getVectorElementType());
5142
5143     unsigned NumElems = VT.getVectorNumElements();
5144     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5145                                          : SV->getOperand(1);
5146     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5147   }
5148
5149   // Recurse into target specific vector shuffles to find scalars.
5150   if (isTargetShuffle(Opcode)) {
5151     MVT ShufVT = V.getSimpleValueType();
5152     unsigned NumElems = ShufVT.getVectorNumElements();
5153     SmallVector<int, 16> ShuffleMask;
5154     bool IsUnary;
5155
5156     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5157       return SDValue();
5158
5159     int Elt = ShuffleMask[Index];
5160     if (Elt < 0)
5161       return DAG.getUNDEF(ShufVT.getVectorElementType());
5162
5163     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5164                                          : N->getOperand(1);
5165     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5166                                Depth+1);
5167   }
5168
5169   // Actual nodes that may contain scalar elements
5170   if (Opcode == ISD::BITCAST) {
5171     V = V.getOperand(0);
5172     EVT SrcVT = V.getValueType();
5173     unsigned NumElems = VT.getVectorNumElements();
5174
5175     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5176       return SDValue();
5177   }
5178
5179   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5180     return (Index == 0) ? V.getOperand(0)
5181                         : DAG.getUNDEF(VT.getVectorElementType());
5182
5183   if (V.getOpcode() == ISD::BUILD_VECTOR)
5184     return V.getOperand(Index);
5185
5186   return SDValue();
5187 }
5188
5189 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5190 /// shuffle operation which come from a consecutively from a zero. The
5191 /// search can start in two different directions, from left or right.
5192 /// We count undefs as zeros until PreferredNum is reached.
5193 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5194                                          unsigned NumElems, bool ZerosFromLeft,
5195                                          SelectionDAG &DAG,
5196                                          unsigned PreferredNum = -1U) {
5197   unsigned NumZeros = 0;
5198   for (unsigned i = 0; i != NumElems; ++i) {
5199     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5200     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5201     if (!Elt.getNode())
5202       break;
5203
5204     if (X86::isZeroNode(Elt))
5205       ++NumZeros;
5206     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5207       NumZeros = std::min(NumZeros + 1, PreferredNum);
5208     else
5209       break;
5210   }
5211
5212   return NumZeros;
5213 }
5214
5215 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5216 /// correspond consecutively to elements from one of the vector operands,
5217 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5218 static
5219 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5220                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5221                               unsigned NumElems, unsigned &OpNum) {
5222   bool SeenV1 = false;
5223   bool SeenV2 = false;
5224
5225   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5226     int Idx = SVOp->getMaskElt(i);
5227     // Ignore undef indicies
5228     if (Idx < 0)
5229       continue;
5230
5231     if (Idx < (int)NumElems)
5232       SeenV1 = true;
5233     else
5234       SeenV2 = true;
5235
5236     // Only accept consecutive elements from the same vector
5237     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5238       return false;
5239   }
5240
5241   OpNum = SeenV1 ? 0 : 1;
5242   return true;
5243 }
5244
5245 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5246 /// logical left shift of a vector.
5247 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5248                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5249   unsigned NumElems =
5250     SVOp->getSimpleValueType(0).getVectorNumElements();
5251   unsigned NumZeros = getNumOfConsecutiveZeros(
5252       SVOp, NumElems, false /* check zeros from right */, DAG,
5253       SVOp->getMaskElt(0));
5254   unsigned OpSrc;
5255
5256   if (!NumZeros)
5257     return false;
5258
5259   // Considering the elements in the mask that are not consecutive zeros,
5260   // check if they consecutively come from only one of the source vectors.
5261   //
5262   //               V1 = {X, A, B, C}     0
5263   //                         \  \  \    /
5264   //   vector_shuffle V1, V2 <1, 2, 3, X>
5265   //
5266   if (!isShuffleMaskConsecutive(SVOp,
5267             0,                   // Mask Start Index
5268             NumElems-NumZeros,   // Mask End Index(exclusive)
5269             NumZeros,            // Where to start looking in the src vector
5270             NumElems,            // Number of elements in vector
5271             OpSrc))              // Which source operand ?
5272     return false;
5273
5274   isLeft = false;
5275   ShAmt = NumZeros;
5276   ShVal = SVOp->getOperand(OpSrc);
5277   return true;
5278 }
5279
5280 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5281 /// logical left shift of a vector.
5282 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5283                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5284   unsigned NumElems =
5285     SVOp->getSimpleValueType(0).getVectorNumElements();
5286   unsigned NumZeros = getNumOfConsecutiveZeros(
5287       SVOp, NumElems, true /* check zeros from left */, DAG,
5288       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5289   unsigned OpSrc;
5290
5291   if (!NumZeros)
5292     return false;
5293
5294   // Considering the elements in the mask that are not consecutive zeros,
5295   // check if they consecutively come from only one of the source vectors.
5296   //
5297   //                           0    { A, B, X, X } = V2
5298   //                          / \    /  /
5299   //   vector_shuffle V1, V2 <X, X, 4, 5>
5300   //
5301   if (!isShuffleMaskConsecutive(SVOp,
5302             NumZeros,     // Mask Start Index
5303             NumElems,     // Mask End Index(exclusive)
5304             0,            // Where to start looking in the src vector
5305             NumElems,     // Number of elements in vector
5306             OpSrc))       // Which source operand ?
5307     return false;
5308
5309   isLeft = true;
5310   ShAmt = NumZeros;
5311   ShVal = SVOp->getOperand(OpSrc);
5312   return true;
5313 }
5314
5315 /// isVectorShift - Returns true if the shuffle can be implemented as a
5316 /// logical left or right shift of a vector.
5317 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5318                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5319   // Although the logic below support any bitwidth size, there are no
5320   // shift instructions which handle more than 128-bit vectors.
5321   if (!SVOp->getSimpleValueType(0).is128BitVector())
5322     return false;
5323
5324   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5325       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5326     return true;
5327
5328   return false;
5329 }
5330
5331 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5332 ///
5333 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5334                                        unsigned NumNonZero, unsigned NumZero,
5335                                        SelectionDAG &DAG,
5336                                        const X86Subtarget* Subtarget,
5337                                        const TargetLowering &TLI) {
5338   if (NumNonZero > 8)
5339     return SDValue();
5340
5341   SDLoc dl(Op);
5342   SDValue V;
5343   bool First = true;
5344   for (unsigned i = 0; i < 16; ++i) {
5345     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5346     if (ThisIsNonZero && First) {
5347       if (NumZero)
5348         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5349       else
5350         V = DAG.getUNDEF(MVT::v8i16);
5351       First = false;
5352     }
5353
5354     if ((i & 1) != 0) {
5355       SDValue ThisElt, LastElt;
5356       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5357       if (LastIsNonZero) {
5358         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5359                               MVT::i16, Op.getOperand(i-1));
5360       }
5361       if (ThisIsNonZero) {
5362         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5363         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5364                               ThisElt, DAG.getConstant(8, MVT::i8));
5365         if (LastIsNonZero)
5366           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5367       } else
5368         ThisElt = LastElt;
5369
5370       if (ThisElt.getNode())
5371         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5372                         DAG.getIntPtrConstant(i/2));
5373     }
5374   }
5375
5376   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5377 }
5378
5379 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5380 ///
5381 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5382                                      unsigned NumNonZero, unsigned NumZero,
5383                                      SelectionDAG &DAG,
5384                                      const X86Subtarget* Subtarget,
5385                                      const TargetLowering &TLI) {
5386   if (NumNonZero > 4)
5387     return SDValue();
5388
5389   SDLoc dl(Op);
5390   SDValue V;
5391   bool First = true;
5392   for (unsigned i = 0; i < 8; ++i) {
5393     bool isNonZero = (NonZeros & (1 << i)) != 0;
5394     if (isNonZero) {
5395       if (First) {
5396         if (NumZero)
5397           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5398         else
5399           V = DAG.getUNDEF(MVT::v8i16);
5400         First = false;
5401       }
5402       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5403                       MVT::v8i16, V, Op.getOperand(i),
5404                       DAG.getIntPtrConstant(i));
5405     }
5406   }
5407
5408   return V;
5409 }
5410
5411 /// getVShift - Return a vector logical shift node.
5412 ///
5413 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5414                          unsigned NumBits, SelectionDAG &DAG,
5415                          const TargetLowering &TLI, SDLoc dl) {
5416   assert(VT.is128BitVector() && "Unknown type for VShift");
5417   EVT ShVT = MVT::v2i64;
5418   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5419   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5420   return DAG.getNode(ISD::BITCAST, dl, VT,
5421                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5422                              DAG.getConstant(NumBits,
5423                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5424 }
5425
5426 static SDValue
5427 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5428
5429   // Check if the scalar load can be widened into a vector load. And if
5430   // the address is "base + cst" see if the cst can be "absorbed" into
5431   // the shuffle mask.
5432   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5433     SDValue Ptr = LD->getBasePtr();
5434     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5435       return SDValue();
5436     EVT PVT = LD->getValueType(0);
5437     if (PVT != MVT::i32 && PVT != MVT::f32)
5438       return SDValue();
5439
5440     int FI = -1;
5441     int64_t Offset = 0;
5442     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5443       FI = FINode->getIndex();
5444       Offset = 0;
5445     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5446                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5447       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5448       Offset = Ptr.getConstantOperandVal(1);
5449       Ptr = Ptr.getOperand(0);
5450     } else {
5451       return SDValue();
5452     }
5453
5454     // FIXME: 256-bit vector instructions don't require a strict alignment,
5455     // improve this code to support it better.
5456     unsigned RequiredAlign = VT.getSizeInBits()/8;
5457     SDValue Chain = LD->getChain();
5458     // Make sure the stack object alignment is at least 16 or 32.
5459     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5460     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5461       if (MFI->isFixedObjectIndex(FI)) {
5462         // Can't change the alignment. FIXME: It's possible to compute
5463         // the exact stack offset and reference FI + adjust offset instead.
5464         // If someone *really* cares about this. That's the way to implement it.
5465         return SDValue();
5466       } else {
5467         MFI->setObjectAlignment(FI, RequiredAlign);
5468       }
5469     }
5470
5471     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5472     // Ptr + (Offset & ~15).
5473     if (Offset < 0)
5474       return SDValue();
5475     if ((Offset % RequiredAlign) & 3)
5476       return SDValue();
5477     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5478     if (StartOffset)
5479       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5480                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5481
5482     int EltNo = (Offset - StartOffset) >> 2;
5483     unsigned NumElems = VT.getVectorNumElements();
5484
5485     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5486     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5487                              LD->getPointerInfo().getWithOffset(StartOffset),
5488                              false, false, false, 0);
5489
5490     SmallVector<int, 8> Mask;
5491     for (unsigned i = 0; i != NumElems; ++i)
5492       Mask.push_back(EltNo);
5493
5494     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5495   }
5496
5497   return SDValue();
5498 }
5499
5500 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5501 /// vector of type 'VT', see if the elements can be replaced by a single large
5502 /// load which has the same value as a build_vector whose operands are 'elts'.
5503 ///
5504 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5505 ///
5506 /// FIXME: we'd also like to handle the case where the last elements are zero
5507 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5508 /// There's even a handy isZeroNode for that purpose.
5509 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5510                                         SDLoc &DL, SelectionDAG &DAG,
5511                                         bool isAfterLegalize) {
5512   EVT EltVT = VT.getVectorElementType();
5513   unsigned NumElems = Elts.size();
5514
5515   LoadSDNode *LDBase = nullptr;
5516   unsigned LastLoadedElt = -1U;
5517
5518   // For each element in the initializer, see if we've found a load or an undef.
5519   // If we don't find an initial load element, or later load elements are
5520   // non-consecutive, bail out.
5521   for (unsigned i = 0; i < NumElems; ++i) {
5522     SDValue Elt = Elts[i];
5523
5524     if (!Elt.getNode() ||
5525         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5526       return SDValue();
5527     if (!LDBase) {
5528       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5529         return SDValue();
5530       LDBase = cast<LoadSDNode>(Elt.getNode());
5531       LastLoadedElt = i;
5532       continue;
5533     }
5534     if (Elt.getOpcode() == ISD::UNDEF)
5535       continue;
5536
5537     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5538     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5539       return SDValue();
5540     LastLoadedElt = i;
5541   }
5542
5543   // If we have found an entire vector of loads and undefs, then return a large
5544   // load of the entire vector width starting at the base pointer.  If we found
5545   // consecutive loads for the low half, generate a vzext_load node.
5546   if (LastLoadedElt == NumElems - 1) {
5547
5548     if (isAfterLegalize &&
5549         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5550       return SDValue();
5551
5552     SDValue NewLd = SDValue();
5553
5554     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5555       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5556                           LDBase->getPointerInfo(),
5557                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5558                           LDBase->isInvariant(), 0);
5559     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5560                         LDBase->getPointerInfo(),
5561                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5562                         LDBase->isInvariant(), LDBase->getAlignment());
5563
5564     if (LDBase->hasAnyUseOfValue(1)) {
5565       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5566                                      SDValue(LDBase, 1),
5567                                      SDValue(NewLd.getNode(), 1));
5568       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5569       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5570                              SDValue(NewLd.getNode(), 1));
5571     }
5572
5573     return NewLd;
5574   }
5575   if (NumElems == 4 && LastLoadedElt == 1 &&
5576       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5577     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5578     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5579     SDValue ResNode =
5580         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5581                                 array_lengthof(Ops), MVT::i64,
5582                                 LDBase->getPointerInfo(),
5583                                 LDBase->getAlignment(),
5584                                 false/*isVolatile*/, true/*ReadMem*/,
5585                                 false/*WriteMem*/);
5586
5587     // Make sure the newly-created LOAD is in the same position as LDBase in
5588     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5589     // update uses of LDBase's output chain to use the TokenFactor.
5590     if (LDBase->hasAnyUseOfValue(1)) {
5591       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5592                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5593       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5594       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5595                              SDValue(ResNode.getNode(), 1));
5596     }
5597
5598     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5599   }
5600   return SDValue();
5601 }
5602
5603 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5604 /// to generate a splat value for the following cases:
5605 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5606 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5607 /// a scalar load, or a constant.
5608 /// The VBROADCAST node is returned when a pattern is found,
5609 /// or SDValue() otherwise.
5610 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5611                                     SelectionDAG &DAG) {
5612   if (!Subtarget->hasFp256())
5613     return SDValue();
5614
5615   MVT VT = Op.getSimpleValueType();
5616   SDLoc dl(Op);
5617
5618   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5619          "Unsupported vector type for broadcast.");
5620
5621   SDValue Ld;
5622   bool ConstSplatVal;
5623
5624   switch (Op.getOpcode()) {
5625     default:
5626       // Unknown pattern found.
5627       return SDValue();
5628
5629     case ISD::BUILD_VECTOR: {
5630       // The BUILD_VECTOR node must be a splat.
5631       if (!isSplatVector(Op.getNode()))
5632         return SDValue();
5633
5634       Ld = Op.getOperand(0);
5635       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5636                      Ld.getOpcode() == ISD::ConstantFP);
5637
5638       // The suspected load node has several users. Make sure that all
5639       // of its users are from the BUILD_VECTOR node.
5640       // Constants may have multiple users.
5641       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5642         return SDValue();
5643       break;
5644     }
5645
5646     case ISD::VECTOR_SHUFFLE: {
5647       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5648
5649       // Shuffles must have a splat mask where the first element is
5650       // broadcasted.
5651       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5652         return SDValue();
5653
5654       SDValue Sc = Op.getOperand(0);
5655       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5656           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5657
5658         if (!Subtarget->hasInt256())
5659           return SDValue();
5660
5661         // Use the register form of the broadcast instruction available on AVX2.
5662         if (VT.getSizeInBits() >= 256)
5663           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5664         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5665       }
5666
5667       Ld = Sc.getOperand(0);
5668       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5669                        Ld.getOpcode() == ISD::ConstantFP);
5670
5671       // The scalar_to_vector node and the suspected
5672       // load node must have exactly one user.
5673       // Constants may have multiple users.
5674
5675       // AVX-512 has register version of the broadcast
5676       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5677         Ld.getValueType().getSizeInBits() >= 32;
5678       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5679           !hasRegVer))
5680         return SDValue();
5681       break;
5682     }
5683   }
5684
5685   bool IsGE256 = (VT.getSizeInBits() >= 256);
5686
5687   // Handle the broadcasting a single constant scalar from the constant pool
5688   // into a vector. On Sandybridge it is still better to load a constant vector
5689   // from the constant pool and not to broadcast it from a scalar.
5690   if (ConstSplatVal && Subtarget->hasInt256()) {
5691     EVT CVT = Ld.getValueType();
5692     assert(!CVT.isVector() && "Must not broadcast a vector type");
5693     unsigned ScalarSize = CVT.getSizeInBits();
5694
5695     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5696       const Constant *C = nullptr;
5697       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5698         C = CI->getConstantIntValue();
5699       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5700         C = CF->getConstantFPValue();
5701
5702       assert(C && "Invalid constant type");
5703
5704       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5705       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5706       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5707       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5708                        MachinePointerInfo::getConstantPool(),
5709                        false, false, false, Alignment);
5710
5711       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5712     }
5713   }
5714
5715   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5716   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5717
5718   // Handle AVX2 in-register broadcasts.
5719   if (!IsLoad && Subtarget->hasInt256() &&
5720       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5721     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5722
5723   // The scalar source must be a normal load.
5724   if (!IsLoad)
5725     return SDValue();
5726
5727   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5728     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5729
5730   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5731   // double since there is no vbroadcastsd xmm
5732   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5733     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5734       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5735   }
5736
5737   // Unsupported broadcast.
5738   return SDValue();
5739 }
5740
5741 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5742 /// underlying vector and index.
5743 ///
5744 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5745 /// index.
5746 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5747                                          SDValue ExtIdx) {
5748   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5749   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5750     return Idx;
5751
5752   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5753   // lowered this:
5754   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5755   // to:
5756   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5757   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5758   //                           undef)
5759   //                       Constant<0>)
5760   // In this case the vector is the extract_subvector expression and the index
5761   // is 2, as specified by the shuffle.
5762   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5763   SDValue ShuffleVec = SVOp->getOperand(0);
5764   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5765   assert(ShuffleVecVT.getVectorElementType() ==
5766          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5767
5768   int ShuffleIdx = SVOp->getMaskElt(Idx);
5769   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5770     ExtractedFromVec = ShuffleVec;
5771     return ShuffleIdx;
5772   }
5773   return Idx;
5774 }
5775
5776 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5777   MVT VT = Op.getSimpleValueType();
5778
5779   // Skip if insert_vec_elt is not supported.
5780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5781   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5782     return SDValue();
5783
5784   SDLoc DL(Op);
5785   unsigned NumElems = Op.getNumOperands();
5786
5787   SDValue VecIn1;
5788   SDValue VecIn2;
5789   SmallVector<unsigned, 4> InsertIndices;
5790   SmallVector<int, 8> Mask(NumElems, -1);
5791
5792   for (unsigned i = 0; i != NumElems; ++i) {
5793     unsigned Opc = Op.getOperand(i).getOpcode();
5794
5795     if (Opc == ISD::UNDEF)
5796       continue;
5797
5798     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5799       // Quit if more than 1 elements need inserting.
5800       if (InsertIndices.size() > 1)
5801         return SDValue();
5802
5803       InsertIndices.push_back(i);
5804       continue;
5805     }
5806
5807     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5808     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5809     // Quit if non-constant index.
5810     if (!isa<ConstantSDNode>(ExtIdx))
5811       return SDValue();
5812     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5813
5814     // Quit if extracted from vector of different type.
5815     if (ExtractedFromVec.getValueType() != VT)
5816       return SDValue();
5817
5818     if (!VecIn1.getNode())
5819       VecIn1 = ExtractedFromVec;
5820     else if (VecIn1 != ExtractedFromVec) {
5821       if (!VecIn2.getNode())
5822         VecIn2 = ExtractedFromVec;
5823       else if (VecIn2 != ExtractedFromVec)
5824         // Quit if more than 2 vectors to shuffle
5825         return SDValue();
5826     }
5827
5828     if (ExtractedFromVec == VecIn1)
5829       Mask[i] = Idx;
5830     else if (ExtractedFromVec == VecIn2)
5831       Mask[i] = Idx + NumElems;
5832   }
5833
5834   if (!VecIn1.getNode())
5835     return SDValue();
5836
5837   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5838   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5839   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5840     unsigned Idx = InsertIndices[i];
5841     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5842                      DAG.getIntPtrConstant(Idx));
5843   }
5844
5845   return NV;
5846 }
5847
5848 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5849 SDValue
5850 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5851
5852   MVT VT = Op.getSimpleValueType();
5853   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5854          "Unexpected type in LowerBUILD_VECTORvXi1!");
5855
5856   SDLoc dl(Op);
5857   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5858     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5859     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5860                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5861     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5862                        Ops, VT.getVectorNumElements());
5863   }
5864
5865   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5866     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5867     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5868                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5869     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5870                        Ops, VT.getVectorNumElements());
5871   }
5872
5873   bool AllContants = true;
5874   uint64_t Immediate = 0;
5875   int NonConstIdx = -1;
5876   bool IsSplat = true;
5877   unsigned NumNonConsts = 0;
5878   unsigned NumConsts = 0;
5879   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5880     SDValue In = Op.getOperand(idx);
5881     if (In.getOpcode() == ISD::UNDEF)
5882       continue;
5883     if (!isa<ConstantSDNode>(In)) {
5884       AllContants = false;
5885       NonConstIdx = idx;
5886       NumNonConsts++;
5887     }
5888     else {
5889       NumConsts++;
5890       if (cast<ConstantSDNode>(In)->getZExtValue())
5891       Immediate |= (1ULL << idx);
5892     }
5893     if (In != Op.getOperand(0))
5894       IsSplat = false;
5895   }
5896
5897   if (AllContants) {
5898     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5899       DAG.getConstant(Immediate, MVT::i16));
5900     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5901                        DAG.getIntPtrConstant(0));
5902   }
5903
5904   if (NumNonConsts == 1 && NonConstIdx != 0) {
5905     SDValue DstVec;
5906     if (NumConsts) {
5907       SDValue VecAsImm = DAG.getConstant(Immediate,
5908                                          MVT::getIntegerVT(VT.getSizeInBits()));
5909       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5910     }
5911     else 
5912       DstVec = DAG.getUNDEF(VT);
5913     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5914                        Op.getOperand(NonConstIdx),
5915                        DAG.getIntPtrConstant(NonConstIdx));
5916   }
5917   if (!IsSplat && (NonConstIdx != 0))
5918     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5919   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5920   SDValue Select;
5921   if (IsSplat)
5922     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5923                           DAG.getConstant(-1, SelectVT),
5924                           DAG.getConstant(0, SelectVT));
5925   else
5926     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5927                          DAG.getConstant((Immediate | 1), SelectVT),
5928                          DAG.getConstant(Immediate, SelectVT));
5929   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5930 }
5931
5932 SDValue
5933 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5934   SDLoc dl(Op);
5935
5936   MVT VT = Op.getSimpleValueType();
5937   MVT ExtVT = VT.getVectorElementType();
5938   unsigned NumElems = Op.getNumOperands();
5939
5940   // Generate vectors for predicate vectors.
5941   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5942     return LowerBUILD_VECTORvXi1(Op, DAG);
5943
5944   // Vectors containing all zeros can be matched by pxor and xorps later
5945   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5946     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5947     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5948     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5949       return Op;
5950
5951     return getZeroVector(VT, Subtarget, DAG, dl);
5952   }
5953
5954   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5955   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5956   // vpcmpeqd on 256-bit vectors.
5957   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5958     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5959       return Op;
5960
5961     if (!VT.is512BitVector())
5962       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5963   }
5964
5965   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5966   if (Broadcast.getNode())
5967     return Broadcast;
5968
5969   unsigned EVTBits = ExtVT.getSizeInBits();
5970
5971   unsigned NumZero  = 0;
5972   unsigned NumNonZero = 0;
5973   unsigned NonZeros = 0;
5974   bool IsAllConstants = true;
5975   SmallSet<SDValue, 8> Values;
5976   for (unsigned i = 0; i < NumElems; ++i) {
5977     SDValue Elt = Op.getOperand(i);
5978     if (Elt.getOpcode() == ISD::UNDEF)
5979       continue;
5980     Values.insert(Elt);
5981     if (Elt.getOpcode() != ISD::Constant &&
5982         Elt.getOpcode() != ISD::ConstantFP)
5983       IsAllConstants = false;
5984     if (X86::isZeroNode(Elt))
5985       NumZero++;
5986     else {
5987       NonZeros |= (1 << i);
5988       NumNonZero++;
5989     }
5990   }
5991
5992   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5993   if (NumNonZero == 0)
5994     return DAG.getUNDEF(VT);
5995
5996   // Special case for single non-zero, non-undef, element.
5997   if (NumNonZero == 1) {
5998     unsigned Idx = countTrailingZeros(NonZeros);
5999     SDValue Item = Op.getOperand(Idx);
6000
6001     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6002     // the value are obviously zero, truncate the value to i32 and do the
6003     // insertion that way.  Only do this if the value is non-constant or if the
6004     // value is a constant being inserted into element 0.  It is cheaper to do
6005     // a constant pool load than it is to do a movd + shuffle.
6006     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6007         (!IsAllConstants || Idx == 0)) {
6008       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6009         // Handle SSE only.
6010         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6011         EVT VecVT = MVT::v4i32;
6012         unsigned VecElts = 4;
6013
6014         // Truncate the value (which may itself be a constant) to i32, and
6015         // convert it to a vector with movd (S2V+shuffle to zero extend).
6016         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6017         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6018         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6019
6020         // Now we have our 32-bit value zero extended in the low element of
6021         // a vector.  If Idx != 0, swizzle it into place.
6022         if (Idx != 0) {
6023           SmallVector<int, 4> Mask;
6024           Mask.push_back(Idx);
6025           for (unsigned i = 1; i != VecElts; ++i)
6026             Mask.push_back(i);
6027           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6028                                       &Mask[0]);
6029         }
6030         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6031       }
6032     }
6033
6034     // If we have a constant or non-constant insertion into the low element of
6035     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6036     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6037     // depending on what the source datatype is.
6038     if (Idx == 0) {
6039       if (NumZero == 0)
6040         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6041
6042       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6043           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6044         if (VT.is256BitVector() || VT.is512BitVector()) {
6045           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6046           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6047                              Item, DAG.getIntPtrConstant(0));
6048         }
6049         assert(VT.is128BitVector() && "Expected an SSE value type!");
6050         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6051         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6052         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6053       }
6054
6055       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6056         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6057         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6058         if (VT.is256BitVector()) {
6059           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6060           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6061         } else {
6062           assert(VT.is128BitVector() && "Expected an SSE value type!");
6063           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6064         }
6065         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6066       }
6067     }
6068
6069     // Is it a vector logical left shift?
6070     if (NumElems == 2 && Idx == 1 &&
6071         X86::isZeroNode(Op.getOperand(0)) &&
6072         !X86::isZeroNode(Op.getOperand(1))) {
6073       unsigned NumBits = VT.getSizeInBits();
6074       return getVShift(true, VT,
6075                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6076                                    VT, Op.getOperand(1)),
6077                        NumBits/2, DAG, *this, dl);
6078     }
6079
6080     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6081       return SDValue();
6082
6083     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6084     // is a non-constant being inserted into an element other than the low one,
6085     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6086     // movd/movss) to move this into the low element, then shuffle it into
6087     // place.
6088     if (EVTBits == 32) {
6089       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6090
6091       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6092       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6093       SmallVector<int, 8> MaskVec;
6094       for (unsigned i = 0; i != NumElems; ++i)
6095         MaskVec.push_back(i == Idx ? 0 : 1);
6096       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6097     }
6098   }
6099
6100   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6101   if (Values.size() == 1) {
6102     if (EVTBits == 32) {
6103       // Instead of a shuffle like this:
6104       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6105       // Check if it's possible to issue this instead.
6106       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6107       unsigned Idx = countTrailingZeros(NonZeros);
6108       SDValue Item = Op.getOperand(Idx);
6109       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6110         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6111     }
6112     return SDValue();
6113   }
6114
6115   // A vector full of immediates; various special cases are already
6116   // handled, so this is best done with a single constant-pool load.
6117   if (IsAllConstants)
6118     return SDValue();
6119
6120   // For AVX-length vectors, build the individual 128-bit pieces and use
6121   // shuffles to put them in place.
6122   if (VT.is256BitVector() || VT.is512BitVector()) {
6123     SmallVector<SDValue, 64> V;
6124     for (unsigned i = 0; i != NumElems; ++i)
6125       V.push_back(Op.getOperand(i));
6126
6127     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6128
6129     // Build both the lower and upper subvector.
6130     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6131     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6132                                 NumElems/2);
6133
6134     // Recreate the wider vector with the lower and upper part.
6135     if (VT.is256BitVector())
6136       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6137     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6138   }
6139
6140   // Let legalizer expand 2-wide build_vectors.
6141   if (EVTBits == 64) {
6142     if (NumNonZero == 1) {
6143       // One half is zero or undef.
6144       unsigned Idx = countTrailingZeros(NonZeros);
6145       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6146                                  Op.getOperand(Idx));
6147       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6148     }
6149     return SDValue();
6150   }
6151
6152   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6153   if (EVTBits == 8 && NumElems == 16) {
6154     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6155                                         Subtarget, *this);
6156     if (V.getNode()) return V;
6157   }
6158
6159   if (EVTBits == 16 && NumElems == 8) {
6160     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6161                                       Subtarget, *this);
6162     if (V.getNode()) return V;
6163   }
6164
6165   // If element VT is == 32 bits, turn it into a number of shuffles.
6166   SmallVector<SDValue, 8> V(NumElems);
6167   if (NumElems == 4 && NumZero > 0) {
6168     for (unsigned i = 0; i < 4; ++i) {
6169       bool isZero = !(NonZeros & (1 << i));
6170       if (isZero)
6171         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6172       else
6173         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6174     }
6175
6176     for (unsigned i = 0; i < 2; ++i) {
6177       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6178         default: break;
6179         case 0:
6180           V[i] = V[i*2];  // Must be a zero vector.
6181           break;
6182         case 1:
6183           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6184           break;
6185         case 2:
6186           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6187           break;
6188         case 3:
6189           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6190           break;
6191       }
6192     }
6193
6194     bool Reverse1 = (NonZeros & 0x3) == 2;
6195     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6196     int MaskVec[] = {
6197       Reverse1 ? 1 : 0,
6198       Reverse1 ? 0 : 1,
6199       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6200       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6201     };
6202     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6203   }
6204
6205   if (Values.size() > 1 && VT.is128BitVector()) {
6206     // Check for a build vector of consecutive loads.
6207     for (unsigned i = 0; i < NumElems; ++i)
6208       V[i] = Op.getOperand(i);
6209
6210     // Check for elements which are consecutive loads.
6211     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6212     if (LD.getNode())
6213       return LD;
6214
6215     // Check for a build vector from mostly shuffle plus few inserting.
6216     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6217     if (Sh.getNode())
6218       return Sh;
6219
6220     // For SSE 4.1, use insertps to put the high elements into the low element.
6221     if (getSubtarget()->hasSSE41()) {
6222       SDValue Result;
6223       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6224         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6225       else
6226         Result = DAG.getUNDEF(VT);
6227
6228       for (unsigned i = 1; i < NumElems; ++i) {
6229         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6230         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6231                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6232       }
6233       return Result;
6234     }
6235
6236     // Otherwise, expand into a number of unpckl*, start by extending each of
6237     // our (non-undef) elements to the full vector width with the element in the
6238     // bottom slot of the vector (which generates no code for SSE).
6239     for (unsigned i = 0; i < NumElems; ++i) {
6240       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6241         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6242       else
6243         V[i] = DAG.getUNDEF(VT);
6244     }
6245
6246     // Next, we iteratively mix elements, e.g. for v4f32:
6247     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6248     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6249     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6250     unsigned EltStride = NumElems >> 1;
6251     while (EltStride != 0) {
6252       for (unsigned i = 0; i < EltStride; ++i) {
6253         // If V[i+EltStride] is undef and this is the first round of mixing,
6254         // then it is safe to just drop this shuffle: V[i] is already in the
6255         // right place, the one element (since it's the first round) being
6256         // inserted as undef can be dropped.  This isn't safe for successive
6257         // rounds because they will permute elements within both vectors.
6258         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6259             EltStride == NumElems/2)
6260           continue;
6261
6262         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6263       }
6264       EltStride >>= 1;
6265     }
6266     return V[0];
6267   }
6268   return SDValue();
6269 }
6270
6271 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6272 // to create 256-bit vectors from two other 128-bit ones.
6273 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6274   SDLoc dl(Op);
6275   MVT ResVT = Op.getSimpleValueType();
6276
6277   assert((ResVT.is256BitVector() ||
6278           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6279
6280   SDValue V1 = Op.getOperand(0);
6281   SDValue V2 = Op.getOperand(1);
6282   unsigned NumElems = ResVT.getVectorNumElements();
6283   if(ResVT.is256BitVector())
6284     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6285
6286   if (Op.getNumOperands() == 4) {
6287     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6288                                 ResVT.getVectorNumElements()/2);
6289     SDValue V3 = Op.getOperand(2);
6290     SDValue V4 = Op.getOperand(3);
6291     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6292       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6293   }
6294   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6295 }
6296
6297 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6298   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6299   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6300          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6301           Op.getNumOperands() == 4)));
6302
6303   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6304   // from two other 128-bit ones.
6305
6306   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6307   return LowerAVXCONCAT_VECTORS(Op, DAG);
6308 }
6309
6310 // Try to lower a shuffle node into a simple blend instruction.
6311 static SDValue
6312 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6313                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6314   SDValue V1 = SVOp->getOperand(0);
6315   SDValue V2 = SVOp->getOperand(1);
6316   SDLoc dl(SVOp);
6317   MVT VT = SVOp->getSimpleValueType(0);
6318   MVT EltVT = VT.getVectorElementType();
6319   unsigned NumElems = VT.getVectorNumElements();
6320
6321   // There is no blend with immediate in AVX-512.
6322   if (VT.is512BitVector())
6323     return SDValue();
6324
6325   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6326     return SDValue();
6327   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6328     return SDValue();
6329
6330   // Check the mask for BLEND and build the value.
6331   unsigned MaskValue = 0;
6332   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6333   unsigned NumLanes = (NumElems-1)/8 + 1;
6334   unsigned NumElemsInLane = NumElems / NumLanes;
6335
6336   // Blend for v16i16 should be symetric for the both lanes.
6337   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6338
6339     int SndLaneEltIdx = (NumLanes == 2) ?
6340       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6341     int EltIdx = SVOp->getMaskElt(i);
6342
6343     if ((EltIdx < 0 || EltIdx == (int)i) &&
6344         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6345       continue;
6346
6347     if (((unsigned)EltIdx == (i + NumElems)) &&
6348         (SndLaneEltIdx < 0 ||
6349          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6350       MaskValue |= (1<<i);
6351     else
6352       return SDValue();
6353   }
6354
6355   // Convert i32 vectors to floating point if it is not AVX2.
6356   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6357   MVT BlendVT = VT;
6358   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6359     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6360                                NumElems);
6361     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6362     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6363   }
6364
6365   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6366                             DAG.getConstant(MaskValue, MVT::i32));
6367   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6368 }
6369
6370 /// In vector type \p VT, return true if the element at index \p InputIdx
6371 /// falls on a different 128-bit lane than \p OutputIdx.
6372 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6373                                      unsigned OutputIdx) {
6374   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6375   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6376 }
6377
6378 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6379 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6380 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6381 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6382 /// zero.
6383 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6384                          SelectionDAG &DAG) {
6385   MVT VT = V1.getSimpleValueType();
6386   assert(VT.is128BitVector() || VT.is256BitVector());
6387
6388   MVT EltVT = VT.getVectorElementType();
6389   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6390   unsigned NumElts = VT.getVectorNumElements();
6391
6392   SmallVector<SDValue, 32> PshufbMask;
6393   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6394     int InputIdx = MaskVals[OutputIdx];
6395     unsigned InputByteIdx;
6396
6397     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6398       InputByteIdx = 0x80;
6399     else {
6400       // Cross lane is not allowed.
6401       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6402         return SDValue();
6403       InputByteIdx = InputIdx * EltSizeInBytes;
6404       // Index is an byte offset within the 128-bit lane.
6405       InputByteIdx &= 0xf;
6406     }
6407
6408     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6409       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6410       if (InputByteIdx != 0x80)
6411         ++InputByteIdx;
6412     }
6413   }
6414
6415   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6416   if (ShufVT != VT)
6417     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6418   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6419                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6420                                  PshufbMask.data(), PshufbMask.size()));
6421 }
6422
6423 // v8i16 shuffles - Prefer shuffles in the following order:
6424 // 1. [all]   pshuflw, pshufhw, optional move
6425 // 2. [ssse3] 1 x pshufb
6426 // 3. [ssse3] 2 x pshufb + 1 x por
6427 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6428 static SDValue
6429 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6430                          SelectionDAG &DAG) {
6431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6432   SDValue V1 = SVOp->getOperand(0);
6433   SDValue V2 = SVOp->getOperand(1);
6434   SDLoc dl(SVOp);
6435   SmallVector<int, 8> MaskVals;
6436
6437   // Determine if more than 1 of the words in each of the low and high quadwords
6438   // of the result come from the same quadword of one of the two inputs.  Undef
6439   // mask values count as coming from any quadword, for better codegen.
6440   //
6441   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6442   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6443   unsigned LoQuad[] = { 0, 0, 0, 0 };
6444   unsigned HiQuad[] = { 0, 0, 0, 0 };
6445   // Indices of quads used.
6446   std::bitset<4> InputQuads;
6447   for (unsigned i = 0; i < 8; ++i) {
6448     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6449     int EltIdx = SVOp->getMaskElt(i);
6450     MaskVals.push_back(EltIdx);
6451     if (EltIdx < 0) {
6452       ++Quad[0];
6453       ++Quad[1];
6454       ++Quad[2];
6455       ++Quad[3];
6456       continue;
6457     }
6458     ++Quad[EltIdx / 4];
6459     InputQuads.set(EltIdx / 4);
6460   }
6461
6462   int BestLoQuad = -1;
6463   unsigned MaxQuad = 1;
6464   for (unsigned i = 0; i < 4; ++i) {
6465     if (LoQuad[i] > MaxQuad) {
6466       BestLoQuad = i;
6467       MaxQuad = LoQuad[i];
6468     }
6469   }
6470
6471   int BestHiQuad = -1;
6472   MaxQuad = 1;
6473   for (unsigned i = 0; i < 4; ++i) {
6474     if (HiQuad[i] > MaxQuad) {
6475       BestHiQuad = i;
6476       MaxQuad = HiQuad[i];
6477     }
6478   }
6479
6480   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6481   // of the two input vectors, shuffle them into one input vector so only a
6482   // single pshufb instruction is necessary. If there are more than 2 input
6483   // quads, disable the next transformation since it does not help SSSE3.
6484   bool V1Used = InputQuads[0] || InputQuads[1];
6485   bool V2Used = InputQuads[2] || InputQuads[3];
6486   if (Subtarget->hasSSSE3()) {
6487     if (InputQuads.count() == 2 && V1Used && V2Used) {
6488       BestLoQuad = InputQuads[0] ? 0 : 1;
6489       BestHiQuad = InputQuads[2] ? 2 : 3;
6490     }
6491     if (InputQuads.count() > 2) {
6492       BestLoQuad = -1;
6493       BestHiQuad = -1;
6494     }
6495   }
6496
6497   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6498   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6499   // words from all 4 input quadwords.
6500   SDValue NewV;
6501   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6502     int MaskV[] = {
6503       BestLoQuad < 0 ? 0 : BestLoQuad,
6504       BestHiQuad < 0 ? 1 : BestHiQuad
6505     };
6506     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6507                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6508                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6509     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6510
6511     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6512     // source words for the shuffle, to aid later transformations.
6513     bool AllWordsInNewV = true;
6514     bool InOrder[2] = { true, true };
6515     for (unsigned i = 0; i != 8; ++i) {
6516       int idx = MaskVals[i];
6517       if (idx != (int)i)
6518         InOrder[i/4] = false;
6519       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6520         continue;
6521       AllWordsInNewV = false;
6522       break;
6523     }
6524
6525     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6526     if (AllWordsInNewV) {
6527       for (int i = 0; i != 8; ++i) {
6528         int idx = MaskVals[i];
6529         if (idx < 0)
6530           continue;
6531         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6532         if ((idx != i) && idx < 4)
6533           pshufhw = false;
6534         if ((idx != i) && idx > 3)
6535           pshuflw = false;
6536       }
6537       V1 = NewV;
6538       V2Used = false;
6539       BestLoQuad = 0;
6540       BestHiQuad = 1;
6541     }
6542
6543     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6544     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6545     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6546       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6547       unsigned TargetMask = 0;
6548       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6549                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6550       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6551       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6552                              getShufflePSHUFLWImmediate(SVOp);
6553       V1 = NewV.getOperand(0);
6554       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6555     }
6556   }
6557
6558   // Promote splats to a larger type which usually leads to more efficient code.
6559   // FIXME: Is this true if pshufb is available?
6560   if (SVOp->isSplat())
6561     return PromoteSplat(SVOp, DAG);
6562
6563   // If we have SSSE3, and all words of the result are from 1 input vector,
6564   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6565   // is present, fall back to case 4.
6566   if (Subtarget->hasSSSE3()) {
6567     SmallVector<SDValue,16> pshufbMask;
6568
6569     // If we have elements from both input vectors, set the high bit of the
6570     // shuffle mask element to zero out elements that come from V2 in the V1
6571     // mask, and elements that come from V1 in the V2 mask, so that the two
6572     // results can be OR'd together.
6573     bool TwoInputs = V1Used && V2Used;
6574     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6575     if (!TwoInputs)
6576       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6577
6578     // Calculate the shuffle mask for the second input, shuffle it, and
6579     // OR it with the first shuffled input.
6580     CommuteVectorShuffleMask(MaskVals, 8);
6581     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6582     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6583     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6584   }
6585
6586   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6587   // and update MaskVals with new element order.
6588   std::bitset<8> InOrder;
6589   if (BestLoQuad >= 0) {
6590     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6591     for (int i = 0; i != 4; ++i) {
6592       int idx = MaskVals[i];
6593       if (idx < 0) {
6594         InOrder.set(i);
6595       } else if ((idx / 4) == BestLoQuad) {
6596         MaskV[i] = idx & 3;
6597         InOrder.set(i);
6598       }
6599     }
6600     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6601                                 &MaskV[0]);
6602
6603     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6604       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6605       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6606                                   NewV.getOperand(0),
6607                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6608     }
6609   }
6610
6611   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6612   // and update MaskVals with the new element order.
6613   if (BestHiQuad >= 0) {
6614     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6615     for (unsigned i = 4; i != 8; ++i) {
6616       int idx = MaskVals[i];
6617       if (idx < 0) {
6618         InOrder.set(i);
6619       } else if ((idx / 4) == BestHiQuad) {
6620         MaskV[i] = (idx & 3) + 4;
6621         InOrder.set(i);
6622       }
6623     }
6624     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6625                                 &MaskV[0]);
6626
6627     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6628       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6629       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6630                                   NewV.getOperand(0),
6631                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6632     }
6633   }
6634
6635   // In case BestHi & BestLo were both -1, which means each quadword has a word
6636   // from each of the four input quadwords, calculate the InOrder bitvector now
6637   // before falling through to the insert/extract cleanup.
6638   if (BestLoQuad == -1 && BestHiQuad == -1) {
6639     NewV = V1;
6640     for (int i = 0; i != 8; ++i)
6641       if (MaskVals[i] < 0 || MaskVals[i] == i)
6642         InOrder.set(i);
6643   }
6644
6645   // The other elements are put in the right place using pextrw and pinsrw.
6646   for (unsigned i = 0; i != 8; ++i) {
6647     if (InOrder[i])
6648       continue;
6649     int EltIdx = MaskVals[i];
6650     if (EltIdx < 0)
6651       continue;
6652     SDValue ExtOp = (EltIdx < 8) ?
6653       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6654                   DAG.getIntPtrConstant(EltIdx)) :
6655       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6656                   DAG.getIntPtrConstant(EltIdx - 8));
6657     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6658                        DAG.getIntPtrConstant(i));
6659   }
6660   return NewV;
6661 }
6662
6663 /// \brief v16i16 shuffles
6664 ///
6665 /// FIXME: We only support generation of a single pshufb currently.  We can
6666 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6667 /// well (e.g 2 x pshufb + 1 x por).
6668 static SDValue
6669 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6670   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6671   SDValue V1 = SVOp->getOperand(0);
6672   SDValue V2 = SVOp->getOperand(1);
6673   SDLoc dl(SVOp);
6674
6675   if (V2.getOpcode() != ISD::UNDEF)
6676     return SDValue();
6677
6678   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6679   return getPSHUFB(MaskVals, V1, dl, DAG);
6680 }
6681
6682 // v16i8 shuffles - Prefer shuffles in the following order:
6683 // 1. [ssse3] 1 x pshufb
6684 // 2. [ssse3] 2 x pshufb + 1 x por
6685 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6686 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6687                                         const X86Subtarget* Subtarget,
6688                                         SelectionDAG &DAG) {
6689   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6690   SDValue V1 = SVOp->getOperand(0);
6691   SDValue V2 = SVOp->getOperand(1);
6692   SDLoc dl(SVOp);
6693   ArrayRef<int> MaskVals = SVOp->getMask();
6694
6695   // Promote splats to a larger type which usually leads to more efficient code.
6696   // FIXME: Is this true if pshufb is available?
6697   if (SVOp->isSplat())
6698     return PromoteSplat(SVOp, DAG);
6699
6700   // If we have SSSE3, case 1 is generated when all result bytes come from
6701   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6702   // present, fall back to case 3.
6703
6704   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6705   if (Subtarget->hasSSSE3()) {
6706     SmallVector<SDValue,16> pshufbMask;
6707
6708     // If all result elements are from one input vector, then only translate
6709     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6710     //
6711     // Otherwise, we have elements from both input vectors, and must zero out
6712     // elements that come from V2 in the first mask, and V1 in the second mask
6713     // so that we can OR them together.
6714     for (unsigned i = 0; i != 16; ++i) {
6715       int EltIdx = MaskVals[i];
6716       if (EltIdx < 0 || EltIdx >= 16)
6717         EltIdx = 0x80;
6718       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6719     }
6720     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6721                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6722                                  MVT::v16i8, &pshufbMask[0], 16));
6723
6724     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6725     // the 2nd operand if it's undefined or zero.
6726     if (V2.getOpcode() == ISD::UNDEF ||
6727         ISD::isBuildVectorAllZeros(V2.getNode()))
6728       return V1;
6729
6730     // Calculate the shuffle mask for the second input, shuffle it, and
6731     // OR it with the first shuffled input.
6732     pshufbMask.clear();
6733     for (unsigned i = 0; i != 16; ++i) {
6734       int EltIdx = MaskVals[i];
6735       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6736       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6737     }
6738     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6739                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6740                                  MVT::v16i8, &pshufbMask[0], 16));
6741     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6742   }
6743
6744   // No SSSE3 - Calculate in place words and then fix all out of place words
6745   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6746   // the 16 different words that comprise the two doublequadword input vectors.
6747   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6748   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6749   SDValue NewV = V1;
6750   for (int i = 0; i != 8; ++i) {
6751     int Elt0 = MaskVals[i*2];
6752     int Elt1 = MaskVals[i*2+1];
6753
6754     // This word of the result is all undef, skip it.
6755     if (Elt0 < 0 && Elt1 < 0)
6756       continue;
6757
6758     // This word of the result is already in the correct place, skip it.
6759     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6760       continue;
6761
6762     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6763     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6764     SDValue InsElt;
6765
6766     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6767     // using a single extract together, load it and store it.
6768     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6769       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6770                            DAG.getIntPtrConstant(Elt1 / 2));
6771       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6772                         DAG.getIntPtrConstant(i));
6773       continue;
6774     }
6775
6776     // If Elt1 is defined, extract it from the appropriate source.  If the
6777     // source byte is not also odd, shift the extracted word left 8 bits
6778     // otherwise clear the bottom 8 bits if we need to do an or.
6779     if (Elt1 >= 0) {
6780       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6781                            DAG.getIntPtrConstant(Elt1 / 2));
6782       if ((Elt1 & 1) == 0)
6783         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6784                              DAG.getConstant(8,
6785                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6786       else if (Elt0 >= 0)
6787         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6788                              DAG.getConstant(0xFF00, MVT::i16));
6789     }
6790     // If Elt0 is defined, extract it from the appropriate source.  If the
6791     // source byte is not also even, shift the extracted word right 8 bits. If
6792     // Elt1 was also defined, OR the extracted values together before
6793     // inserting them in the result.
6794     if (Elt0 >= 0) {
6795       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6796                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6797       if ((Elt0 & 1) != 0)
6798         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6799                               DAG.getConstant(8,
6800                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6801       else if (Elt1 >= 0)
6802         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6803                              DAG.getConstant(0x00FF, MVT::i16));
6804       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6805                          : InsElt0;
6806     }
6807     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6808                        DAG.getIntPtrConstant(i));
6809   }
6810   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6811 }
6812
6813 // v32i8 shuffles - Translate to VPSHUFB if possible.
6814 static
6815 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6816                                  const X86Subtarget *Subtarget,
6817                                  SelectionDAG &DAG) {
6818   MVT VT = SVOp->getSimpleValueType(0);
6819   SDValue V1 = SVOp->getOperand(0);
6820   SDValue V2 = SVOp->getOperand(1);
6821   SDLoc dl(SVOp);
6822   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6823
6824   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6825   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6826   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6827
6828   // VPSHUFB may be generated if
6829   // (1) one of input vector is undefined or zeroinitializer.
6830   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6831   // And (2) the mask indexes don't cross the 128-bit lane.
6832   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6833       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6834     return SDValue();
6835
6836   if (V1IsAllZero && !V2IsAllZero) {
6837     CommuteVectorShuffleMask(MaskVals, 32);
6838     V1 = V2;
6839   }
6840   return getPSHUFB(MaskVals, V1, dl, DAG);
6841 }
6842
6843 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6844 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6845 /// done when every pair / quad of shuffle mask elements point to elements in
6846 /// the right sequence. e.g.
6847 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6848 static
6849 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6850                                  SelectionDAG &DAG) {
6851   MVT VT = SVOp->getSimpleValueType(0);
6852   SDLoc dl(SVOp);
6853   unsigned NumElems = VT.getVectorNumElements();
6854   MVT NewVT;
6855   unsigned Scale;
6856   switch (VT.SimpleTy) {
6857   default: llvm_unreachable("Unexpected!");
6858   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6859   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6860   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6861   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6862   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6863   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6864   }
6865
6866   SmallVector<int, 8> MaskVec;
6867   for (unsigned i = 0; i != NumElems; i += Scale) {
6868     int StartIdx = -1;
6869     for (unsigned j = 0; j != Scale; ++j) {
6870       int EltIdx = SVOp->getMaskElt(i+j);
6871       if (EltIdx < 0)
6872         continue;
6873       if (StartIdx < 0)
6874         StartIdx = (EltIdx / Scale);
6875       if (EltIdx != (int)(StartIdx*Scale + j))
6876         return SDValue();
6877     }
6878     MaskVec.push_back(StartIdx);
6879   }
6880
6881   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6882   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6883   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6884 }
6885
6886 /// getVZextMovL - Return a zero-extending vector move low node.
6887 ///
6888 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6889                             SDValue SrcOp, SelectionDAG &DAG,
6890                             const X86Subtarget *Subtarget, SDLoc dl) {
6891   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6892     LoadSDNode *LD = nullptr;
6893     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6894       LD = dyn_cast<LoadSDNode>(SrcOp);
6895     if (!LD) {
6896       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6897       // instead.
6898       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6899       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6900           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6901           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6902           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6903         // PR2108
6904         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6905         return DAG.getNode(ISD::BITCAST, dl, VT,
6906                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6907                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6908                                                    OpVT,
6909                                                    SrcOp.getOperand(0)
6910                                                           .getOperand(0))));
6911       }
6912     }
6913   }
6914
6915   return DAG.getNode(ISD::BITCAST, dl, VT,
6916                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6917                                  DAG.getNode(ISD::BITCAST, dl,
6918                                              OpVT, SrcOp)));
6919 }
6920
6921 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6922 /// which could not be matched by any known target speficic shuffle
6923 static SDValue
6924 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6925
6926   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6927   if (NewOp.getNode())
6928     return NewOp;
6929
6930   MVT VT = SVOp->getSimpleValueType(0);
6931
6932   unsigned NumElems = VT.getVectorNumElements();
6933   unsigned NumLaneElems = NumElems / 2;
6934
6935   SDLoc dl(SVOp);
6936   MVT EltVT = VT.getVectorElementType();
6937   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6938   SDValue Output[2];
6939
6940   SmallVector<int, 16> Mask;
6941   for (unsigned l = 0; l < 2; ++l) {
6942     // Build a shuffle mask for the output, discovering on the fly which
6943     // input vectors to use as shuffle operands (recorded in InputUsed).
6944     // If building a suitable shuffle vector proves too hard, then bail
6945     // out with UseBuildVector set.
6946     bool UseBuildVector = false;
6947     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6948     unsigned LaneStart = l * NumLaneElems;
6949     for (unsigned i = 0; i != NumLaneElems; ++i) {
6950       // The mask element.  This indexes into the input.
6951       int Idx = SVOp->getMaskElt(i+LaneStart);
6952       if (Idx < 0) {
6953         // the mask element does not index into any input vector.
6954         Mask.push_back(-1);
6955         continue;
6956       }
6957
6958       // The input vector this mask element indexes into.
6959       int Input = Idx / NumLaneElems;
6960
6961       // Turn the index into an offset from the start of the input vector.
6962       Idx -= Input * NumLaneElems;
6963
6964       // Find or create a shuffle vector operand to hold this input.
6965       unsigned OpNo;
6966       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6967         if (InputUsed[OpNo] == Input)
6968           // This input vector is already an operand.
6969           break;
6970         if (InputUsed[OpNo] < 0) {
6971           // Create a new operand for this input vector.
6972           InputUsed[OpNo] = Input;
6973           break;
6974         }
6975       }
6976
6977       if (OpNo >= array_lengthof(InputUsed)) {
6978         // More than two input vectors used!  Give up on trying to create a
6979         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6980         UseBuildVector = true;
6981         break;
6982       }
6983
6984       // Add the mask index for the new shuffle vector.
6985       Mask.push_back(Idx + OpNo * NumLaneElems);
6986     }
6987
6988     if (UseBuildVector) {
6989       SmallVector<SDValue, 16> SVOps;
6990       for (unsigned i = 0; i != NumLaneElems; ++i) {
6991         // The mask element.  This indexes into the input.
6992         int Idx = SVOp->getMaskElt(i+LaneStart);
6993         if (Idx < 0) {
6994           SVOps.push_back(DAG.getUNDEF(EltVT));
6995           continue;
6996         }
6997
6998         // The input vector this mask element indexes into.
6999         int Input = Idx / NumElems;
7000
7001         // Turn the index into an offset from the start of the input vector.
7002         Idx -= Input * NumElems;
7003
7004         // Extract the vector element by hand.
7005         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7006                                     SVOp->getOperand(Input),
7007                                     DAG.getIntPtrConstant(Idx)));
7008       }
7009
7010       // Construct the output using a BUILD_VECTOR.
7011       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
7012                               SVOps.size());
7013     } else if (InputUsed[0] < 0) {
7014       // No input vectors were used! The result is undefined.
7015       Output[l] = DAG.getUNDEF(NVT);
7016     } else {
7017       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7018                                         (InputUsed[0] % 2) * NumLaneElems,
7019                                         DAG, dl);
7020       // If only one input was used, use an undefined vector for the other.
7021       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7022         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7023                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7024       // At least one input vector was used. Create a new shuffle vector.
7025       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7026     }
7027
7028     Mask.clear();
7029   }
7030
7031   // Concatenate the result back
7032   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7033 }
7034
7035 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7036 /// 4 elements, and match them with several different shuffle types.
7037 static SDValue
7038 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7039   SDValue V1 = SVOp->getOperand(0);
7040   SDValue V2 = SVOp->getOperand(1);
7041   SDLoc dl(SVOp);
7042   MVT VT = SVOp->getSimpleValueType(0);
7043
7044   assert(VT.is128BitVector() && "Unsupported vector size");
7045
7046   std::pair<int, int> Locs[4];
7047   int Mask1[] = { -1, -1, -1, -1 };
7048   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7049
7050   unsigned NumHi = 0;
7051   unsigned NumLo = 0;
7052   for (unsigned i = 0; i != 4; ++i) {
7053     int Idx = PermMask[i];
7054     if (Idx < 0) {
7055       Locs[i] = std::make_pair(-1, -1);
7056     } else {
7057       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7058       if (Idx < 4) {
7059         Locs[i] = std::make_pair(0, NumLo);
7060         Mask1[NumLo] = Idx;
7061         NumLo++;
7062       } else {
7063         Locs[i] = std::make_pair(1, NumHi);
7064         if (2+NumHi < 4)
7065           Mask1[2+NumHi] = Idx;
7066         NumHi++;
7067       }
7068     }
7069   }
7070
7071   if (NumLo <= 2 && NumHi <= 2) {
7072     // If no more than two elements come from either vector. This can be
7073     // implemented with two shuffles. First shuffle gather the elements.
7074     // The second shuffle, which takes the first shuffle as both of its
7075     // vector operands, put the elements into the right order.
7076     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7077
7078     int Mask2[] = { -1, -1, -1, -1 };
7079
7080     for (unsigned i = 0; i != 4; ++i)
7081       if (Locs[i].first != -1) {
7082         unsigned Idx = (i < 2) ? 0 : 4;
7083         Idx += Locs[i].first * 2 + Locs[i].second;
7084         Mask2[i] = Idx;
7085       }
7086
7087     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7088   }
7089
7090   if (NumLo == 3 || NumHi == 3) {
7091     // Otherwise, we must have three elements from one vector, call it X, and
7092     // one element from the other, call it Y.  First, use a shufps to build an
7093     // intermediate vector with the one element from Y and the element from X
7094     // that will be in the same half in the final destination (the indexes don't
7095     // matter). Then, use a shufps to build the final vector, taking the half
7096     // containing the element from Y from the intermediate, and the other half
7097     // from X.
7098     if (NumHi == 3) {
7099       // Normalize it so the 3 elements come from V1.
7100       CommuteVectorShuffleMask(PermMask, 4);
7101       std::swap(V1, V2);
7102     }
7103
7104     // Find the element from V2.
7105     unsigned HiIndex;
7106     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7107       int Val = PermMask[HiIndex];
7108       if (Val < 0)
7109         continue;
7110       if (Val >= 4)
7111         break;
7112     }
7113
7114     Mask1[0] = PermMask[HiIndex];
7115     Mask1[1] = -1;
7116     Mask1[2] = PermMask[HiIndex^1];
7117     Mask1[3] = -1;
7118     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7119
7120     if (HiIndex >= 2) {
7121       Mask1[0] = PermMask[0];
7122       Mask1[1] = PermMask[1];
7123       Mask1[2] = HiIndex & 1 ? 6 : 4;
7124       Mask1[3] = HiIndex & 1 ? 4 : 6;
7125       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7126     }
7127
7128     Mask1[0] = HiIndex & 1 ? 2 : 0;
7129     Mask1[1] = HiIndex & 1 ? 0 : 2;
7130     Mask1[2] = PermMask[2];
7131     Mask1[3] = PermMask[3];
7132     if (Mask1[2] >= 0)
7133       Mask1[2] += 4;
7134     if (Mask1[3] >= 0)
7135       Mask1[3] += 4;
7136     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7137   }
7138
7139   // Break it into (shuffle shuffle_hi, shuffle_lo).
7140   int LoMask[] = { -1, -1, -1, -1 };
7141   int HiMask[] = { -1, -1, -1, -1 };
7142
7143   int *MaskPtr = LoMask;
7144   unsigned MaskIdx = 0;
7145   unsigned LoIdx = 0;
7146   unsigned HiIdx = 2;
7147   for (unsigned i = 0; i != 4; ++i) {
7148     if (i == 2) {
7149       MaskPtr = HiMask;
7150       MaskIdx = 1;
7151       LoIdx = 0;
7152       HiIdx = 2;
7153     }
7154     int Idx = PermMask[i];
7155     if (Idx < 0) {
7156       Locs[i] = std::make_pair(-1, -1);
7157     } else if (Idx < 4) {
7158       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7159       MaskPtr[LoIdx] = Idx;
7160       LoIdx++;
7161     } else {
7162       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7163       MaskPtr[HiIdx] = Idx;
7164       HiIdx++;
7165     }
7166   }
7167
7168   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7169   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7170   int MaskOps[] = { -1, -1, -1, -1 };
7171   for (unsigned i = 0; i != 4; ++i)
7172     if (Locs[i].first != -1)
7173       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7174   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7175 }
7176
7177 static bool MayFoldVectorLoad(SDValue V) {
7178   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7179     V = V.getOperand(0);
7180
7181   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7182     V = V.getOperand(0);
7183   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7184       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7185     // BUILD_VECTOR (load), undef
7186     V = V.getOperand(0);
7187
7188   return MayFoldLoad(V);
7189 }
7190
7191 static
7192 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7193   MVT VT = Op.getSimpleValueType();
7194
7195   // Canonizalize to v2f64.
7196   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7197   return DAG.getNode(ISD::BITCAST, dl, VT,
7198                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7199                                           V1, DAG));
7200 }
7201
7202 static
7203 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7204                         bool HasSSE2) {
7205   SDValue V1 = Op.getOperand(0);
7206   SDValue V2 = Op.getOperand(1);
7207   MVT VT = Op.getSimpleValueType();
7208
7209   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7210
7211   if (HasSSE2 && VT == MVT::v2f64)
7212     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7213
7214   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7215   return DAG.getNode(ISD::BITCAST, dl, VT,
7216                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7217                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7218                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7219 }
7220
7221 static
7222 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7223   SDValue V1 = Op.getOperand(0);
7224   SDValue V2 = Op.getOperand(1);
7225   MVT VT = Op.getSimpleValueType();
7226
7227   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7228          "unsupported shuffle type");
7229
7230   if (V2.getOpcode() == ISD::UNDEF)
7231     V2 = V1;
7232
7233   // v4i32 or v4f32
7234   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7235 }
7236
7237 static
7238 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7239   SDValue V1 = Op.getOperand(0);
7240   SDValue V2 = Op.getOperand(1);
7241   MVT VT = Op.getSimpleValueType();
7242   unsigned NumElems = VT.getVectorNumElements();
7243
7244   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7245   // operand of these instructions is only memory, so check if there's a
7246   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7247   // same masks.
7248   bool CanFoldLoad = false;
7249
7250   // Trivial case, when V2 comes from a load.
7251   if (MayFoldVectorLoad(V2))
7252     CanFoldLoad = true;
7253
7254   // When V1 is a load, it can be folded later into a store in isel, example:
7255   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7256   //    turns into:
7257   //  (MOVLPSmr addr:$src1, VR128:$src2)
7258   // So, recognize this potential and also use MOVLPS or MOVLPD
7259   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7260     CanFoldLoad = true;
7261
7262   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7263   if (CanFoldLoad) {
7264     if (HasSSE2 && NumElems == 2)
7265       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7266
7267     if (NumElems == 4)
7268       // If we don't care about the second element, proceed to use movss.
7269       if (SVOp->getMaskElt(1) != -1)
7270         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7271   }
7272
7273   // movl and movlp will both match v2i64, but v2i64 is never matched by
7274   // movl earlier because we make it strict to avoid messing with the movlp load
7275   // folding logic (see the code above getMOVLP call). Match it here then,
7276   // this is horrible, but will stay like this until we move all shuffle
7277   // matching to x86 specific nodes. Note that for the 1st condition all
7278   // types are matched with movsd.
7279   if (HasSSE2) {
7280     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7281     // as to remove this logic from here, as much as possible
7282     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7283       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7284     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7285   }
7286
7287   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7288
7289   // Invert the operand order and use SHUFPS to match it.
7290   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7291                               getShuffleSHUFImmediate(SVOp), DAG);
7292 }
7293
7294 // It is only safe to call this function if isINSERTPSMask is true for
7295 // this shufflevector mask.
7296 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7297                            SelectionDAG &DAG) {
7298   // Generate an insertps instruction when inserting an f32 from memory onto a
7299   // v4f32 or when copying a member from one v4f32 to another.
7300   // We also use it for transferring i32 from one register to another,
7301   // since it simply copies the same bits.
7302   // If we're transfering an i32 from memory to a specific element in a
7303   // register, we output a generic DAG that will match the PINSRD
7304   // instruction.
7305   // TODO: Optimize for AVX cases too (VINSERTPS)
7306   MVT VT = SVOp->getSimpleValueType(0);
7307   MVT EVT = VT.getVectorElementType();
7308   SDValue V1 = SVOp->getOperand(0);
7309   SDValue V2 = SVOp->getOperand(1);
7310   auto Mask = SVOp->getMask();
7311   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7312          "unsupported vector type for insertps/pinsrd");
7313
7314   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7315                              [](const int &i) { return i < 4; });
7316
7317   SDValue From;
7318   SDValue To;
7319   unsigned DestIndex;
7320   if (FromV1 == 1) {
7321     From = V1;
7322     To = V2;
7323     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7324                              [](const int &i) { return i < 4; }) -
7325                 Mask.begin();
7326   } else {
7327     From = V2;
7328     To = V1;
7329     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7330                              [](const int &i) { return i >= 4; }) -
7331                 Mask.begin();
7332   }
7333
7334   if (MayFoldLoad(From)) {
7335     // Trivial case, when From comes from a load and is only used by the
7336     // shuffle. Make it use insertps from the vector that we need from that
7337     // load.
7338     SDValue Addr = From.getOperand(1);
7339     SDValue NewAddr =
7340         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7341                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7342                                     Addr.getSimpleValueType()));
7343
7344     LoadSDNode *Load = cast<LoadSDNode>(From);
7345     SDValue NewLoad =
7346         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7347                     DAG.getMachineFunction().getMachineMemOperand(
7348                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7349
7350     if (EVT == MVT::f32) {
7351       // Create this as a scalar to vector to match the instruction pattern.
7352       SDValue LoadScalarToVector =
7353           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7354       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7355       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7356                          InsertpsMask);
7357     } else { // EVT == MVT::i32
7358       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7359       // instruction, to match the PINSRD instruction, which loads an i32 to a
7360       // certain vector element.
7361       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7362                          DAG.getConstant(DestIndex, MVT::i32));
7363     }
7364   }
7365
7366   // Vector-element-to-vector
7367   unsigned SrcIndex = Mask[DestIndex] % 4;
7368   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7369   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7370 }
7371
7372 // Reduce a vector shuffle to zext.
7373 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7374                                     SelectionDAG &DAG) {
7375   // PMOVZX is only available from SSE41.
7376   if (!Subtarget->hasSSE41())
7377     return SDValue();
7378
7379   MVT VT = Op.getSimpleValueType();
7380
7381   // Only AVX2 support 256-bit vector integer extending.
7382   if (!Subtarget->hasInt256() && VT.is256BitVector())
7383     return SDValue();
7384
7385   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7386   SDLoc DL(Op);
7387   SDValue V1 = Op.getOperand(0);
7388   SDValue V2 = Op.getOperand(1);
7389   unsigned NumElems = VT.getVectorNumElements();
7390
7391   // Extending is an unary operation and the element type of the source vector
7392   // won't be equal to or larger than i64.
7393   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7394       VT.getVectorElementType() == MVT::i64)
7395     return SDValue();
7396
7397   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7398   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7399   while ((1U << Shift) < NumElems) {
7400     if (SVOp->getMaskElt(1U << Shift) == 1)
7401       break;
7402     Shift += 1;
7403     // The maximal ratio is 8, i.e. from i8 to i64.
7404     if (Shift > 3)
7405       return SDValue();
7406   }
7407
7408   // Check the shuffle mask.
7409   unsigned Mask = (1U << Shift) - 1;
7410   for (unsigned i = 0; i != NumElems; ++i) {
7411     int EltIdx = SVOp->getMaskElt(i);
7412     if ((i & Mask) != 0 && EltIdx != -1)
7413       return SDValue();
7414     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7415       return SDValue();
7416   }
7417
7418   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7419   MVT NeVT = MVT::getIntegerVT(NBits);
7420   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7421
7422   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7423     return SDValue();
7424
7425   // Simplify the operand as it's prepared to be fed into shuffle.
7426   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7427   if (V1.getOpcode() == ISD::BITCAST &&
7428       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7429       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7430       V1.getOperand(0).getOperand(0)
7431         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7432     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7433     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7434     ConstantSDNode *CIdx =
7435       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7436     // If it's foldable, i.e. normal load with single use, we will let code
7437     // selection to fold it. Otherwise, we will short the conversion sequence.
7438     if (CIdx && CIdx->getZExtValue() == 0 &&
7439         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7440       MVT FullVT = V.getSimpleValueType();
7441       MVT V1VT = V1.getSimpleValueType();
7442       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7443         // The "ext_vec_elt" node is wider than the result node.
7444         // In this case we should extract subvector from V.
7445         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7446         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7447         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7448                                         FullVT.getVectorNumElements()/Ratio);
7449         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7450                         DAG.getIntPtrConstant(0));
7451       }
7452       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7453     }
7454   }
7455
7456   return DAG.getNode(ISD::BITCAST, DL, VT,
7457                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7458 }
7459
7460 static SDValue
7461 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7462                        SelectionDAG &DAG) {
7463   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7464   MVT VT = Op.getSimpleValueType();
7465   SDLoc dl(Op);
7466   SDValue V1 = Op.getOperand(0);
7467   SDValue V2 = Op.getOperand(1);
7468
7469   if (isZeroShuffle(SVOp))
7470     return getZeroVector(VT, Subtarget, DAG, dl);
7471
7472   // Handle splat operations
7473   if (SVOp->isSplat()) {
7474     // Use vbroadcast whenever the splat comes from a foldable load
7475     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7476     if (Broadcast.getNode())
7477       return Broadcast;
7478   }
7479
7480   // Check integer expanding shuffles.
7481   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7482   if (NewOp.getNode())
7483     return NewOp;
7484
7485   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7486   // do it!
7487   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7488       VT == MVT::v16i16 || VT == MVT::v32i8) {
7489     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7490     if (NewOp.getNode())
7491       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7492   } else if ((VT == MVT::v4i32 ||
7493              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7494     // FIXME: Figure out a cleaner way to do this.
7495     // Try to make use of movq to zero out the top part.
7496     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7497       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7498       if (NewOp.getNode()) {
7499         MVT NewVT = NewOp.getSimpleValueType();
7500         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7501                                NewVT, true, false))
7502           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7503                               DAG, Subtarget, dl);
7504       }
7505     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7506       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7507       if (NewOp.getNode()) {
7508         MVT NewVT = NewOp.getSimpleValueType();
7509         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7510           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7511                               DAG, Subtarget, dl);
7512       }
7513     }
7514   }
7515   return SDValue();
7516 }
7517
7518 SDValue
7519 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7521   SDValue V1 = Op.getOperand(0);
7522   SDValue V2 = Op.getOperand(1);
7523   MVT VT = Op.getSimpleValueType();
7524   SDLoc dl(Op);
7525   unsigned NumElems = VT.getVectorNumElements();
7526   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7527   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7528   bool V1IsSplat = false;
7529   bool V2IsSplat = false;
7530   bool HasSSE2 = Subtarget->hasSSE2();
7531   bool HasFp256    = Subtarget->hasFp256();
7532   bool HasInt256   = Subtarget->hasInt256();
7533   MachineFunction &MF = DAG.getMachineFunction();
7534   bool OptForSize = MF.getFunction()->getAttributes().
7535     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7536
7537   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7538
7539   if (V1IsUndef && V2IsUndef)
7540     return DAG.getUNDEF(VT);
7541
7542   // When we create a shuffle node we put the UNDEF node to second operand,
7543   // but in some cases the first operand may be transformed to UNDEF.
7544   // In this case we should just commute the node.
7545   if (V1IsUndef)
7546     return CommuteVectorShuffle(SVOp, DAG);
7547
7548   // Vector shuffle lowering takes 3 steps:
7549   //
7550   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7551   //    narrowing and commutation of operands should be handled.
7552   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7553   //    shuffle nodes.
7554   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7555   //    so the shuffle can be broken into other shuffles and the legalizer can
7556   //    try the lowering again.
7557   //
7558   // The general idea is that no vector_shuffle operation should be left to
7559   // be matched during isel, all of them must be converted to a target specific
7560   // node here.
7561
7562   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7563   // narrowing and commutation of operands should be handled. The actual code
7564   // doesn't include all of those, work in progress...
7565   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7566   if (NewOp.getNode())
7567     return NewOp;
7568
7569   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7570
7571   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7572   // unpckh_undef). Only use pshufd if speed is more important than size.
7573   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7574     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7575   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7576     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7577
7578   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7579       V2IsUndef && MayFoldVectorLoad(V1))
7580     return getMOVDDup(Op, dl, V1, DAG);
7581
7582   if (isMOVHLPS_v_undef_Mask(M, VT))
7583     return getMOVHighToLow(Op, dl, DAG);
7584
7585   // Use to match splats
7586   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7587       (VT == MVT::v2f64 || VT == MVT::v2i64))
7588     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7589
7590   if (isPSHUFDMask(M, VT)) {
7591     // The actual implementation will match the mask in the if above and then
7592     // during isel it can match several different instructions, not only pshufd
7593     // as its name says, sad but true, emulate the behavior for now...
7594     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7595       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7596
7597     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7598
7599     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7600       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7601
7602     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7603       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7604                                   DAG);
7605
7606     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7607                                 TargetMask, DAG);
7608   }
7609
7610   if (isPALIGNRMask(M, VT, Subtarget))
7611     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7612                                 getShufflePALIGNRImmediate(SVOp),
7613                                 DAG);
7614
7615   // Check if this can be converted into a logical shift.
7616   bool isLeft = false;
7617   unsigned ShAmt = 0;
7618   SDValue ShVal;
7619   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7620   if (isShift && ShVal.hasOneUse()) {
7621     // If the shifted value has multiple uses, it may be cheaper to use
7622     // v_set0 + movlhps or movhlps, etc.
7623     MVT EltVT = VT.getVectorElementType();
7624     ShAmt *= EltVT.getSizeInBits();
7625     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7626   }
7627
7628   if (isMOVLMask(M, VT)) {
7629     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7630       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7631     if (!isMOVLPMask(M, VT)) {
7632       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7633         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7634
7635       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7636         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7637     }
7638   }
7639
7640   // FIXME: fold these into legal mask.
7641   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7642     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7643
7644   if (isMOVHLPSMask(M, VT))
7645     return getMOVHighToLow(Op, dl, DAG);
7646
7647   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7648     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7649
7650   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7651     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7652
7653   if (isMOVLPMask(M, VT))
7654     return getMOVLP(Op, dl, DAG, HasSSE2);
7655
7656   if (ShouldXformToMOVHLPS(M, VT) ||
7657       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7658     return CommuteVectorShuffle(SVOp, DAG);
7659
7660   if (isShift) {
7661     // No better options. Use a vshldq / vsrldq.
7662     MVT EltVT = VT.getVectorElementType();
7663     ShAmt *= EltVT.getSizeInBits();
7664     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7665   }
7666
7667   bool Commuted = false;
7668   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7669   // 1,1,1,1 -> v8i16 though.
7670   V1IsSplat = isSplatVector(V1.getNode());
7671   V2IsSplat = isSplatVector(V2.getNode());
7672
7673   // Canonicalize the splat or undef, if present, to be on the RHS.
7674   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7675     CommuteVectorShuffleMask(M, NumElems);
7676     std::swap(V1, V2);
7677     std::swap(V1IsSplat, V2IsSplat);
7678     Commuted = true;
7679   }
7680
7681   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7682     // Shuffling low element of v1 into undef, just return v1.
7683     if (V2IsUndef)
7684       return V1;
7685     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7686     // the instruction selector will not match, so get a canonical MOVL with
7687     // swapped operands to undo the commute.
7688     return getMOVL(DAG, dl, VT, V2, V1);
7689   }
7690
7691   if (isUNPCKLMask(M, VT, HasInt256))
7692     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7693
7694   if (isUNPCKHMask(M, VT, HasInt256))
7695     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7696
7697   if (V2IsSplat) {
7698     // Normalize mask so all entries that point to V2 points to its first
7699     // element then try to match unpck{h|l} again. If match, return a
7700     // new vector_shuffle with the corrected mask.p
7701     SmallVector<int, 8> NewMask(M.begin(), M.end());
7702     NormalizeMask(NewMask, NumElems);
7703     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7704       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7705     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7706       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7707   }
7708
7709   if (Commuted) {
7710     // Commute is back and try unpck* again.
7711     // FIXME: this seems wrong.
7712     CommuteVectorShuffleMask(M, NumElems);
7713     std::swap(V1, V2);
7714     std::swap(V1IsSplat, V2IsSplat);
7715
7716     if (isUNPCKLMask(M, VT, HasInt256))
7717       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7718
7719     if (isUNPCKHMask(M, VT, HasInt256))
7720       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7721   }
7722
7723   // Normalize the node to match x86 shuffle ops if needed
7724   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7725     return CommuteVectorShuffle(SVOp, DAG);
7726
7727   // The checks below are all present in isShuffleMaskLegal, but they are
7728   // inlined here right now to enable us to directly emit target specific
7729   // nodes, and remove one by one until they don't return Op anymore.
7730
7731   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7732       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7733     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7734       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7735   }
7736
7737   if (isPSHUFHWMask(M, VT, HasInt256))
7738     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7739                                 getShufflePSHUFHWImmediate(SVOp),
7740                                 DAG);
7741
7742   if (isPSHUFLWMask(M, VT, HasInt256))
7743     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7744                                 getShufflePSHUFLWImmediate(SVOp),
7745                                 DAG);
7746
7747   if (isSHUFPMask(M, VT))
7748     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7749                                 getShuffleSHUFImmediate(SVOp), DAG);
7750
7751   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7752     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7753   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7754     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7755
7756   //===--------------------------------------------------------------------===//
7757   // Generate target specific nodes for 128 or 256-bit shuffles only
7758   // supported in the AVX instruction set.
7759   //
7760
7761   // Handle VMOVDDUPY permutations
7762   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7763     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7764
7765   // Handle VPERMILPS/D* permutations
7766   if (isVPERMILPMask(M, VT)) {
7767     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7768       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7769                                   getShuffleSHUFImmediate(SVOp), DAG);
7770     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7771                                 getShuffleSHUFImmediate(SVOp), DAG);
7772   }
7773
7774   // Handle VPERM2F128/VPERM2I128 permutations
7775   if (isVPERM2X128Mask(M, VT, HasFp256))
7776     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7777                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7778
7779   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7780   if (BlendOp.getNode())
7781     return BlendOp;
7782
7783   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7784     return getINSERTPS(SVOp, dl, DAG);
7785
7786   unsigned Imm8;
7787   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7788     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7789
7790   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7791       VT.is512BitVector()) {
7792     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7793     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7794     SmallVector<SDValue, 16> permclMask;
7795     for (unsigned i = 0; i != NumElems; ++i) {
7796       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7797     }
7798
7799     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7800                                 &permclMask[0], NumElems);
7801     if (V2IsUndef)
7802       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7803       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7804                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7805     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7806                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7807   }
7808
7809   //===--------------------------------------------------------------------===//
7810   // Since no target specific shuffle was selected for this generic one,
7811   // lower it into other known shuffles. FIXME: this isn't true yet, but
7812   // this is the plan.
7813   //
7814
7815   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7816   if (VT == MVT::v8i16) {
7817     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7818     if (NewOp.getNode())
7819       return NewOp;
7820   }
7821
7822   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7823     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7824     if (NewOp.getNode())
7825       return NewOp;
7826   }
7827
7828   if (VT == MVT::v16i8) {
7829     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7830     if (NewOp.getNode())
7831       return NewOp;
7832   }
7833
7834   if (VT == MVT::v32i8) {
7835     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7836     if (NewOp.getNode())
7837       return NewOp;
7838   }
7839
7840   // Handle all 128-bit wide vectors with 4 elements, and match them with
7841   // several different shuffle types.
7842   if (NumElems == 4 && VT.is128BitVector())
7843     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7844
7845   // Handle general 256-bit shuffles
7846   if (VT.is256BitVector())
7847     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7848
7849   return SDValue();
7850 }
7851
7852 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7853   MVT VT = Op.getSimpleValueType();
7854   SDLoc dl(Op);
7855
7856   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7857     return SDValue();
7858
7859   if (VT.getSizeInBits() == 8) {
7860     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7861                                   Op.getOperand(0), Op.getOperand(1));
7862     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7863                                   DAG.getValueType(VT));
7864     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7865   }
7866
7867   if (VT.getSizeInBits() == 16) {
7868     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7869     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7870     if (Idx == 0)
7871       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7872                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7873                                      DAG.getNode(ISD::BITCAST, dl,
7874                                                  MVT::v4i32,
7875                                                  Op.getOperand(0)),
7876                                      Op.getOperand(1)));
7877     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7878                                   Op.getOperand(0), Op.getOperand(1));
7879     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7880                                   DAG.getValueType(VT));
7881     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7882   }
7883
7884   if (VT == MVT::f32) {
7885     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7886     // the result back to FR32 register. It's only worth matching if the
7887     // result has a single use which is a store or a bitcast to i32.  And in
7888     // the case of a store, it's not worth it if the index is a constant 0,
7889     // because a MOVSSmr can be used instead, which is smaller and faster.
7890     if (!Op.hasOneUse())
7891       return SDValue();
7892     SDNode *User = *Op.getNode()->use_begin();
7893     if ((User->getOpcode() != ISD::STORE ||
7894          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7895           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7896         (User->getOpcode() != ISD::BITCAST ||
7897          User->getValueType(0) != MVT::i32))
7898       return SDValue();
7899     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7900                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7901                                               Op.getOperand(0)),
7902                                               Op.getOperand(1));
7903     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7904   }
7905
7906   if (VT == MVT::i32 || VT == MVT::i64) {
7907     // ExtractPS/pextrq works with constant index.
7908     if (isa<ConstantSDNode>(Op.getOperand(1)))
7909       return Op;
7910   }
7911   return SDValue();
7912 }
7913
7914 /// Extract one bit from mask vector, like v16i1 or v8i1.
7915 /// AVX-512 feature.
7916 SDValue
7917 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7918   SDValue Vec = Op.getOperand(0);
7919   SDLoc dl(Vec);
7920   MVT VecVT = Vec.getSimpleValueType();
7921   SDValue Idx = Op.getOperand(1);
7922   MVT EltVT = Op.getSimpleValueType();
7923
7924   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7925
7926   // variable index can't be handled in mask registers,
7927   // extend vector to VR512
7928   if (!isa<ConstantSDNode>(Idx)) {
7929     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7930     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7931     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7932                               ExtVT.getVectorElementType(), Ext, Idx);
7933     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7934   }
7935
7936   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7937   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7938   unsigned MaxSift = rc->getSize()*8 - 1;
7939   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7940                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7941   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7942                     DAG.getConstant(MaxSift, MVT::i8));
7943   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7944                        DAG.getIntPtrConstant(0));
7945 }
7946
7947 SDValue
7948 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7949                                            SelectionDAG &DAG) const {
7950   SDLoc dl(Op);
7951   SDValue Vec = Op.getOperand(0);
7952   MVT VecVT = Vec.getSimpleValueType();
7953   SDValue Idx = Op.getOperand(1);
7954
7955   if (Op.getSimpleValueType() == MVT::i1)
7956     return ExtractBitFromMaskVector(Op, DAG);
7957
7958   if (!isa<ConstantSDNode>(Idx)) {
7959     if (VecVT.is512BitVector() ||
7960         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7961          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7962
7963       MVT MaskEltVT =
7964         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7965       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7966                                     MaskEltVT.getSizeInBits());
7967
7968       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7969       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7970                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7971                                 Idx, DAG.getConstant(0, getPointerTy()));
7972       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7973       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7974                         Perm, DAG.getConstant(0, getPointerTy()));
7975     }
7976     return SDValue();
7977   }
7978
7979   // If this is a 256-bit vector result, first extract the 128-bit vector and
7980   // then extract the element from the 128-bit vector.
7981   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7982
7983     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7984     // Get the 128-bit vector.
7985     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7986     MVT EltVT = VecVT.getVectorElementType();
7987
7988     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7989
7990     //if (IdxVal >= NumElems/2)
7991     //  IdxVal -= NumElems/2;
7992     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7993     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7994                        DAG.getConstant(IdxVal, MVT::i32));
7995   }
7996
7997   assert(VecVT.is128BitVector() && "Unexpected vector length");
7998
7999   if (Subtarget->hasSSE41()) {
8000     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8001     if (Res.getNode())
8002       return Res;
8003   }
8004
8005   MVT VT = Op.getSimpleValueType();
8006   // TODO: handle v16i8.
8007   if (VT.getSizeInBits() == 16) {
8008     SDValue Vec = Op.getOperand(0);
8009     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8010     if (Idx == 0)
8011       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8012                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8013                                      DAG.getNode(ISD::BITCAST, dl,
8014                                                  MVT::v4i32, Vec),
8015                                      Op.getOperand(1)));
8016     // Transform it so it match pextrw which produces a 32-bit result.
8017     MVT EltVT = MVT::i32;
8018     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8019                                   Op.getOperand(0), Op.getOperand(1));
8020     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8021                                   DAG.getValueType(VT));
8022     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8023   }
8024
8025   if (VT.getSizeInBits() == 32) {
8026     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8027     if (Idx == 0)
8028       return Op;
8029
8030     // SHUFPS the element to the lowest double word, then movss.
8031     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8032     MVT VVT = Op.getOperand(0).getSimpleValueType();
8033     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8034                                        DAG.getUNDEF(VVT), Mask);
8035     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8036                        DAG.getIntPtrConstant(0));
8037   }
8038
8039   if (VT.getSizeInBits() == 64) {
8040     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8041     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8042     //        to match extract_elt for f64.
8043     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8044     if (Idx == 0)
8045       return Op;
8046
8047     // UNPCKHPD the element to the lowest double word, then movsd.
8048     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8049     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8050     int Mask[2] = { 1, -1 };
8051     MVT VVT = Op.getOperand(0).getSimpleValueType();
8052     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8053                                        DAG.getUNDEF(VVT), Mask);
8054     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8055                        DAG.getIntPtrConstant(0));
8056   }
8057
8058   return SDValue();
8059 }
8060
8061 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8062   MVT VT = Op.getSimpleValueType();
8063   MVT EltVT = VT.getVectorElementType();
8064   SDLoc dl(Op);
8065
8066   SDValue N0 = Op.getOperand(0);
8067   SDValue N1 = Op.getOperand(1);
8068   SDValue N2 = Op.getOperand(2);
8069
8070   if (!VT.is128BitVector())
8071     return SDValue();
8072
8073   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8074       isa<ConstantSDNode>(N2)) {
8075     unsigned Opc;
8076     if (VT == MVT::v8i16)
8077       Opc = X86ISD::PINSRW;
8078     else if (VT == MVT::v16i8)
8079       Opc = X86ISD::PINSRB;
8080     else
8081       Opc = X86ISD::PINSRB;
8082
8083     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8084     // argument.
8085     if (N1.getValueType() != MVT::i32)
8086       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8087     if (N2.getValueType() != MVT::i32)
8088       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8089     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8090   }
8091
8092   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8093     // Bits [7:6] of the constant are the source select.  This will always be
8094     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8095     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8096     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8097     // Bits [5:4] of the constant are the destination select.  This is the
8098     //  value of the incoming immediate.
8099     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8100     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8101     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8102     // Create this as a scalar to vector..
8103     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8104     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8105   }
8106
8107   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8108     // PINSR* works with constant index.
8109     return Op;
8110   }
8111   return SDValue();
8112 }
8113
8114 /// Insert one bit to mask vector, like v16i1 or v8i1.
8115 /// AVX-512 feature.
8116 SDValue 
8117 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8118   SDLoc dl(Op);
8119   SDValue Vec = Op.getOperand(0);
8120   SDValue Elt = Op.getOperand(1);
8121   SDValue Idx = Op.getOperand(2);
8122   MVT VecVT = Vec.getSimpleValueType();
8123
8124   if (!isa<ConstantSDNode>(Idx)) {
8125     // Non constant index. Extend source and destination,
8126     // insert element and then truncate the result.
8127     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8128     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8129     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8130       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8131       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8132     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8133   }
8134
8135   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8136   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8137   if (Vec.getOpcode() == ISD::UNDEF)
8138     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8139                        DAG.getConstant(IdxVal, MVT::i8));
8140   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8141   unsigned MaxSift = rc->getSize()*8 - 1;
8142   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8143                     DAG.getConstant(MaxSift, MVT::i8));
8144   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8145                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8146   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8147 }
8148 SDValue
8149 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8150   MVT VT = Op.getSimpleValueType();
8151   MVT EltVT = VT.getVectorElementType();
8152   
8153   if (EltVT == MVT::i1)
8154     return InsertBitToMaskVector(Op, DAG);
8155
8156   SDLoc dl(Op);
8157   SDValue N0 = Op.getOperand(0);
8158   SDValue N1 = Op.getOperand(1);
8159   SDValue N2 = Op.getOperand(2);
8160
8161   // If this is a 256-bit vector result, first extract the 128-bit vector,
8162   // insert the element into the extracted half and then place it back.
8163   if (VT.is256BitVector() || VT.is512BitVector()) {
8164     if (!isa<ConstantSDNode>(N2))
8165       return SDValue();
8166
8167     // Get the desired 128-bit vector half.
8168     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8169     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8170
8171     // Insert the element into the desired half.
8172     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8173     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8174
8175     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8176                     DAG.getConstant(IdxIn128, MVT::i32));
8177
8178     // Insert the changed part back to the 256-bit vector
8179     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8180   }
8181
8182   if (Subtarget->hasSSE41())
8183     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8184
8185   if (EltVT == MVT::i8)
8186     return SDValue();
8187
8188   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8189     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8190     // as its second argument.
8191     if (N1.getValueType() != MVT::i32)
8192       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8193     if (N2.getValueType() != MVT::i32)
8194       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8195     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8196   }
8197   return SDValue();
8198 }
8199
8200 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8201   SDLoc dl(Op);
8202   MVT OpVT = Op.getSimpleValueType();
8203
8204   // If this is a 256-bit vector result, first insert into a 128-bit
8205   // vector and then insert into the 256-bit vector.
8206   if (!OpVT.is128BitVector()) {
8207     // Insert into a 128-bit vector.
8208     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8209     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8210                                  OpVT.getVectorNumElements() / SizeFactor);
8211
8212     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8213
8214     // Insert the 128-bit vector.
8215     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8216   }
8217
8218   if (OpVT == MVT::v1i64 &&
8219       Op.getOperand(0).getValueType() == MVT::i64)
8220     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8221
8222   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8223   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8224   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8225                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8226 }
8227
8228 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8229 // a simple subregister reference or explicit instructions to grab
8230 // upper bits of a vector.
8231 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8232                                       SelectionDAG &DAG) {
8233   SDLoc dl(Op);
8234   SDValue In =  Op.getOperand(0);
8235   SDValue Idx = Op.getOperand(1);
8236   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8237   MVT ResVT   = Op.getSimpleValueType();
8238   MVT InVT    = In.getSimpleValueType();
8239
8240   if (Subtarget->hasFp256()) {
8241     if (ResVT.is128BitVector() &&
8242         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8243         isa<ConstantSDNode>(Idx)) {
8244       return Extract128BitVector(In, IdxVal, DAG, dl);
8245     }
8246     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8247         isa<ConstantSDNode>(Idx)) {
8248       return Extract256BitVector(In, IdxVal, DAG, dl);
8249     }
8250   }
8251   return SDValue();
8252 }
8253
8254 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8255 // simple superregister reference or explicit instructions to insert
8256 // the upper bits of a vector.
8257 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8258                                      SelectionDAG &DAG) {
8259   if (Subtarget->hasFp256()) {
8260     SDLoc dl(Op.getNode());
8261     SDValue Vec = Op.getNode()->getOperand(0);
8262     SDValue SubVec = Op.getNode()->getOperand(1);
8263     SDValue Idx = Op.getNode()->getOperand(2);
8264
8265     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8266          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8267         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8268         isa<ConstantSDNode>(Idx)) {
8269       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8270       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8271     }
8272
8273     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8274         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8275         isa<ConstantSDNode>(Idx)) {
8276       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8277       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8278     }
8279   }
8280   return SDValue();
8281 }
8282
8283 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8284 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8285 // one of the above mentioned nodes. It has to be wrapped because otherwise
8286 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8287 // be used to form addressing mode. These wrapped nodes will be selected
8288 // into MOV32ri.
8289 SDValue
8290 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8291   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8292
8293   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8294   // global base reg.
8295   unsigned char OpFlag = 0;
8296   unsigned WrapperKind = X86ISD::Wrapper;
8297   CodeModel::Model M = getTargetMachine().getCodeModel();
8298
8299   if (Subtarget->isPICStyleRIPRel() &&
8300       (M == CodeModel::Small || M == CodeModel::Kernel))
8301     WrapperKind = X86ISD::WrapperRIP;
8302   else if (Subtarget->isPICStyleGOT())
8303     OpFlag = X86II::MO_GOTOFF;
8304   else if (Subtarget->isPICStyleStubPIC())
8305     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8306
8307   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8308                                              CP->getAlignment(),
8309                                              CP->getOffset(), OpFlag);
8310   SDLoc DL(CP);
8311   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8312   // With PIC, the address is actually $g + Offset.
8313   if (OpFlag) {
8314     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8315                          DAG.getNode(X86ISD::GlobalBaseReg,
8316                                      SDLoc(), getPointerTy()),
8317                          Result);
8318   }
8319
8320   return Result;
8321 }
8322
8323 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8324   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8325
8326   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8327   // global base reg.
8328   unsigned char OpFlag = 0;
8329   unsigned WrapperKind = X86ISD::Wrapper;
8330   CodeModel::Model M = getTargetMachine().getCodeModel();
8331
8332   if (Subtarget->isPICStyleRIPRel() &&
8333       (M == CodeModel::Small || M == CodeModel::Kernel))
8334     WrapperKind = X86ISD::WrapperRIP;
8335   else if (Subtarget->isPICStyleGOT())
8336     OpFlag = X86II::MO_GOTOFF;
8337   else if (Subtarget->isPICStyleStubPIC())
8338     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8339
8340   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8341                                           OpFlag);
8342   SDLoc DL(JT);
8343   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8344
8345   // With PIC, the address is actually $g + Offset.
8346   if (OpFlag)
8347     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8348                          DAG.getNode(X86ISD::GlobalBaseReg,
8349                                      SDLoc(), getPointerTy()),
8350                          Result);
8351
8352   return Result;
8353 }
8354
8355 SDValue
8356 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8357   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8358
8359   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8360   // global base reg.
8361   unsigned char OpFlag = 0;
8362   unsigned WrapperKind = X86ISD::Wrapper;
8363   CodeModel::Model M = getTargetMachine().getCodeModel();
8364
8365   if (Subtarget->isPICStyleRIPRel() &&
8366       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8367     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8368       OpFlag = X86II::MO_GOTPCREL;
8369     WrapperKind = X86ISD::WrapperRIP;
8370   } else if (Subtarget->isPICStyleGOT()) {
8371     OpFlag = X86II::MO_GOT;
8372   } else if (Subtarget->isPICStyleStubPIC()) {
8373     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8374   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8375     OpFlag = X86II::MO_DARWIN_NONLAZY;
8376   }
8377
8378   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8379
8380   SDLoc DL(Op);
8381   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8382
8383   // With PIC, the address is actually $g + Offset.
8384   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8385       !Subtarget->is64Bit()) {
8386     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8387                          DAG.getNode(X86ISD::GlobalBaseReg,
8388                                      SDLoc(), getPointerTy()),
8389                          Result);
8390   }
8391
8392   // For symbols that require a load from a stub to get the address, emit the
8393   // load.
8394   if (isGlobalStubReference(OpFlag))
8395     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8396                          MachinePointerInfo::getGOT(), false, false, false, 0);
8397
8398   return Result;
8399 }
8400
8401 SDValue
8402 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8403   // Create the TargetBlockAddressAddress node.
8404   unsigned char OpFlags =
8405     Subtarget->ClassifyBlockAddressReference();
8406   CodeModel::Model M = getTargetMachine().getCodeModel();
8407   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8408   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8409   SDLoc dl(Op);
8410   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8411                                              OpFlags);
8412
8413   if (Subtarget->isPICStyleRIPRel() &&
8414       (M == CodeModel::Small || M == CodeModel::Kernel))
8415     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8416   else
8417     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8418
8419   // With PIC, the address is actually $g + Offset.
8420   if (isGlobalRelativeToPICBase(OpFlags)) {
8421     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8422                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8423                          Result);
8424   }
8425
8426   return Result;
8427 }
8428
8429 SDValue
8430 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8431                                       int64_t Offset, SelectionDAG &DAG) const {
8432   // Create the TargetGlobalAddress node, folding in the constant
8433   // offset if it is legal.
8434   unsigned char OpFlags =
8435     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8436   CodeModel::Model M = getTargetMachine().getCodeModel();
8437   SDValue Result;
8438   if (OpFlags == X86II::MO_NO_FLAG &&
8439       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8440     // A direct static reference to a global.
8441     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8442     Offset = 0;
8443   } else {
8444     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8445   }
8446
8447   if (Subtarget->isPICStyleRIPRel() &&
8448       (M == CodeModel::Small || M == CodeModel::Kernel))
8449     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8450   else
8451     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8452
8453   // With PIC, the address is actually $g + Offset.
8454   if (isGlobalRelativeToPICBase(OpFlags)) {
8455     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8456                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8457                          Result);
8458   }
8459
8460   // For globals that require a load from a stub to get the address, emit the
8461   // load.
8462   if (isGlobalStubReference(OpFlags))
8463     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8464                          MachinePointerInfo::getGOT(), false, false, false, 0);
8465
8466   // If there was a non-zero offset that we didn't fold, create an explicit
8467   // addition for it.
8468   if (Offset != 0)
8469     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8470                          DAG.getConstant(Offset, getPointerTy()));
8471
8472   return Result;
8473 }
8474
8475 SDValue
8476 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8477   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8478   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8479   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8480 }
8481
8482 static SDValue
8483 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8484            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8485            unsigned char OperandFlags, bool LocalDynamic = false) {
8486   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8487   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8488   SDLoc dl(GA);
8489   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8490                                            GA->getValueType(0),
8491                                            GA->getOffset(),
8492                                            OperandFlags);
8493
8494   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8495                                            : X86ISD::TLSADDR;
8496
8497   if (InFlag) {
8498     SDValue Ops[] = { Chain,  TGA, *InFlag };
8499     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8500   } else {
8501     SDValue Ops[]  = { Chain, TGA };
8502     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8503   }
8504
8505   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8506   MFI->setAdjustsStack(true);
8507
8508   SDValue Flag = Chain.getValue(1);
8509   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8510 }
8511
8512 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8513 static SDValue
8514 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8515                                 const EVT PtrVT) {
8516   SDValue InFlag;
8517   SDLoc dl(GA);  // ? function entry point might be better
8518   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8519                                    DAG.getNode(X86ISD::GlobalBaseReg,
8520                                                SDLoc(), PtrVT), InFlag);
8521   InFlag = Chain.getValue(1);
8522
8523   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8524 }
8525
8526 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8527 static SDValue
8528 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8529                                 const EVT PtrVT) {
8530   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8531                     X86::RAX, X86II::MO_TLSGD);
8532 }
8533
8534 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8535                                            SelectionDAG &DAG,
8536                                            const EVT PtrVT,
8537                                            bool is64Bit) {
8538   SDLoc dl(GA);
8539
8540   // Get the start address of the TLS block for this module.
8541   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8542       .getInfo<X86MachineFunctionInfo>();
8543   MFI->incNumLocalDynamicTLSAccesses();
8544
8545   SDValue Base;
8546   if (is64Bit) {
8547     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8548                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8549   } else {
8550     SDValue InFlag;
8551     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8552         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8553     InFlag = Chain.getValue(1);
8554     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8555                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8556   }
8557
8558   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8559   // of Base.
8560
8561   // Build x@dtpoff.
8562   unsigned char OperandFlags = X86II::MO_DTPOFF;
8563   unsigned WrapperKind = X86ISD::Wrapper;
8564   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8565                                            GA->getValueType(0),
8566                                            GA->getOffset(), OperandFlags);
8567   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8568
8569   // Add x@dtpoff with the base.
8570   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8571 }
8572
8573 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8574 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8575                                    const EVT PtrVT, TLSModel::Model model,
8576                                    bool is64Bit, bool isPIC) {
8577   SDLoc dl(GA);
8578
8579   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8580   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8581                                                          is64Bit ? 257 : 256));
8582
8583   SDValue ThreadPointer =
8584       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8585                   MachinePointerInfo(Ptr), false, false, false, 0);
8586
8587   unsigned char OperandFlags = 0;
8588   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8589   // initialexec.
8590   unsigned WrapperKind = X86ISD::Wrapper;
8591   if (model == TLSModel::LocalExec) {
8592     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8593   } else if (model == TLSModel::InitialExec) {
8594     if (is64Bit) {
8595       OperandFlags = X86II::MO_GOTTPOFF;
8596       WrapperKind = X86ISD::WrapperRIP;
8597     } else {
8598       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8599     }
8600   } else {
8601     llvm_unreachable("Unexpected model");
8602   }
8603
8604   // emit "addl x@ntpoff,%eax" (local exec)
8605   // or "addl x@indntpoff,%eax" (initial exec)
8606   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8607   SDValue TGA =
8608       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8609                                  GA->getOffset(), OperandFlags);
8610   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8611
8612   if (model == TLSModel::InitialExec) {
8613     if (isPIC && !is64Bit) {
8614       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8615                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8616                            Offset);
8617     }
8618
8619     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8620                          MachinePointerInfo::getGOT(), false, false, false, 0);
8621   }
8622
8623   // The address of the thread local variable is the add of the thread
8624   // pointer with the offset of the variable.
8625   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8626 }
8627
8628 SDValue
8629 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8630
8631   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8632   const GlobalValue *GV = GA->getGlobal();
8633
8634   if (Subtarget->isTargetELF()) {
8635     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8636
8637     switch (model) {
8638       case TLSModel::GeneralDynamic:
8639         if (Subtarget->is64Bit())
8640           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8641         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8642       case TLSModel::LocalDynamic:
8643         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8644                                            Subtarget->is64Bit());
8645       case TLSModel::InitialExec:
8646       case TLSModel::LocalExec:
8647         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8648                                    Subtarget->is64Bit(),
8649                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8650     }
8651     llvm_unreachable("Unknown TLS model.");
8652   }
8653
8654   if (Subtarget->isTargetDarwin()) {
8655     // Darwin only has one model of TLS.  Lower to that.
8656     unsigned char OpFlag = 0;
8657     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8658                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8659
8660     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8661     // global base reg.
8662     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8663                   !Subtarget->is64Bit();
8664     if (PIC32)
8665       OpFlag = X86II::MO_TLVP_PIC_BASE;
8666     else
8667       OpFlag = X86II::MO_TLVP;
8668     SDLoc DL(Op);
8669     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8670                                                 GA->getValueType(0),
8671                                                 GA->getOffset(), OpFlag);
8672     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8673
8674     // With PIC32, the address is actually $g + Offset.
8675     if (PIC32)
8676       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8677                            DAG.getNode(X86ISD::GlobalBaseReg,
8678                                        SDLoc(), getPointerTy()),
8679                            Offset);
8680
8681     // Lowering the machine isd will make sure everything is in the right
8682     // location.
8683     SDValue Chain = DAG.getEntryNode();
8684     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8685     SDValue Args[] = { Chain, Offset };
8686     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8687
8688     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8689     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8690     MFI->setAdjustsStack(true);
8691
8692     // And our return value (tls address) is in the standard call return value
8693     // location.
8694     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8695     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8696                               Chain.getValue(1));
8697   }
8698
8699   if (Subtarget->isTargetKnownWindowsMSVC() ||
8700       Subtarget->isTargetWindowsGNU()) {
8701     // Just use the implicit TLS architecture
8702     // Need to generate someting similar to:
8703     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8704     //                                  ; from TEB
8705     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8706     //   mov     rcx, qword [rdx+rcx*8]
8707     //   mov     eax, .tls$:tlsvar
8708     //   [rax+rcx] contains the address
8709     // Windows 64bit: gs:0x58
8710     // Windows 32bit: fs:__tls_array
8711
8712     // If GV is an alias then use the aliasee for determining
8713     // thread-localness.
8714     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8715       GV = GA->getAliasedGlobal();
8716     SDLoc dl(GA);
8717     SDValue Chain = DAG.getEntryNode();
8718
8719     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8720     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8721     // use its literal value of 0x2C.
8722     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8723                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8724                                                              256)
8725                                         : Type::getInt32PtrTy(*DAG.getContext(),
8726                                                               257));
8727
8728     SDValue TlsArray =
8729         Subtarget->is64Bit()
8730             ? DAG.getIntPtrConstant(0x58)
8731             : (Subtarget->isTargetWindowsGNU()
8732                    ? DAG.getIntPtrConstant(0x2C)
8733                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8734
8735     SDValue ThreadPointer =
8736         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8737                     MachinePointerInfo(Ptr), false, false, false, 0);
8738
8739     // Load the _tls_index variable
8740     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8741     if (Subtarget->is64Bit())
8742       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8743                            IDX, MachinePointerInfo(), MVT::i32,
8744                            false, false, 0);
8745     else
8746       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8747                         false, false, false, 0);
8748
8749     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8750                                     getPointerTy());
8751     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8752
8753     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8754     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8755                       false, false, false, 0);
8756
8757     // Get the offset of start of .tls section
8758     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8759                                              GA->getValueType(0),
8760                                              GA->getOffset(), X86II::MO_SECREL);
8761     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8762
8763     // The address of the thread local variable is the add of the thread
8764     // pointer with the offset of the variable.
8765     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8766   }
8767
8768   llvm_unreachable("TLS not implemented for this target.");
8769 }
8770
8771 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8772 /// and take a 2 x i32 value to shift plus a shift amount.
8773 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8774   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8775   MVT VT = Op.getSimpleValueType();
8776   unsigned VTBits = VT.getSizeInBits();
8777   SDLoc dl(Op);
8778   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8779   SDValue ShOpLo = Op.getOperand(0);
8780   SDValue ShOpHi = Op.getOperand(1);
8781   SDValue ShAmt  = Op.getOperand(2);
8782   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8783   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8784   // during isel.
8785   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8786                                   DAG.getConstant(VTBits - 1, MVT::i8));
8787   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8788                                      DAG.getConstant(VTBits - 1, MVT::i8))
8789                        : DAG.getConstant(0, VT);
8790
8791   SDValue Tmp2, Tmp3;
8792   if (Op.getOpcode() == ISD::SHL_PARTS) {
8793     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8794     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8795   } else {
8796     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8797     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8798   }
8799
8800   // If the shift amount is larger or equal than the width of a part we can't
8801   // rely on the results of shld/shrd. Insert a test and select the appropriate
8802   // values for large shift amounts.
8803   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8804                                 DAG.getConstant(VTBits, MVT::i8));
8805   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8806                              AndNode, DAG.getConstant(0, MVT::i8));
8807
8808   SDValue Hi, Lo;
8809   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8810   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8811   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8812
8813   if (Op.getOpcode() == ISD::SHL_PARTS) {
8814     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8815     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8816   } else {
8817     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8818     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8819   }
8820
8821   SDValue Ops[2] = { Lo, Hi };
8822   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8823 }
8824
8825 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8826                                            SelectionDAG &DAG) const {
8827   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8828
8829   if (SrcVT.isVector())
8830     return SDValue();
8831
8832   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8833          "Unknown SINT_TO_FP to lower!");
8834
8835   // These are really Legal; return the operand so the caller accepts it as
8836   // Legal.
8837   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8838     return Op;
8839   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8840       Subtarget->is64Bit()) {
8841     return Op;
8842   }
8843
8844   SDLoc dl(Op);
8845   unsigned Size = SrcVT.getSizeInBits()/8;
8846   MachineFunction &MF = DAG.getMachineFunction();
8847   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8848   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8849   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8850                                StackSlot,
8851                                MachinePointerInfo::getFixedStack(SSFI),
8852                                false, false, 0);
8853   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8854 }
8855
8856 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8857                                      SDValue StackSlot,
8858                                      SelectionDAG &DAG) const {
8859   // Build the FILD
8860   SDLoc DL(Op);
8861   SDVTList Tys;
8862   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8863   if (useSSE)
8864     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8865   else
8866     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8867
8868   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8869
8870   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8871   MachineMemOperand *MMO;
8872   if (FI) {
8873     int SSFI = FI->getIndex();
8874     MMO =
8875       DAG.getMachineFunction()
8876       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8877                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8878   } else {
8879     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8880     StackSlot = StackSlot.getOperand(1);
8881   }
8882   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8883   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8884                                            X86ISD::FILD, DL,
8885                                            Tys, Ops, array_lengthof(Ops),
8886                                            SrcVT, MMO);
8887
8888   if (useSSE) {
8889     Chain = Result.getValue(1);
8890     SDValue InFlag = Result.getValue(2);
8891
8892     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8893     // shouldn't be necessary except that RFP cannot be live across
8894     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8895     MachineFunction &MF = DAG.getMachineFunction();
8896     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8897     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8898     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8899     Tys = DAG.getVTList(MVT::Other);
8900     SDValue Ops[] = {
8901       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8902     };
8903     MachineMemOperand *MMO =
8904       DAG.getMachineFunction()
8905       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8906                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8907
8908     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8909                                     Ops, array_lengthof(Ops),
8910                                     Op.getValueType(), MMO);
8911     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8912                          MachinePointerInfo::getFixedStack(SSFI),
8913                          false, false, false, 0);
8914   }
8915
8916   return Result;
8917 }
8918
8919 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8920 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8921                                                SelectionDAG &DAG) const {
8922   // This algorithm is not obvious. Here it is what we're trying to output:
8923   /*
8924      movq       %rax,  %xmm0
8925      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8926      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8927      #ifdef __SSE3__
8928        haddpd   %xmm0, %xmm0
8929      #else
8930        pshufd   $0x4e, %xmm0, %xmm1
8931        addpd    %xmm1, %xmm0
8932      #endif
8933   */
8934
8935   SDLoc dl(Op);
8936   LLVMContext *Context = DAG.getContext();
8937
8938   // Build some magic constants.
8939   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8940   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8941   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8942
8943   SmallVector<Constant*,2> CV1;
8944   CV1.push_back(
8945     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8946                                       APInt(64, 0x4330000000000000ULL))));
8947   CV1.push_back(
8948     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8949                                       APInt(64, 0x4530000000000000ULL))));
8950   Constant *C1 = ConstantVector::get(CV1);
8951   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8952
8953   // Load the 64-bit value into an XMM register.
8954   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8955                             Op.getOperand(0));
8956   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8957                               MachinePointerInfo::getConstantPool(),
8958                               false, false, false, 16);
8959   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8960                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8961                               CLod0);
8962
8963   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8964                               MachinePointerInfo::getConstantPool(),
8965                               false, false, false, 16);
8966   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8967   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8968   SDValue Result;
8969
8970   if (Subtarget->hasSSE3()) {
8971     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8972     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8973   } else {
8974     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8975     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8976                                            S2F, 0x4E, DAG);
8977     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8978                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8979                          Sub);
8980   }
8981
8982   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8983                      DAG.getIntPtrConstant(0));
8984 }
8985
8986 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8987 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8988                                                SelectionDAG &DAG) const {
8989   SDLoc dl(Op);
8990   // FP constant to bias correct the final result.
8991   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8992                                    MVT::f64);
8993
8994   // Load the 32-bit value into an XMM register.
8995   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8996                              Op.getOperand(0));
8997
8998   // Zero out the upper parts of the register.
8999   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9000
9001   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9002                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9003                      DAG.getIntPtrConstant(0));
9004
9005   // Or the load with the bias.
9006   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9007                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9008                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9009                                                    MVT::v2f64, Load)),
9010                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9011                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9012                                                    MVT::v2f64, Bias)));
9013   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9014                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9015                    DAG.getIntPtrConstant(0));
9016
9017   // Subtract the bias.
9018   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9019
9020   // Handle final rounding.
9021   EVT DestVT = Op.getValueType();
9022
9023   if (DestVT.bitsLT(MVT::f64))
9024     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9025                        DAG.getIntPtrConstant(0));
9026   if (DestVT.bitsGT(MVT::f64))
9027     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9028
9029   // Handle final rounding.
9030   return Sub;
9031 }
9032
9033 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9034                                                SelectionDAG &DAG) const {
9035   SDValue N0 = Op.getOperand(0);
9036   MVT SVT = N0.getSimpleValueType();
9037   SDLoc dl(Op);
9038
9039   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9040           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9041          "Custom UINT_TO_FP is not supported!");
9042
9043   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9044   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9045                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9046 }
9047
9048 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9049                                            SelectionDAG &DAG) const {
9050   SDValue N0 = Op.getOperand(0);
9051   SDLoc dl(Op);
9052
9053   if (Op.getValueType().isVector())
9054     return lowerUINT_TO_FP_vec(Op, DAG);
9055
9056   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9057   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9058   // the optimization here.
9059   if (DAG.SignBitIsZero(N0))
9060     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9061
9062   MVT SrcVT = N0.getSimpleValueType();
9063   MVT DstVT = Op.getSimpleValueType();
9064   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9065     return LowerUINT_TO_FP_i64(Op, DAG);
9066   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9067     return LowerUINT_TO_FP_i32(Op, DAG);
9068   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9069     return SDValue();
9070
9071   // Make a 64-bit buffer, and use it to build an FILD.
9072   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9073   if (SrcVT == MVT::i32) {
9074     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9075     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9076                                      getPointerTy(), StackSlot, WordOff);
9077     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9078                                   StackSlot, MachinePointerInfo(),
9079                                   false, false, 0);
9080     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9081                                   OffsetSlot, MachinePointerInfo(),
9082                                   false, false, 0);
9083     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9084     return Fild;
9085   }
9086
9087   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9088   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9089                                StackSlot, MachinePointerInfo(),
9090                                false, false, 0);
9091   // For i64 source, we need to add the appropriate power of 2 if the input
9092   // was negative.  This is the same as the optimization in
9093   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9094   // we must be careful to do the computation in x87 extended precision, not
9095   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9096   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9097   MachineMemOperand *MMO =
9098     DAG.getMachineFunction()
9099     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9100                           MachineMemOperand::MOLoad, 8, 8);
9101
9102   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9103   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9104   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9105                                          array_lengthof(Ops), MVT::i64, MMO);
9106
9107   APInt FF(32, 0x5F800000ULL);
9108
9109   // Check whether the sign bit is set.
9110   SDValue SignSet = DAG.getSetCC(dl,
9111                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9112                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9113                                  ISD::SETLT);
9114
9115   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9116   SDValue FudgePtr = DAG.getConstantPool(
9117                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9118                                          getPointerTy());
9119
9120   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9121   SDValue Zero = DAG.getIntPtrConstant(0);
9122   SDValue Four = DAG.getIntPtrConstant(4);
9123   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9124                                Zero, Four);
9125   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9126
9127   // Load the value out, extending it from f32 to f80.
9128   // FIXME: Avoid the extend by constructing the right constant pool?
9129   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9130                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9131                                  MVT::f32, false, false, 4);
9132   // Extend everything to 80 bits to force it to be done on x87.
9133   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9134   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9135 }
9136
9137 std::pair<SDValue,SDValue>
9138 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9139                                     bool IsSigned, bool IsReplace) const {
9140   SDLoc DL(Op);
9141
9142   EVT DstTy = Op.getValueType();
9143
9144   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9145     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9146     DstTy = MVT::i64;
9147   }
9148
9149   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9150          DstTy.getSimpleVT() >= MVT::i16 &&
9151          "Unknown FP_TO_INT to lower!");
9152
9153   // These are really Legal.
9154   if (DstTy == MVT::i32 &&
9155       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9156     return std::make_pair(SDValue(), SDValue());
9157   if (Subtarget->is64Bit() &&
9158       DstTy == MVT::i64 &&
9159       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9160     return std::make_pair(SDValue(), SDValue());
9161
9162   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9163   // stack slot, or into the FTOL runtime function.
9164   MachineFunction &MF = DAG.getMachineFunction();
9165   unsigned MemSize = DstTy.getSizeInBits()/8;
9166   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9167   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9168
9169   unsigned Opc;
9170   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9171     Opc = X86ISD::WIN_FTOL;
9172   else
9173     switch (DstTy.getSimpleVT().SimpleTy) {
9174     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9175     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9176     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9177     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9178     }
9179
9180   SDValue Chain = DAG.getEntryNode();
9181   SDValue Value = Op.getOperand(0);
9182   EVT TheVT = Op.getOperand(0).getValueType();
9183   // FIXME This causes a redundant load/store if the SSE-class value is already
9184   // in memory, such as if it is on the callstack.
9185   if (isScalarFPTypeInSSEReg(TheVT)) {
9186     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9187     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9188                          MachinePointerInfo::getFixedStack(SSFI),
9189                          false, false, 0);
9190     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9191     SDValue Ops[] = {
9192       Chain, StackSlot, DAG.getValueType(TheVT)
9193     };
9194
9195     MachineMemOperand *MMO =
9196       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9197                               MachineMemOperand::MOLoad, MemSize, MemSize);
9198     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9199                                     array_lengthof(Ops), DstTy, MMO);
9200     Chain = Value.getValue(1);
9201     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9202     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9203   }
9204
9205   MachineMemOperand *MMO =
9206     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9207                             MachineMemOperand::MOStore, MemSize, MemSize);
9208
9209   if (Opc != X86ISD::WIN_FTOL) {
9210     // Build the FP_TO_INT*_IN_MEM
9211     SDValue Ops[] = { Chain, Value, StackSlot };
9212     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9213                                            Ops, array_lengthof(Ops), DstTy,
9214                                            MMO);
9215     return std::make_pair(FIST, StackSlot);
9216   } else {
9217     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9218       DAG.getVTList(MVT::Other, MVT::Glue),
9219       Chain, Value);
9220     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9221       MVT::i32, ftol.getValue(1));
9222     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9223       MVT::i32, eax.getValue(2));
9224     SDValue Ops[] = { eax, edx };
9225     SDValue pair = IsReplace
9226       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9227       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9228     return std::make_pair(pair, SDValue());
9229   }
9230 }
9231
9232 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9233                               const X86Subtarget *Subtarget) {
9234   MVT VT = Op->getSimpleValueType(0);
9235   SDValue In = Op->getOperand(0);
9236   MVT InVT = In.getSimpleValueType();
9237   SDLoc dl(Op);
9238
9239   // Optimize vectors in AVX mode:
9240   //
9241   //   v8i16 -> v8i32
9242   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9243   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9244   //   Concat upper and lower parts.
9245   //
9246   //   v4i32 -> v4i64
9247   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9248   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9249   //   Concat upper and lower parts.
9250   //
9251
9252   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9253       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9254       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9255     return SDValue();
9256
9257   if (Subtarget->hasInt256())
9258     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9259
9260   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9261   SDValue Undef = DAG.getUNDEF(InVT);
9262   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9263   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9264   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9265
9266   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9267                              VT.getVectorNumElements()/2);
9268
9269   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9270   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9271
9272   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9273 }
9274
9275 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9276                                         SelectionDAG &DAG) {
9277   MVT VT = Op->getSimpleValueType(0);
9278   SDValue In = Op->getOperand(0);
9279   MVT InVT = In.getSimpleValueType();
9280   SDLoc DL(Op);
9281   unsigned int NumElts = VT.getVectorNumElements();
9282   if (NumElts != 8 && NumElts != 16)
9283     return SDValue();
9284
9285   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9286     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9287
9288   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9290   // Now we have only mask extension
9291   assert(InVT.getVectorElementType() == MVT::i1);
9292   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9293   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9294   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9295   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9296   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9297                            MachinePointerInfo::getConstantPool(),
9298                            false, false, false, Alignment);
9299
9300   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9301   if (VT.is512BitVector())
9302     return Brcst;
9303   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9304 }
9305
9306 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9307                                SelectionDAG &DAG) {
9308   if (Subtarget->hasFp256()) {
9309     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9310     if (Res.getNode())
9311       return Res;
9312   }
9313
9314   return SDValue();
9315 }
9316
9317 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9318                                 SelectionDAG &DAG) {
9319   SDLoc DL(Op);
9320   MVT VT = Op.getSimpleValueType();
9321   SDValue In = Op.getOperand(0);
9322   MVT SVT = In.getSimpleValueType();
9323
9324   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9325     return LowerZERO_EXTEND_AVX512(Op, DAG);
9326
9327   if (Subtarget->hasFp256()) {
9328     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9329     if (Res.getNode())
9330       return Res;
9331   }
9332
9333   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9334          VT.getVectorNumElements() != SVT.getVectorNumElements());
9335   return SDValue();
9336 }
9337
9338 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9339   SDLoc DL(Op);
9340   MVT VT = Op.getSimpleValueType();
9341   SDValue In = Op.getOperand(0);
9342   MVT InVT = In.getSimpleValueType();
9343
9344   if (VT == MVT::i1) {
9345     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9346            "Invalid scalar TRUNCATE operation");
9347     if (InVT == MVT::i32)
9348       return SDValue();
9349     if (InVT.getSizeInBits() == 64)
9350       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9351     else if (InVT.getSizeInBits() < 32)
9352       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9353     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9354   }
9355   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9356          "Invalid TRUNCATE operation");
9357
9358   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9359     if (VT.getVectorElementType().getSizeInBits() >=8)
9360       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9361
9362     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9363     unsigned NumElts = InVT.getVectorNumElements();
9364     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9365     if (InVT.getSizeInBits() < 512) {
9366       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9367       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9368       InVT = ExtVT;
9369     }
9370     
9371     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9372     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9373     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9374     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9375     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9376                            MachinePointerInfo::getConstantPool(),
9377                            false, false, false, Alignment);
9378     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9379     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9380     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9381   }
9382
9383   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9384     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9385     if (Subtarget->hasInt256()) {
9386       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9387       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9388       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9389                                 ShufMask);
9390       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9391                          DAG.getIntPtrConstant(0));
9392     }
9393
9394     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9395                                DAG.getIntPtrConstant(0));
9396     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9397                                DAG.getIntPtrConstant(2));
9398     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9399     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9400     static const int ShufMask[] = {0, 2, 4, 6};
9401     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9402   }
9403
9404   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9405     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9406     if (Subtarget->hasInt256()) {
9407       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9408
9409       SmallVector<SDValue,32> pshufbMask;
9410       for (unsigned i = 0; i < 2; ++i) {
9411         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9412         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9413         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9414         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9415         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9416         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9417         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9418         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9419         for (unsigned j = 0; j < 8; ++j)
9420           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9421       }
9422       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9423                                &pshufbMask[0], 32);
9424       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9425       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9426
9427       static const int ShufMask[] = {0,  2,  -1,  -1};
9428       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9429                                 &ShufMask[0]);
9430       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9431                        DAG.getIntPtrConstant(0));
9432       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9433     }
9434
9435     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9436                                DAG.getIntPtrConstant(0));
9437
9438     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9439                                DAG.getIntPtrConstant(4));
9440
9441     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9442     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9443
9444     // The PSHUFB mask:
9445     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9446                                    -1, -1, -1, -1, -1, -1, -1, -1};
9447
9448     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9449     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9450     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9451
9452     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9453     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9454
9455     // The MOVLHPS Mask:
9456     static const int ShufMask2[] = {0, 1, 4, 5};
9457     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9458     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9459   }
9460
9461   // Handle truncation of V256 to V128 using shuffles.
9462   if (!VT.is128BitVector() || !InVT.is256BitVector())
9463     return SDValue();
9464
9465   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9466
9467   unsigned NumElems = VT.getVectorNumElements();
9468   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9469
9470   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9471   // Prepare truncation shuffle mask
9472   for (unsigned i = 0; i != NumElems; ++i)
9473     MaskVec[i] = i * 2;
9474   SDValue V = DAG.getVectorShuffle(NVT, DL,
9475                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9476                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9477   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9478                      DAG.getIntPtrConstant(0));
9479 }
9480
9481 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9482                                            SelectionDAG &DAG) const {
9483   assert(!Op.getSimpleValueType().isVector());
9484
9485   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9486     /*IsSigned=*/ true, /*IsReplace=*/ false);
9487   SDValue FIST = Vals.first, StackSlot = Vals.second;
9488   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9489   if (!FIST.getNode()) return Op;
9490
9491   if (StackSlot.getNode())
9492     // Load the result.
9493     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9494                        FIST, StackSlot, MachinePointerInfo(),
9495                        false, false, false, 0);
9496
9497   // The node is the result.
9498   return FIST;
9499 }
9500
9501 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9502                                            SelectionDAG &DAG) const {
9503   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9504     /*IsSigned=*/ false, /*IsReplace=*/ false);
9505   SDValue FIST = Vals.first, StackSlot = Vals.second;
9506   assert(FIST.getNode() && "Unexpected failure");
9507
9508   if (StackSlot.getNode())
9509     // Load the result.
9510     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9511                        FIST, StackSlot, MachinePointerInfo(),
9512                        false, false, false, 0);
9513
9514   // The node is the result.
9515   return FIST;
9516 }
9517
9518 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9519   SDLoc DL(Op);
9520   MVT VT = Op.getSimpleValueType();
9521   SDValue In = Op.getOperand(0);
9522   MVT SVT = In.getSimpleValueType();
9523
9524   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9525
9526   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9527                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9528                                  In, DAG.getUNDEF(SVT)));
9529 }
9530
9531 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9532   LLVMContext *Context = DAG.getContext();
9533   SDLoc dl(Op);
9534   MVT VT = Op.getSimpleValueType();
9535   MVT EltVT = VT;
9536   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9537   if (VT.isVector()) {
9538     EltVT = VT.getVectorElementType();
9539     NumElts = VT.getVectorNumElements();
9540   }
9541   Constant *C;
9542   if (EltVT == MVT::f64)
9543     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9544                                           APInt(64, ~(1ULL << 63))));
9545   else
9546     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9547                                           APInt(32, ~(1U << 31))));
9548   C = ConstantVector::getSplat(NumElts, C);
9549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9550   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9551   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9552   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9553                              MachinePointerInfo::getConstantPool(),
9554                              false, false, false, Alignment);
9555   if (VT.isVector()) {
9556     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9557     return DAG.getNode(ISD::BITCAST, dl, VT,
9558                        DAG.getNode(ISD::AND, dl, ANDVT,
9559                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9560                                                Op.getOperand(0)),
9561                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9562   }
9563   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9564 }
9565
9566 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9567   LLVMContext *Context = DAG.getContext();
9568   SDLoc dl(Op);
9569   MVT VT = Op.getSimpleValueType();
9570   MVT EltVT = VT;
9571   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9572   if (VT.isVector()) {
9573     EltVT = VT.getVectorElementType();
9574     NumElts = VT.getVectorNumElements();
9575   }
9576   Constant *C;
9577   if (EltVT == MVT::f64)
9578     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9579                                           APInt(64, 1ULL << 63)));
9580   else
9581     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9582                                           APInt(32, 1U << 31)));
9583   C = ConstantVector::getSplat(NumElts, C);
9584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9585   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9586   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9587   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9588                              MachinePointerInfo::getConstantPool(),
9589                              false, false, false, Alignment);
9590   if (VT.isVector()) {
9591     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9592     return DAG.getNode(ISD::BITCAST, dl, VT,
9593                        DAG.getNode(ISD::XOR, dl, XORVT,
9594                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9595                                                Op.getOperand(0)),
9596                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9597   }
9598
9599   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9600 }
9601
9602 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9604   LLVMContext *Context = DAG.getContext();
9605   SDValue Op0 = Op.getOperand(0);
9606   SDValue Op1 = Op.getOperand(1);
9607   SDLoc dl(Op);
9608   MVT VT = Op.getSimpleValueType();
9609   MVT SrcVT = Op1.getSimpleValueType();
9610
9611   // If second operand is smaller, extend it first.
9612   if (SrcVT.bitsLT(VT)) {
9613     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9614     SrcVT = VT;
9615   }
9616   // And if it is bigger, shrink it first.
9617   if (SrcVT.bitsGT(VT)) {
9618     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9619     SrcVT = VT;
9620   }
9621
9622   // At this point the operands and the result should have the same
9623   // type, and that won't be f80 since that is not custom lowered.
9624
9625   // First get the sign bit of second operand.
9626   SmallVector<Constant*,4> CV;
9627   if (SrcVT == MVT::f64) {
9628     const fltSemantics &Sem = APFloat::IEEEdouble;
9629     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9630     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9631   } else {
9632     const fltSemantics &Sem = APFloat::IEEEsingle;
9633     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9634     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9635     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9636     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9637   }
9638   Constant *C = ConstantVector::get(CV);
9639   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9640   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9641                               MachinePointerInfo::getConstantPool(),
9642                               false, false, false, 16);
9643   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9644
9645   // Shift sign bit right or left if the two operands have different types.
9646   if (SrcVT.bitsGT(VT)) {
9647     // Op0 is MVT::f32, Op1 is MVT::f64.
9648     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9649     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9650                           DAG.getConstant(32, MVT::i32));
9651     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9652     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9653                           DAG.getIntPtrConstant(0));
9654   }
9655
9656   // Clear first operand sign bit.
9657   CV.clear();
9658   if (VT == MVT::f64) {
9659     const fltSemantics &Sem = APFloat::IEEEdouble;
9660     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9661                                                    APInt(64, ~(1ULL << 63)))));
9662     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9663   } else {
9664     const fltSemantics &Sem = APFloat::IEEEsingle;
9665     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9666                                                    APInt(32, ~(1U << 31)))));
9667     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9668     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9669     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9670   }
9671   C = ConstantVector::get(CV);
9672   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9673   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9674                               MachinePointerInfo::getConstantPool(),
9675                               false, false, false, 16);
9676   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9677
9678   // Or the value with the sign bit.
9679   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9680 }
9681
9682 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9683   SDValue N0 = Op.getOperand(0);
9684   SDLoc dl(Op);
9685   MVT VT = Op.getSimpleValueType();
9686
9687   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9688   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9689                                   DAG.getConstant(1, VT));
9690   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9691 }
9692
9693 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9694 //
9695 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9696                                       SelectionDAG &DAG) {
9697   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9698
9699   if (!Subtarget->hasSSE41())
9700     return SDValue();
9701
9702   if (!Op->hasOneUse())
9703     return SDValue();
9704
9705   SDNode *N = Op.getNode();
9706   SDLoc DL(N);
9707
9708   SmallVector<SDValue, 8> Opnds;
9709   DenseMap<SDValue, unsigned> VecInMap;
9710   SmallVector<SDValue, 8> VecIns;
9711   EVT VT = MVT::Other;
9712
9713   // Recognize a special case where a vector is casted into wide integer to
9714   // test all 0s.
9715   Opnds.push_back(N->getOperand(0));
9716   Opnds.push_back(N->getOperand(1));
9717
9718   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9719     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9720     // BFS traverse all OR'd operands.
9721     if (I->getOpcode() == ISD::OR) {
9722       Opnds.push_back(I->getOperand(0));
9723       Opnds.push_back(I->getOperand(1));
9724       // Re-evaluate the number of nodes to be traversed.
9725       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9726       continue;
9727     }
9728
9729     // Quit if a non-EXTRACT_VECTOR_ELT
9730     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9731       return SDValue();
9732
9733     // Quit if without a constant index.
9734     SDValue Idx = I->getOperand(1);
9735     if (!isa<ConstantSDNode>(Idx))
9736       return SDValue();
9737
9738     SDValue ExtractedFromVec = I->getOperand(0);
9739     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9740     if (M == VecInMap.end()) {
9741       VT = ExtractedFromVec.getValueType();
9742       // Quit if not 128/256-bit vector.
9743       if (!VT.is128BitVector() && !VT.is256BitVector())
9744         return SDValue();
9745       // Quit if not the same type.
9746       if (VecInMap.begin() != VecInMap.end() &&
9747           VT != VecInMap.begin()->first.getValueType())
9748         return SDValue();
9749       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9750       VecIns.push_back(ExtractedFromVec);
9751     }
9752     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9753   }
9754
9755   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9756          "Not extracted from 128-/256-bit vector.");
9757
9758   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9759
9760   for (DenseMap<SDValue, unsigned>::const_iterator
9761         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9762     // Quit if not all elements are used.
9763     if (I->second != FullMask)
9764       return SDValue();
9765   }
9766
9767   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9768
9769   // Cast all vectors into TestVT for PTEST.
9770   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9771     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9772
9773   // If more than one full vectors are evaluated, OR them first before PTEST.
9774   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9775     // Each iteration will OR 2 nodes and append the result until there is only
9776     // 1 node left, i.e. the final OR'd value of all vectors.
9777     SDValue LHS = VecIns[Slot];
9778     SDValue RHS = VecIns[Slot + 1];
9779     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9780   }
9781
9782   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9783                      VecIns.back(), VecIns.back());
9784 }
9785
9786 /// \brief return true if \c Op has a use that doesn't just read flags.
9787 static bool hasNonFlagsUse(SDValue Op) {
9788   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9789        ++UI) {
9790     SDNode *User = *UI;
9791     unsigned UOpNo = UI.getOperandNo();
9792     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9793       // Look pass truncate.
9794       UOpNo = User->use_begin().getOperandNo();
9795       User = *User->use_begin();
9796     }
9797
9798     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9799         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9800       return true;
9801   }
9802   return false;
9803 }
9804
9805 /// Emit nodes that will be selected as "test Op0,Op0", or something
9806 /// equivalent.
9807 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9808                                     SelectionDAG &DAG) const {
9809   if (Op.getValueType() == MVT::i1)
9810     // KORTEST instruction should be selected
9811     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9812                        DAG.getConstant(0, Op.getValueType()));
9813
9814   // CF and OF aren't always set the way we want. Determine which
9815   // of these we need.
9816   bool NeedCF = false;
9817   bool NeedOF = false;
9818   switch (X86CC) {
9819   default: break;
9820   case X86::COND_A: case X86::COND_AE:
9821   case X86::COND_B: case X86::COND_BE:
9822     NeedCF = true;
9823     break;
9824   case X86::COND_G: case X86::COND_GE:
9825   case X86::COND_L: case X86::COND_LE:
9826   case X86::COND_O: case X86::COND_NO:
9827     NeedOF = true;
9828     break;
9829   }
9830   // See if we can use the EFLAGS value from the operand instead of
9831   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9832   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9833   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9834     // Emit a CMP with 0, which is the TEST pattern.
9835     //if (Op.getValueType() == MVT::i1)
9836     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9837     //                     DAG.getConstant(0, MVT::i1));
9838     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9839                        DAG.getConstant(0, Op.getValueType()));
9840   }
9841   unsigned Opcode = 0;
9842   unsigned NumOperands = 0;
9843
9844   // Truncate operations may prevent the merge of the SETCC instruction
9845   // and the arithmetic instruction before it. Attempt to truncate the operands
9846   // of the arithmetic instruction and use a reduced bit-width instruction.
9847   bool NeedTruncation = false;
9848   SDValue ArithOp = Op;
9849   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9850     SDValue Arith = Op->getOperand(0);
9851     // Both the trunc and the arithmetic op need to have one user each.
9852     if (Arith->hasOneUse())
9853       switch (Arith.getOpcode()) {
9854         default: break;
9855         case ISD::ADD:
9856         case ISD::SUB:
9857         case ISD::AND:
9858         case ISD::OR:
9859         case ISD::XOR: {
9860           NeedTruncation = true;
9861           ArithOp = Arith;
9862         }
9863       }
9864   }
9865
9866   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9867   // which may be the result of a CAST.  We use the variable 'Op', which is the
9868   // non-casted variable when we check for possible users.
9869   switch (ArithOp.getOpcode()) {
9870   case ISD::ADD:
9871     // Due to an isel shortcoming, be conservative if this add is likely to be
9872     // selected as part of a load-modify-store instruction. When the root node
9873     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9874     // uses of other nodes in the match, such as the ADD in this case. This
9875     // leads to the ADD being left around and reselected, with the result being
9876     // two adds in the output.  Alas, even if none our users are stores, that
9877     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9878     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9879     // climbing the DAG back to the root, and it doesn't seem to be worth the
9880     // effort.
9881     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9882          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9883       if (UI->getOpcode() != ISD::CopyToReg &&
9884           UI->getOpcode() != ISD::SETCC &&
9885           UI->getOpcode() != ISD::STORE)
9886         goto default_case;
9887
9888     if (ConstantSDNode *C =
9889         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9890       // An add of one will be selected as an INC.
9891       if (C->getAPIntValue() == 1) {
9892         Opcode = X86ISD::INC;
9893         NumOperands = 1;
9894         break;
9895       }
9896
9897       // An add of negative one (subtract of one) will be selected as a DEC.
9898       if (C->getAPIntValue().isAllOnesValue()) {
9899         Opcode = X86ISD::DEC;
9900         NumOperands = 1;
9901         break;
9902       }
9903     }
9904
9905     // Otherwise use a regular EFLAGS-setting add.
9906     Opcode = X86ISD::ADD;
9907     NumOperands = 2;
9908     break;
9909   case ISD::SHL:
9910   case ISD::SRL:
9911     // If we have a constant logical shift that's only used in a comparison
9912     // against zero turn it into an equivalent AND. This allows turning it into
9913     // a TEST instruction later.
9914     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9915         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9916       EVT VT = Op.getValueType();
9917       unsigned BitWidth = VT.getSizeInBits();
9918       unsigned ShAmt = Op->getConstantOperandVal(1);
9919       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9920         break;
9921       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9922                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9923                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9924       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9925         break;
9926       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9927                                 DAG.getConstant(Mask, VT));
9928       DAG.ReplaceAllUsesWith(Op, New);
9929       Op = New;
9930     }
9931     break;
9932
9933   case ISD::AND:
9934     // If the primary and result isn't used, don't bother using X86ISD::AND,
9935     // because a TEST instruction will be better.
9936     if (!hasNonFlagsUse(Op))
9937       break;
9938     // FALL THROUGH
9939   case ISD::SUB:
9940   case ISD::OR:
9941   case ISD::XOR:
9942     // Due to the ISEL shortcoming noted above, be conservative if this op is
9943     // likely to be selected as part of a load-modify-store instruction.
9944     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9945            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9946       if (UI->getOpcode() == ISD::STORE)
9947         goto default_case;
9948
9949     // Otherwise use a regular EFLAGS-setting instruction.
9950     switch (ArithOp.getOpcode()) {
9951     default: llvm_unreachable("unexpected operator!");
9952     case ISD::SUB: Opcode = X86ISD::SUB; break;
9953     case ISD::XOR: Opcode = X86ISD::XOR; break;
9954     case ISD::AND: Opcode = X86ISD::AND; break;
9955     case ISD::OR: {
9956       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9957         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9958         if (EFLAGS.getNode())
9959           return EFLAGS;
9960       }
9961       Opcode = X86ISD::OR;
9962       break;
9963     }
9964     }
9965
9966     NumOperands = 2;
9967     break;
9968   case X86ISD::ADD:
9969   case X86ISD::SUB:
9970   case X86ISD::INC:
9971   case X86ISD::DEC:
9972   case X86ISD::OR:
9973   case X86ISD::XOR:
9974   case X86ISD::AND:
9975     return SDValue(Op.getNode(), 1);
9976   default:
9977   default_case:
9978     break;
9979   }
9980
9981   // If we found that truncation is beneficial, perform the truncation and
9982   // update 'Op'.
9983   if (NeedTruncation) {
9984     EVT VT = Op.getValueType();
9985     SDValue WideVal = Op->getOperand(0);
9986     EVT WideVT = WideVal.getValueType();
9987     unsigned ConvertedOp = 0;
9988     // Use a target machine opcode to prevent further DAGCombine
9989     // optimizations that may separate the arithmetic operations
9990     // from the setcc node.
9991     switch (WideVal.getOpcode()) {
9992       default: break;
9993       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9994       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9995       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9996       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9997       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9998     }
9999
10000     if (ConvertedOp) {
10001       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10002       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10003         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10004         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10005         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10006       }
10007     }
10008   }
10009
10010   if (Opcode == 0)
10011     // Emit a CMP with 0, which is the TEST pattern.
10012     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10013                        DAG.getConstant(0, Op.getValueType()));
10014
10015   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10016   SmallVector<SDValue, 4> Ops;
10017   for (unsigned i = 0; i != NumOperands; ++i)
10018     Ops.push_back(Op.getOperand(i));
10019
10020   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
10021   DAG.ReplaceAllUsesWith(Op, New);
10022   return SDValue(New.getNode(), 1);
10023 }
10024
10025 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10026 /// equivalent.
10027 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10028                                    SDLoc dl, SelectionDAG &DAG) const {
10029   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10030     if (C->getAPIntValue() == 0)
10031       return EmitTest(Op0, X86CC, dl, DAG);
10032
10033      if (Op0.getValueType() == MVT::i1)
10034        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10035   }
10036  
10037   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10038        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10039     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10040     // This avoids subregister aliasing issues. Keep the smaller reference 
10041     // if we're optimizing for size, however, as that'll allow better folding 
10042     // of memory operations.
10043     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10044         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10045              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10046         !Subtarget->isAtom()) {
10047       unsigned ExtendOp =
10048           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10049       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10050       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10051     }
10052     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10053     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10054     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10055                               Op0, Op1);
10056     return SDValue(Sub.getNode(), 1);
10057   }
10058   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10059 }
10060
10061 /// Convert a comparison if required by the subtarget.
10062 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10063                                                  SelectionDAG &DAG) const {
10064   // If the subtarget does not support the FUCOMI instruction, floating-point
10065   // comparisons have to be converted.
10066   if (Subtarget->hasCMov() ||
10067       Cmp.getOpcode() != X86ISD::CMP ||
10068       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10069       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10070     return Cmp;
10071
10072   // The instruction selector will select an FUCOM instruction instead of
10073   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10074   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10075   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10076   SDLoc dl(Cmp);
10077   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10078   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10079   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10080                             DAG.getConstant(8, MVT::i8));
10081   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10082   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10083 }
10084
10085 static bool isAllOnes(SDValue V) {
10086   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10087   return C && C->isAllOnesValue();
10088 }
10089
10090 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10091 /// if it's possible.
10092 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10093                                      SDLoc dl, SelectionDAG &DAG) const {
10094   SDValue Op0 = And.getOperand(0);
10095   SDValue Op1 = And.getOperand(1);
10096   if (Op0.getOpcode() == ISD::TRUNCATE)
10097     Op0 = Op0.getOperand(0);
10098   if (Op1.getOpcode() == ISD::TRUNCATE)
10099     Op1 = Op1.getOperand(0);
10100
10101   SDValue LHS, RHS;
10102   if (Op1.getOpcode() == ISD::SHL)
10103     std::swap(Op0, Op1);
10104   if (Op0.getOpcode() == ISD::SHL) {
10105     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10106       if (And00C->getZExtValue() == 1) {
10107         // If we looked past a truncate, check that it's only truncating away
10108         // known zeros.
10109         unsigned BitWidth = Op0.getValueSizeInBits();
10110         unsigned AndBitWidth = And.getValueSizeInBits();
10111         if (BitWidth > AndBitWidth) {
10112           APInt Zeros, Ones;
10113           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10114           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10115             return SDValue();
10116         }
10117         LHS = Op1;
10118         RHS = Op0.getOperand(1);
10119       }
10120   } else if (Op1.getOpcode() == ISD::Constant) {
10121     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10122     uint64_t AndRHSVal = AndRHS->getZExtValue();
10123     SDValue AndLHS = Op0;
10124
10125     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10126       LHS = AndLHS.getOperand(0);
10127       RHS = AndLHS.getOperand(1);
10128     }
10129
10130     // Use BT if the immediate can't be encoded in a TEST instruction.
10131     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10132       LHS = AndLHS;
10133       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10134     }
10135   }
10136
10137   if (LHS.getNode()) {
10138     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10139     // instruction.  Since the shift amount is in-range-or-undefined, we know
10140     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10141     // the encoding for the i16 version is larger than the i32 version.
10142     // Also promote i16 to i32 for performance / code size reason.
10143     if (LHS.getValueType() == MVT::i8 ||
10144         LHS.getValueType() == MVT::i16)
10145       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10146
10147     // If the operand types disagree, extend the shift amount to match.  Since
10148     // BT ignores high bits (like shifts) we can use anyextend.
10149     if (LHS.getValueType() != RHS.getValueType())
10150       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10151
10152     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10153     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10154     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10155                        DAG.getConstant(Cond, MVT::i8), BT);
10156   }
10157
10158   return SDValue();
10159 }
10160
10161 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10162 /// mask CMPs.
10163 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10164                               SDValue &Op1) {
10165   unsigned SSECC;
10166   bool Swap = false;
10167
10168   // SSE Condition code mapping:
10169   //  0 - EQ
10170   //  1 - LT
10171   //  2 - LE
10172   //  3 - UNORD
10173   //  4 - NEQ
10174   //  5 - NLT
10175   //  6 - NLE
10176   //  7 - ORD
10177   switch (SetCCOpcode) {
10178   default: llvm_unreachable("Unexpected SETCC condition");
10179   case ISD::SETOEQ:
10180   case ISD::SETEQ:  SSECC = 0; break;
10181   case ISD::SETOGT:
10182   case ISD::SETGT:  Swap = true; // Fallthrough
10183   case ISD::SETLT:
10184   case ISD::SETOLT: SSECC = 1; break;
10185   case ISD::SETOGE:
10186   case ISD::SETGE:  Swap = true; // Fallthrough
10187   case ISD::SETLE:
10188   case ISD::SETOLE: SSECC = 2; break;
10189   case ISD::SETUO:  SSECC = 3; break;
10190   case ISD::SETUNE:
10191   case ISD::SETNE:  SSECC = 4; break;
10192   case ISD::SETULE: Swap = true; // Fallthrough
10193   case ISD::SETUGE: SSECC = 5; break;
10194   case ISD::SETULT: Swap = true; // Fallthrough
10195   case ISD::SETUGT: SSECC = 6; break;
10196   case ISD::SETO:   SSECC = 7; break;
10197   case ISD::SETUEQ:
10198   case ISD::SETONE: SSECC = 8; break;
10199   }
10200   if (Swap)
10201     std::swap(Op0, Op1);
10202
10203   return SSECC;
10204 }
10205
10206 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10207 // ones, and then concatenate the result back.
10208 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10209   MVT VT = Op.getSimpleValueType();
10210
10211   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10212          "Unsupported value type for operation");
10213
10214   unsigned NumElems = VT.getVectorNumElements();
10215   SDLoc dl(Op);
10216   SDValue CC = Op.getOperand(2);
10217
10218   // Extract the LHS vectors
10219   SDValue LHS = Op.getOperand(0);
10220   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10221   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10222
10223   // Extract the RHS vectors
10224   SDValue RHS = Op.getOperand(1);
10225   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10226   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10227
10228   // Issue the operation on the smaller types and concatenate the result back
10229   MVT EltVT = VT.getVectorElementType();
10230   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10231   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10232                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10233                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10234 }
10235
10236 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10237                                      const X86Subtarget *Subtarget) {
10238   SDValue Op0 = Op.getOperand(0);
10239   SDValue Op1 = Op.getOperand(1);
10240   SDValue CC = Op.getOperand(2);
10241   MVT VT = Op.getSimpleValueType();
10242   SDLoc dl(Op);
10243
10244   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10245          Op.getValueType().getScalarType() == MVT::i1 &&
10246          "Cannot set masked compare for this operation");
10247
10248   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10249   unsigned  Opc = 0;
10250   bool Unsigned = false;
10251   bool Swap = false;
10252   unsigned SSECC;
10253   switch (SetCCOpcode) {
10254   default: llvm_unreachable("Unexpected SETCC condition");
10255   case ISD::SETNE:  SSECC = 4; break;
10256   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10257   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10258   case ISD::SETLT:  Swap = true; //fall-through
10259   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10260   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10261   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10262   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10263   case ISD::SETULE: Unsigned = true; //fall-through
10264   case ISD::SETLE:  SSECC = 2; break;
10265   }
10266
10267   if (Swap)
10268     std::swap(Op0, Op1);
10269   if (Opc)
10270     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10271   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10272   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10273                      DAG.getConstant(SSECC, MVT::i8));
10274 }
10275
10276 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10277 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10278 /// return an empty value.
10279 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10280 {
10281   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10282   if (!BV)
10283     return SDValue();
10284
10285   MVT VT = Op1.getSimpleValueType();
10286   MVT EVT = VT.getVectorElementType();
10287   unsigned n = VT.getVectorNumElements();
10288   SmallVector<SDValue, 8> ULTOp1;
10289
10290   for (unsigned i = 0; i < n; ++i) {
10291     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10292     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10293       return SDValue();
10294
10295     // Avoid underflow.
10296     APInt Val = Elt->getAPIntValue();
10297     if (Val == 0)
10298       return SDValue();
10299
10300     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10301   }
10302
10303   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10304 }
10305
10306 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10307                            SelectionDAG &DAG) {
10308   SDValue Op0 = Op.getOperand(0);
10309   SDValue Op1 = Op.getOperand(1);
10310   SDValue CC = Op.getOperand(2);
10311   MVT VT = Op.getSimpleValueType();
10312   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10313   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10314   SDLoc dl(Op);
10315
10316   if (isFP) {
10317 #ifndef NDEBUG
10318     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10319     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10320 #endif
10321
10322     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10323     unsigned Opc = X86ISD::CMPP;
10324     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10325       assert(VT.getVectorNumElements() <= 16);
10326       Opc = X86ISD::CMPM;
10327     }
10328     // In the two special cases we can't handle, emit two comparisons.
10329     if (SSECC == 8) {
10330       unsigned CC0, CC1;
10331       unsigned CombineOpc;
10332       if (SetCCOpcode == ISD::SETUEQ) {
10333         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10334       } else {
10335         assert(SetCCOpcode == ISD::SETONE);
10336         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10337       }
10338
10339       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10340                                  DAG.getConstant(CC0, MVT::i8));
10341       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10342                                  DAG.getConstant(CC1, MVT::i8));
10343       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10344     }
10345     // Handle all other FP comparisons here.
10346     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10347                        DAG.getConstant(SSECC, MVT::i8));
10348   }
10349
10350   // Break 256-bit integer vector compare into smaller ones.
10351   if (VT.is256BitVector() && !Subtarget->hasInt256())
10352     return Lower256IntVSETCC(Op, DAG);
10353
10354   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10355   EVT OpVT = Op1.getValueType();
10356   if (Subtarget->hasAVX512()) {
10357     if (Op1.getValueType().is512BitVector() ||
10358         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10359       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10360
10361     // In AVX-512 architecture setcc returns mask with i1 elements,
10362     // But there is no compare instruction for i8 and i16 elements.
10363     // We are not talking about 512-bit operands in this case, these
10364     // types are illegal.
10365     if (MaskResult &&
10366         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10367          OpVT.getVectorElementType().getSizeInBits() >= 8))
10368       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10369                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10370   }
10371
10372   // We are handling one of the integer comparisons here.  Since SSE only has
10373   // GT and EQ comparisons for integer, swapping operands and multiple
10374   // operations may be required for some comparisons.
10375   unsigned Opc;
10376   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10377   bool Subus = false;
10378
10379   switch (SetCCOpcode) {
10380   default: llvm_unreachable("Unexpected SETCC condition");
10381   case ISD::SETNE:  Invert = true;
10382   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10383   case ISD::SETLT:  Swap = true;
10384   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10385   case ISD::SETGE:  Swap = true;
10386   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10387                     Invert = true; break;
10388   case ISD::SETULT: Swap = true;
10389   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10390                     FlipSigns = true; break;
10391   case ISD::SETUGE: Swap = true;
10392   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10393                     FlipSigns = true; Invert = true; break;
10394   }
10395
10396   // Special case: Use min/max operations for SETULE/SETUGE
10397   MVT VET = VT.getVectorElementType();
10398   bool hasMinMax =
10399        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10400     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10401
10402   if (hasMinMax) {
10403     switch (SetCCOpcode) {
10404     default: break;
10405     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10406     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10407     }
10408
10409     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10410   }
10411
10412   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10413   if (!MinMax && hasSubus) {
10414     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10415     // Op0 u<= Op1:
10416     //   t = psubus Op0, Op1
10417     //   pcmpeq t, <0..0>
10418     switch (SetCCOpcode) {
10419     default: break;
10420     case ISD::SETULT: {
10421       // If the comparison is against a constant we can turn this into a
10422       // setule.  With psubus, setule does not require a swap.  This is
10423       // beneficial because the constant in the register is no longer
10424       // destructed as the destination so it can be hoisted out of a loop.
10425       // Only do this pre-AVX since vpcmp* is no longer destructive.
10426       if (Subtarget->hasAVX())
10427         break;
10428       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10429       if (ULEOp1.getNode()) {
10430         Op1 = ULEOp1;
10431         Subus = true; Invert = false; Swap = false;
10432       }
10433       break;
10434     }
10435     // Psubus is better than flip-sign because it requires no inversion.
10436     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10437     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10438     }
10439
10440     if (Subus) {
10441       Opc = X86ISD::SUBUS;
10442       FlipSigns = false;
10443     }
10444   }
10445
10446   if (Swap)
10447     std::swap(Op0, Op1);
10448
10449   // Check that the operation in question is available (most are plain SSE2,
10450   // but PCMPGTQ and PCMPEQQ have different requirements).
10451   if (VT == MVT::v2i64) {
10452     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10453       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10454
10455       // First cast everything to the right type.
10456       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10457       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10458
10459       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10460       // bits of the inputs before performing those operations. The lower
10461       // compare is always unsigned.
10462       SDValue SB;
10463       if (FlipSigns) {
10464         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10465       } else {
10466         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10467         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10468         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10469                          Sign, Zero, Sign, Zero);
10470       }
10471       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10472       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10473
10474       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10475       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10476       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10477
10478       // Create masks for only the low parts/high parts of the 64 bit integers.
10479       static const int MaskHi[] = { 1, 1, 3, 3 };
10480       static const int MaskLo[] = { 0, 0, 2, 2 };
10481       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10482       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10483       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10484
10485       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10486       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10487
10488       if (Invert)
10489         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10490
10491       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10492     }
10493
10494     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10495       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10496       // pcmpeqd + pshufd + pand.
10497       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10498
10499       // First cast everything to the right type.
10500       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10501       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10502
10503       // Do the compare.
10504       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10505
10506       // Make sure the lower and upper halves are both all-ones.
10507       static const int Mask[] = { 1, 0, 3, 2 };
10508       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10509       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10510
10511       if (Invert)
10512         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10513
10514       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10515     }
10516   }
10517
10518   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10519   // bits of the inputs before performing those operations.
10520   if (FlipSigns) {
10521     EVT EltVT = VT.getVectorElementType();
10522     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10523     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10524     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10525   }
10526
10527   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10528
10529   // If the logical-not of the result is required, perform that now.
10530   if (Invert)
10531     Result = DAG.getNOT(dl, Result, VT);
10532
10533   if (MinMax)
10534     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10535
10536   if (Subus)
10537     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10538                          getZeroVector(VT, Subtarget, DAG, dl));
10539
10540   return Result;
10541 }
10542
10543 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10544
10545   MVT VT = Op.getSimpleValueType();
10546
10547   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10548
10549   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10550          && "SetCC type must be 8-bit or 1-bit integer");
10551   SDValue Op0 = Op.getOperand(0);
10552   SDValue Op1 = Op.getOperand(1);
10553   SDLoc dl(Op);
10554   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10555
10556   // Optimize to BT if possible.
10557   // Lower (X & (1 << N)) == 0 to BT(X, N).
10558   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10559   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10560   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10561       Op1.getOpcode() == ISD::Constant &&
10562       cast<ConstantSDNode>(Op1)->isNullValue() &&
10563       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10564     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10565     if (NewSetCC.getNode())
10566       return NewSetCC;
10567   }
10568
10569   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10570   // these.
10571   if (Op1.getOpcode() == ISD::Constant &&
10572       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10573        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10574       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10575
10576     // If the input is a setcc, then reuse the input setcc or use a new one with
10577     // the inverted condition.
10578     if (Op0.getOpcode() == X86ISD::SETCC) {
10579       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10580       bool Invert = (CC == ISD::SETNE) ^
10581         cast<ConstantSDNode>(Op1)->isNullValue();
10582       if (!Invert)
10583         return Op0;
10584
10585       CCode = X86::GetOppositeBranchCondition(CCode);
10586       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10587                                   DAG.getConstant(CCode, MVT::i8),
10588                                   Op0.getOperand(1));
10589       if (VT == MVT::i1)
10590         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10591       return SetCC;
10592     }
10593   }
10594   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10595       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10596       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10597
10598     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10599     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10600   }
10601
10602   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10603   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10604   if (X86CC == X86::COND_INVALID)
10605     return SDValue();
10606
10607   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10608   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10609   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10610                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10611   if (VT == MVT::i1)
10612     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10613   return SetCC;
10614 }
10615
10616 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10617 static bool isX86LogicalCmp(SDValue Op) {
10618   unsigned Opc = Op.getNode()->getOpcode();
10619   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10620       Opc == X86ISD::SAHF)
10621     return true;
10622   if (Op.getResNo() == 1 &&
10623       (Opc == X86ISD::ADD ||
10624        Opc == X86ISD::SUB ||
10625        Opc == X86ISD::ADC ||
10626        Opc == X86ISD::SBB ||
10627        Opc == X86ISD::SMUL ||
10628        Opc == X86ISD::UMUL ||
10629        Opc == X86ISD::INC ||
10630        Opc == X86ISD::DEC ||
10631        Opc == X86ISD::OR ||
10632        Opc == X86ISD::XOR ||
10633        Opc == X86ISD::AND))
10634     return true;
10635
10636   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10637     return true;
10638
10639   return false;
10640 }
10641
10642 static bool isZero(SDValue V) {
10643   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10644   return C && C->isNullValue();
10645 }
10646
10647 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10648   if (V.getOpcode() != ISD::TRUNCATE)
10649     return false;
10650
10651   SDValue VOp0 = V.getOperand(0);
10652   unsigned InBits = VOp0.getValueSizeInBits();
10653   unsigned Bits = V.getValueSizeInBits();
10654   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10655 }
10656
10657 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10658   bool addTest = true;
10659   SDValue Cond  = Op.getOperand(0);
10660   SDValue Op1 = Op.getOperand(1);
10661   SDValue Op2 = Op.getOperand(2);
10662   SDLoc DL(Op);
10663   EVT VT = Op1.getValueType();
10664   SDValue CC;
10665
10666   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10667   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10668   // sequence later on.
10669   if (Cond.getOpcode() == ISD::SETCC &&
10670       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10671        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10672       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10673     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10674     int SSECC = translateX86FSETCC(
10675         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10676
10677     if (SSECC != 8) {
10678       if (Subtarget->hasAVX512()) {
10679         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10680                                   DAG.getConstant(SSECC, MVT::i8));
10681         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10682       }
10683       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10684                                 DAG.getConstant(SSECC, MVT::i8));
10685       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10686       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10687       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10688     }
10689   }
10690
10691   if (Cond.getOpcode() == ISD::SETCC) {
10692     SDValue NewCond = LowerSETCC(Cond, DAG);
10693     if (NewCond.getNode())
10694       Cond = NewCond;
10695   }
10696
10697   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10698   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10699   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10700   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10701   if (Cond.getOpcode() == X86ISD::SETCC &&
10702       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10703       isZero(Cond.getOperand(1).getOperand(1))) {
10704     SDValue Cmp = Cond.getOperand(1);
10705
10706     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10707
10708     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10709         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10710       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10711
10712       SDValue CmpOp0 = Cmp.getOperand(0);
10713       // Apply further optimizations for special cases
10714       // (select (x != 0), -1, 0) -> neg & sbb
10715       // (select (x == 0), 0, -1) -> neg & sbb
10716       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10717         if (YC->isNullValue() &&
10718             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10719           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10720           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10721                                     DAG.getConstant(0, CmpOp0.getValueType()),
10722                                     CmpOp0);
10723           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10724                                     DAG.getConstant(X86::COND_B, MVT::i8),
10725                                     SDValue(Neg.getNode(), 1));
10726           return Res;
10727         }
10728
10729       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10730                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10731       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10732
10733       SDValue Res =   // Res = 0 or -1.
10734         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10735                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10736
10737       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10738         Res = DAG.getNOT(DL, Res, Res.getValueType());
10739
10740       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10741       if (!N2C || !N2C->isNullValue())
10742         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10743       return Res;
10744     }
10745   }
10746
10747   // Look past (and (setcc_carry (cmp ...)), 1).
10748   if (Cond.getOpcode() == ISD::AND &&
10749       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10750     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10751     if (C && C->getAPIntValue() == 1)
10752       Cond = Cond.getOperand(0);
10753   }
10754
10755   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10756   // setting operand in place of the X86ISD::SETCC.
10757   unsigned CondOpcode = Cond.getOpcode();
10758   if (CondOpcode == X86ISD::SETCC ||
10759       CondOpcode == X86ISD::SETCC_CARRY) {
10760     CC = Cond.getOperand(0);
10761
10762     SDValue Cmp = Cond.getOperand(1);
10763     unsigned Opc = Cmp.getOpcode();
10764     MVT VT = Op.getSimpleValueType();
10765
10766     bool IllegalFPCMov = false;
10767     if (VT.isFloatingPoint() && !VT.isVector() &&
10768         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10769       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10770
10771     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10772         Opc == X86ISD::BT) { // FIXME
10773       Cond = Cmp;
10774       addTest = false;
10775     }
10776   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10777              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10778              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10779               Cond.getOperand(0).getValueType() != MVT::i8)) {
10780     SDValue LHS = Cond.getOperand(0);
10781     SDValue RHS = Cond.getOperand(1);
10782     unsigned X86Opcode;
10783     unsigned X86Cond;
10784     SDVTList VTs;
10785     switch (CondOpcode) {
10786     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10787     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10788     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10789     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10790     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10791     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10792     default: llvm_unreachable("unexpected overflowing operator");
10793     }
10794     if (CondOpcode == ISD::UMULO)
10795       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10796                           MVT::i32);
10797     else
10798       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10799
10800     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10801
10802     if (CondOpcode == ISD::UMULO)
10803       Cond = X86Op.getValue(2);
10804     else
10805       Cond = X86Op.getValue(1);
10806
10807     CC = DAG.getConstant(X86Cond, MVT::i8);
10808     addTest = false;
10809   }
10810
10811   if (addTest) {
10812     // Look pass the truncate if the high bits are known zero.
10813     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10814         Cond = Cond.getOperand(0);
10815
10816     // We know the result of AND is compared against zero. Try to match
10817     // it to BT.
10818     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10819       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10820       if (NewSetCC.getNode()) {
10821         CC = NewSetCC.getOperand(0);
10822         Cond = NewSetCC.getOperand(1);
10823         addTest = false;
10824       }
10825     }
10826   }
10827
10828   if (addTest) {
10829     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10830     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10831   }
10832
10833   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10834   // a <  b ?  0 : -1 -> RES = setcc_carry
10835   // a >= b ? -1 :  0 -> RES = setcc_carry
10836   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10837   if (Cond.getOpcode() == X86ISD::SUB) {
10838     Cond = ConvertCmpIfNecessary(Cond, DAG);
10839     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10840
10841     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10842         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10843       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10844                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10845       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10846         return DAG.getNOT(DL, Res, Res.getValueType());
10847       return Res;
10848     }
10849   }
10850
10851   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10852   // widen the cmov and push the truncate through. This avoids introducing a new
10853   // branch during isel and doesn't add any extensions.
10854   if (Op.getValueType() == MVT::i8 &&
10855       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10856     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10857     if (T1.getValueType() == T2.getValueType() &&
10858         // Blacklist CopyFromReg to avoid partial register stalls.
10859         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10860       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10861       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10862       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10863     }
10864   }
10865
10866   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10867   // condition is true.
10868   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10869   SDValue Ops[] = { Op2, Op1, CC, Cond };
10870   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10871 }
10872
10873 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10874   MVT VT = Op->getSimpleValueType(0);
10875   SDValue In = Op->getOperand(0);
10876   MVT InVT = In.getSimpleValueType();
10877   SDLoc dl(Op);
10878
10879   unsigned int NumElts = VT.getVectorNumElements();
10880   if (NumElts != 8 && NumElts != 16)
10881     return SDValue();
10882
10883   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10884     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10885
10886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10887   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10888
10889   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10890   Constant *C = ConstantInt::get(*DAG.getContext(),
10891     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10892
10893   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10894   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10895   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10896                           MachinePointerInfo::getConstantPool(),
10897                           false, false, false, Alignment);
10898   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10899   if (VT.is512BitVector())
10900     return Brcst;
10901   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10902 }
10903
10904 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10905                                 SelectionDAG &DAG) {
10906   MVT VT = Op->getSimpleValueType(0);
10907   SDValue In = Op->getOperand(0);
10908   MVT InVT = In.getSimpleValueType();
10909   SDLoc dl(Op);
10910
10911   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10912     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10913
10914   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10915       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10916       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10917     return SDValue();
10918
10919   if (Subtarget->hasInt256())
10920     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10921
10922   // Optimize vectors in AVX mode
10923   // Sign extend  v8i16 to v8i32 and
10924   //              v4i32 to v4i64
10925   //
10926   // Divide input vector into two parts
10927   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10928   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10929   // concat the vectors to original VT
10930
10931   unsigned NumElems = InVT.getVectorNumElements();
10932   SDValue Undef = DAG.getUNDEF(InVT);
10933
10934   SmallVector<int,8> ShufMask1(NumElems, -1);
10935   for (unsigned i = 0; i != NumElems/2; ++i)
10936     ShufMask1[i] = i;
10937
10938   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10939
10940   SmallVector<int,8> ShufMask2(NumElems, -1);
10941   for (unsigned i = 0; i != NumElems/2; ++i)
10942     ShufMask2[i] = i + NumElems/2;
10943
10944   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10945
10946   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10947                                 VT.getVectorNumElements()/2);
10948
10949   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10950   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10951
10952   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10953 }
10954
10955 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10956 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10957 // from the AND / OR.
10958 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10959   Opc = Op.getOpcode();
10960   if (Opc != ISD::OR && Opc != ISD::AND)
10961     return false;
10962   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10963           Op.getOperand(0).hasOneUse() &&
10964           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10965           Op.getOperand(1).hasOneUse());
10966 }
10967
10968 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10969 // 1 and that the SETCC node has a single use.
10970 static bool isXor1OfSetCC(SDValue Op) {
10971   if (Op.getOpcode() != ISD::XOR)
10972     return false;
10973   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10974   if (N1C && N1C->getAPIntValue() == 1) {
10975     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10976       Op.getOperand(0).hasOneUse();
10977   }
10978   return false;
10979 }
10980
10981 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10982   bool addTest = true;
10983   SDValue Chain = Op.getOperand(0);
10984   SDValue Cond  = Op.getOperand(1);
10985   SDValue Dest  = Op.getOperand(2);
10986   SDLoc dl(Op);
10987   SDValue CC;
10988   bool Inverted = false;
10989
10990   if (Cond.getOpcode() == ISD::SETCC) {
10991     // Check for setcc([su]{add,sub,mul}o == 0).
10992     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10993         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10994         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10995         Cond.getOperand(0).getResNo() == 1 &&
10996         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10997          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10998          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10999          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11000          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11001          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11002       Inverted = true;
11003       Cond = Cond.getOperand(0);
11004     } else {
11005       SDValue NewCond = LowerSETCC(Cond, DAG);
11006       if (NewCond.getNode())
11007         Cond = NewCond;
11008     }
11009   }
11010 #if 0
11011   // FIXME: LowerXALUO doesn't handle these!!
11012   else if (Cond.getOpcode() == X86ISD::ADD  ||
11013            Cond.getOpcode() == X86ISD::SUB  ||
11014            Cond.getOpcode() == X86ISD::SMUL ||
11015            Cond.getOpcode() == X86ISD::UMUL)
11016     Cond = LowerXALUO(Cond, DAG);
11017 #endif
11018
11019   // Look pass (and (setcc_carry (cmp ...)), 1).
11020   if (Cond.getOpcode() == ISD::AND &&
11021       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11022     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11023     if (C && C->getAPIntValue() == 1)
11024       Cond = Cond.getOperand(0);
11025   }
11026
11027   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11028   // setting operand in place of the X86ISD::SETCC.
11029   unsigned CondOpcode = Cond.getOpcode();
11030   if (CondOpcode == X86ISD::SETCC ||
11031       CondOpcode == X86ISD::SETCC_CARRY) {
11032     CC = Cond.getOperand(0);
11033
11034     SDValue Cmp = Cond.getOperand(1);
11035     unsigned Opc = Cmp.getOpcode();
11036     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11037     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11038       Cond = Cmp;
11039       addTest = false;
11040     } else {
11041       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11042       default: break;
11043       case X86::COND_O:
11044       case X86::COND_B:
11045         // These can only come from an arithmetic instruction with overflow,
11046         // e.g. SADDO, UADDO.
11047         Cond = Cond.getNode()->getOperand(1);
11048         addTest = false;
11049         break;
11050       }
11051     }
11052   }
11053   CondOpcode = Cond.getOpcode();
11054   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11055       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11056       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11057        Cond.getOperand(0).getValueType() != MVT::i8)) {
11058     SDValue LHS = Cond.getOperand(0);
11059     SDValue RHS = Cond.getOperand(1);
11060     unsigned X86Opcode;
11061     unsigned X86Cond;
11062     SDVTList VTs;
11063     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11064     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11065     // X86ISD::INC).
11066     switch (CondOpcode) {
11067     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11068     case ISD::SADDO:
11069       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11070         if (C->isOne()) {
11071           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11072           break;
11073         }
11074       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11075     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11076     case ISD::SSUBO:
11077       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11078         if (C->isOne()) {
11079           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11080           break;
11081         }
11082       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11083     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11084     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11085     default: llvm_unreachable("unexpected overflowing operator");
11086     }
11087     if (Inverted)
11088       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11089     if (CondOpcode == ISD::UMULO)
11090       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11091                           MVT::i32);
11092     else
11093       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11094
11095     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11096
11097     if (CondOpcode == ISD::UMULO)
11098       Cond = X86Op.getValue(2);
11099     else
11100       Cond = X86Op.getValue(1);
11101
11102     CC = DAG.getConstant(X86Cond, MVT::i8);
11103     addTest = false;
11104   } else {
11105     unsigned CondOpc;
11106     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11107       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11108       if (CondOpc == ISD::OR) {
11109         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11110         // two branches instead of an explicit OR instruction with a
11111         // separate test.
11112         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11113             isX86LogicalCmp(Cmp)) {
11114           CC = Cond.getOperand(0).getOperand(0);
11115           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11116                               Chain, Dest, CC, Cmp);
11117           CC = Cond.getOperand(1).getOperand(0);
11118           Cond = Cmp;
11119           addTest = false;
11120         }
11121       } else { // ISD::AND
11122         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11123         // two branches instead of an explicit AND instruction with a
11124         // separate test. However, we only do this if this block doesn't
11125         // have a fall-through edge, because this requires an explicit
11126         // jmp when the condition is false.
11127         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11128             isX86LogicalCmp(Cmp) &&
11129             Op.getNode()->hasOneUse()) {
11130           X86::CondCode CCode =
11131             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11132           CCode = X86::GetOppositeBranchCondition(CCode);
11133           CC = DAG.getConstant(CCode, MVT::i8);
11134           SDNode *User = *Op.getNode()->use_begin();
11135           // Look for an unconditional branch following this conditional branch.
11136           // We need this because we need to reverse the successors in order
11137           // to implement FCMP_OEQ.
11138           if (User->getOpcode() == ISD::BR) {
11139             SDValue FalseBB = User->getOperand(1);
11140             SDNode *NewBR =
11141               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11142             assert(NewBR == User);
11143             (void)NewBR;
11144             Dest = FalseBB;
11145
11146             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11147                                 Chain, Dest, CC, Cmp);
11148             X86::CondCode CCode =
11149               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11150             CCode = X86::GetOppositeBranchCondition(CCode);
11151             CC = DAG.getConstant(CCode, MVT::i8);
11152             Cond = Cmp;
11153             addTest = false;
11154           }
11155         }
11156       }
11157     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11158       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11159       // It should be transformed during dag combiner except when the condition
11160       // is set by a arithmetics with overflow node.
11161       X86::CondCode CCode =
11162         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11163       CCode = X86::GetOppositeBranchCondition(CCode);
11164       CC = DAG.getConstant(CCode, MVT::i8);
11165       Cond = Cond.getOperand(0).getOperand(1);
11166       addTest = false;
11167     } else if (Cond.getOpcode() == ISD::SETCC &&
11168                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11169       // For FCMP_OEQ, we can emit
11170       // two branches instead of an explicit AND instruction with a
11171       // separate test. However, we only do this if this block doesn't
11172       // have a fall-through edge, because this requires an explicit
11173       // jmp when the condition is false.
11174       if (Op.getNode()->hasOneUse()) {
11175         SDNode *User = *Op.getNode()->use_begin();
11176         // Look for an unconditional branch following this conditional branch.
11177         // We need this because we need to reverse the successors in order
11178         // to implement FCMP_OEQ.
11179         if (User->getOpcode() == ISD::BR) {
11180           SDValue FalseBB = User->getOperand(1);
11181           SDNode *NewBR =
11182             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11183           assert(NewBR == User);
11184           (void)NewBR;
11185           Dest = FalseBB;
11186
11187           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11188                                     Cond.getOperand(0), Cond.getOperand(1));
11189           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11190           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11191           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11192                               Chain, Dest, CC, Cmp);
11193           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11194           Cond = Cmp;
11195           addTest = false;
11196         }
11197       }
11198     } else if (Cond.getOpcode() == ISD::SETCC &&
11199                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11200       // For FCMP_UNE, we can emit
11201       // two branches instead of an explicit AND instruction with a
11202       // separate test. However, we only do this if this block doesn't
11203       // have a fall-through edge, because this requires an explicit
11204       // jmp when the condition is false.
11205       if (Op.getNode()->hasOneUse()) {
11206         SDNode *User = *Op.getNode()->use_begin();
11207         // Look for an unconditional branch following this conditional branch.
11208         // We need this because we need to reverse the successors in order
11209         // to implement FCMP_UNE.
11210         if (User->getOpcode() == ISD::BR) {
11211           SDValue FalseBB = User->getOperand(1);
11212           SDNode *NewBR =
11213             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11214           assert(NewBR == User);
11215           (void)NewBR;
11216
11217           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11218                                     Cond.getOperand(0), Cond.getOperand(1));
11219           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11220           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11221           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11222                               Chain, Dest, CC, Cmp);
11223           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11224           Cond = Cmp;
11225           addTest = false;
11226           Dest = FalseBB;
11227         }
11228       }
11229     }
11230   }
11231
11232   if (addTest) {
11233     // Look pass the truncate if the high bits are known zero.
11234     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11235         Cond = Cond.getOperand(0);
11236
11237     // We know the result of AND is compared against zero. Try to match
11238     // it to BT.
11239     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11240       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11241       if (NewSetCC.getNode()) {
11242         CC = NewSetCC.getOperand(0);
11243         Cond = NewSetCC.getOperand(1);
11244         addTest = false;
11245       }
11246     }
11247   }
11248
11249   if (addTest) {
11250     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11251     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11252   }
11253   Cond = ConvertCmpIfNecessary(Cond, DAG);
11254   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11255                      Chain, Dest, CC, Cond);
11256 }
11257
11258 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11259 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11260 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11261 // that the guard pages used by the OS virtual memory manager are allocated in
11262 // correct sequence.
11263 SDValue
11264 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11265                                            SelectionDAG &DAG) const {
11266   MachineFunction &MF = DAG.getMachineFunction();
11267   bool SplitStack = MF.shouldSplitStack();
11268   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11269                SplitStack;
11270   SDLoc dl(Op);
11271
11272   if (!Lower) {
11273     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11274     SDNode* Node = Op.getNode();
11275
11276     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11277     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11278         " not tell us which reg is the stack pointer!");
11279     EVT VT = Node->getValueType(0);
11280     SDValue Tmp1 = SDValue(Node, 0);
11281     SDValue Tmp2 = SDValue(Node, 1);
11282     SDValue Tmp3 = Node->getOperand(2);
11283     SDValue Chain = Tmp1.getOperand(0);
11284
11285     // Chain the dynamic stack allocation so that it doesn't modify the stack
11286     // pointer when other instructions are using the stack.
11287     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11288         SDLoc(Node));
11289
11290     SDValue Size = Tmp2.getOperand(1);
11291     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11292     Chain = SP.getValue(1);
11293     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11294     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11295     unsigned StackAlign = TFI.getStackAlignment();
11296     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11297     if (Align > StackAlign)
11298       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11299           DAG.getConstant(-(uint64_t)Align, VT));
11300     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11301
11302     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11303         DAG.getIntPtrConstant(0, true), SDValue(),
11304         SDLoc(Node));
11305
11306     SDValue Ops[2] = { Tmp1, Tmp2 };
11307     return DAG.getMergeValues(Ops, 2, dl);
11308   }
11309
11310   // Get the inputs.
11311   SDValue Chain = Op.getOperand(0);
11312   SDValue Size  = Op.getOperand(1);
11313   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11314   EVT VT = Op.getNode()->getValueType(0);
11315
11316   bool Is64Bit = Subtarget->is64Bit();
11317   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11318
11319   if (SplitStack) {
11320     MachineRegisterInfo &MRI = MF.getRegInfo();
11321
11322     if (Is64Bit) {
11323       // The 64 bit implementation of segmented stacks needs to clobber both r10
11324       // r11. This makes it impossible to use it along with nested parameters.
11325       const Function *F = MF.getFunction();
11326
11327       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11328            I != E; ++I)
11329         if (I->hasNestAttr())
11330           report_fatal_error("Cannot use segmented stacks with functions that "
11331                              "have nested arguments.");
11332     }
11333
11334     const TargetRegisterClass *AddrRegClass =
11335       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11336     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11337     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11338     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11339                                 DAG.getRegister(Vreg, SPTy));
11340     SDValue Ops1[2] = { Value, Chain };
11341     return DAG.getMergeValues(Ops1, 2, dl);
11342   } else {
11343     SDValue Flag;
11344     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11345
11346     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11347     Flag = Chain.getValue(1);
11348     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11349
11350     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11351
11352     const X86RegisterInfo *RegInfo =
11353       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11354     unsigned SPReg = RegInfo->getStackRegister();
11355     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11356     Chain = SP.getValue(1);
11357
11358     if (Align) {
11359       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11360                        DAG.getConstant(-(uint64_t)Align, VT));
11361       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11362     }
11363
11364     SDValue Ops1[2] = { SP, Chain };
11365     return DAG.getMergeValues(Ops1, 2, dl);
11366   }
11367 }
11368
11369 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11370   MachineFunction &MF = DAG.getMachineFunction();
11371   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11372
11373   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11374   SDLoc DL(Op);
11375
11376   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11377     // vastart just stores the address of the VarArgsFrameIndex slot into the
11378     // memory location argument.
11379     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11380                                    getPointerTy());
11381     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11382                         MachinePointerInfo(SV), false, false, 0);
11383   }
11384
11385   // __va_list_tag:
11386   //   gp_offset         (0 - 6 * 8)
11387   //   fp_offset         (48 - 48 + 8 * 16)
11388   //   overflow_arg_area (point to parameters coming in memory).
11389   //   reg_save_area
11390   SmallVector<SDValue, 8> MemOps;
11391   SDValue FIN = Op.getOperand(1);
11392   // Store gp_offset
11393   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11394                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11395                                                MVT::i32),
11396                                FIN, MachinePointerInfo(SV), false, false, 0);
11397   MemOps.push_back(Store);
11398
11399   // Store fp_offset
11400   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11401                     FIN, DAG.getIntPtrConstant(4));
11402   Store = DAG.getStore(Op.getOperand(0), DL,
11403                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11404                                        MVT::i32),
11405                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11406   MemOps.push_back(Store);
11407
11408   // Store ptr to overflow_arg_area
11409   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11410                     FIN, DAG.getIntPtrConstant(4));
11411   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11412                                     getPointerTy());
11413   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11414                        MachinePointerInfo(SV, 8),
11415                        false, false, 0);
11416   MemOps.push_back(Store);
11417
11418   // Store ptr to reg_save_area.
11419   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11420                     FIN, DAG.getIntPtrConstant(8));
11421   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11422                                     getPointerTy());
11423   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11424                        MachinePointerInfo(SV, 16), false, false, 0);
11425   MemOps.push_back(Store);
11426   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11427                      &MemOps[0], MemOps.size());
11428 }
11429
11430 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11431   assert(Subtarget->is64Bit() &&
11432          "LowerVAARG only handles 64-bit va_arg!");
11433   assert((Subtarget->isTargetLinux() ||
11434           Subtarget->isTargetDarwin()) &&
11435           "Unhandled target in LowerVAARG");
11436   assert(Op.getNode()->getNumOperands() == 4);
11437   SDValue Chain = Op.getOperand(0);
11438   SDValue SrcPtr = Op.getOperand(1);
11439   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11440   unsigned Align = Op.getConstantOperandVal(3);
11441   SDLoc dl(Op);
11442
11443   EVT ArgVT = Op.getNode()->getValueType(0);
11444   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11445   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11446   uint8_t ArgMode;
11447
11448   // Decide which area this value should be read from.
11449   // TODO: Implement the AMD64 ABI in its entirety. This simple
11450   // selection mechanism works only for the basic types.
11451   if (ArgVT == MVT::f80) {
11452     llvm_unreachable("va_arg for f80 not yet implemented");
11453   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11454     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11455   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11456     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11457   } else {
11458     llvm_unreachable("Unhandled argument type in LowerVAARG");
11459   }
11460
11461   if (ArgMode == 2) {
11462     // Sanity Check: Make sure using fp_offset makes sense.
11463     assert(!getTargetMachine().Options.UseSoftFloat &&
11464            !(DAG.getMachineFunction()
11465                 .getFunction()->getAttributes()
11466                 .hasAttribute(AttributeSet::FunctionIndex,
11467                               Attribute::NoImplicitFloat)) &&
11468            Subtarget->hasSSE1());
11469   }
11470
11471   // Insert VAARG_64 node into the DAG
11472   // VAARG_64 returns two values: Variable Argument Address, Chain
11473   SmallVector<SDValue, 11> InstOps;
11474   InstOps.push_back(Chain);
11475   InstOps.push_back(SrcPtr);
11476   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11477   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11478   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11479   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11480   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11481                                           VTs, &InstOps[0], InstOps.size(),
11482                                           MVT::i64,
11483                                           MachinePointerInfo(SV),
11484                                           /*Align=*/0,
11485                                           /*Volatile=*/false,
11486                                           /*ReadMem=*/true,
11487                                           /*WriteMem=*/true);
11488   Chain = VAARG.getValue(1);
11489
11490   // Load the next argument and return it
11491   return DAG.getLoad(ArgVT, dl,
11492                      Chain,
11493                      VAARG,
11494                      MachinePointerInfo(),
11495                      false, false, false, 0);
11496 }
11497
11498 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11499                            SelectionDAG &DAG) {
11500   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11501   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11502   SDValue Chain = Op.getOperand(0);
11503   SDValue DstPtr = Op.getOperand(1);
11504   SDValue SrcPtr = Op.getOperand(2);
11505   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11506   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11507   SDLoc DL(Op);
11508
11509   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11510                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11511                        false,
11512                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11513 }
11514
11515 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11516 // amount is a constant. Takes immediate version of shift as input.
11517 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11518                                           SDValue SrcOp, uint64_t ShiftAmt,
11519                                           SelectionDAG &DAG) {
11520   MVT ElementType = VT.getVectorElementType();
11521
11522   // Check for ShiftAmt >= element width
11523   if (ShiftAmt >= ElementType.getSizeInBits()) {
11524     if (Opc == X86ISD::VSRAI)
11525       ShiftAmt = ElementType.getSizeInBits() - 1;
11526     else
11527       return DAG.getConstant(0, VT);
11528   }
11529
11530   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11531          && "Unknown target vector shift-by-constant node");
11532
11533   // Fold this packed vector shift into a build vector if SrcOp is a
11534   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11535   if (VT == SrcOp.getSimpleValueType() &&
11536       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11537     SmallVector<SDValue, 8> Elts;
11538     unsigned NumElts = SrcOp->getNumOperands();
11539     ConstantSDNode *ND;
11540
11541     switch(Opc) {
11542     default: llvm_unreachable(0);
11543     case X86ISD::VSHLI:
11544       for (unsigned i=0; i!=NumElts; ++i) {
11545         SDValue CurrentOp = SrcOp->getOperand(i);
11546         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11547           Elts.push_back(CurrentOp);
11548           continue;
11549         }
11550         ND = cast<ConstantSDNode>(CurrentOp);
11551         const APInt &C = ND->getAPIntValue();
11552         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11553       }
11554       break;
11555     case X86ISD::VSRLI:
11556       for (unsigned i=0; i!=NumElts; ++i) {
11557         SDValue CurrentOp = SrcOp->getOperand(i);
11558         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11559           Elts.push_back(CurrentOp);
11560           continue;
11561         }
11562         ND = cast<ConstantSDNode>(CurrentOp);
11563         const APInt &C = ND->getAPIntValue();
11564         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11565       }
11566       break;
11567     case X86ISD::VSRAI:
11568       for (unsigned i=0; i!=NumElts; ++i) {
11569         SDValue CurrentOp = SrcOp->getOperand(i);
11570         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11571           Elts.push_back(CurrentOp);
11572           continue;
11573         }
11574         ND = cast<ConstantSDNode>(CurrentOp);
11575         const APInt &C = ND->getAPIntValue();
11576         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11577       }
11578       break;
11579     }
11580
11581     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11582   }
11583
11584   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11585 }
11586
11587 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11588 // may or may not be a constant. Takes immediate version of shift as input.
11589 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11590                                    SDValue SrcOp, SDValue ShAmt,
11591                                    SelectionDAG &DAG) {
11592   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11593
11594   // Catch shift-by-constant.
11595   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11596     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11597                                       CShAmt->getZExtValue(), DAG);
11598
11599   // Change opcode to non-immediate version
11600   switch (Opc) {
11601     default: llvm_unreachable("Unknown target vector shift node");
11602     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11603     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11604     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11605   }
11606
11607   // Need to build a vector containing shift amount
11608   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11609   SDValue ShOps[4];
11610   ShOps[0] = ShAmt;
11611   ShOps[1] = DAG.getConstant(0, MVT::i32);
11612   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11613   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11614
11615   // The return type has to be a 128-bit type with the same element
11616   // type as the input type.
11617   MVT EltVT = VT.getVectorElementType();
11618   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11619
11620   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11621   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11622 }
11623
11624 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11625   SDLoc dl(Op);
11626   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11627   switch (IntNo) {
11628   default: return SDValue();    // Don't custom lower most intrinsics.
11629   // Comparison intrinsics.
11630   case Intrinsic::x86_sse_comieq_ss:
11631   case Intrinsic::x86_sse_comilt_ss:
11632   case Intrinsic::x86_sse_comile_ss:
11633   case Intrinsic::x86_sse_comigt_ss:
11634   case Intrinsic::x86_sse_comige_ss:
11635   case Intrinsic::x86_sse_comineq_ss:
11636   case Intrinsic::x86_sse_ucomieq_ss:
11637   case Intrinsic::x86_sse_ucomilt_ss:
11638   case Intrinsic::x86_sse_ucomile_ss:
11639   case Intrinsic::x86_sse_ucomigt_ss:
11640   case Intrinsic::x86_sse_ucomige_ss:
11641   case Intrinsic::x86_sse_ucomineq_ss:
11642   case Intrinsic::x86_sse2_comieq_sd:
11643   case Intrinsic::x86_sse2_comilt_sd:
11644   case Intrinsic::x86_sse2_comile_sd:
11645   case Intrinsic::x86_sse2_comigt_sd:
11646   case Intrinsic::x86_sse2_comige_sd:
11647   case Intrinsic::x86_sse2_comineq_sd:
11648   case Intrinsic::x86_sse2_ucomieq_sd:
11649   case Intrinsic::x86_sse2_ucomilt_sd:
11650   case Intrinsic::x86_sse2_ucomile_sd:
11651   case Intrinsic::x86_sse2_ucomigt_sd:
11652   case Intrinsic::x86_sse2_ucomige_sd:
11653   case Intrinsic::x86_sse2_ucomineq_sd: {
11654     unsigned Opc;
11655     ISD::CondCode CC;
11656     switch (IntNo) {
11657     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11658     case Intrinsic::x86_sse_comieq_ss:
11659     case Intrinsic::x86_sse2_comieq_sd:
11660       Opc = X86ISD::COMI;
11661       CC = ISD::SETEQ;
11662       break;
11663     case Intrinsic::x86_sse_comilt_ss:
11664     case Intrinsic::x86_sse2_comilt_sd:
11665       Opc = X86ISD::COMI;
11666       CC = ISD::SETLT;
11667       break;
11668     case Intrinsic::x86_sse_comile_ss:
11669     case Intrinsic::x86_sse2_comile_sd:
11670       Opc = X86ISD::COMI;
11671       CC = ISD::SETLE;
11672       break;
11673     case Intrinsic::x86_sse_comigt_ss:
11674     case Intrinsic::x86_sse2_comigt_sd:
11675       Opc = X86ISD::COMI;
11676       CC = ISD::SETGT;
11677       break;
11678     case Intrinsic::x86_sse_comige_ss:
11679     case Intrinsic::x86_sse2_comige_sd:
11680       Opc = X86ISD::COMI;
11681       CC = ISD::SETGE;
11682       break;
11683     case Intrinsic::x86_sse_comineq_ss:
11684     case Intrinsic::x86_sse2_comineq_sd:
11685       Opc = X86ISD::COMI;
11686       CC = ISD::SETNE;
11687       break;
11688     case Intrinsic::x86_sse_ucomieq_ss:
11689     case Intrinsic::x86_sse2_ucomieq_sd:
11690       Opc = X86ISD::UCOMI;
11691       CC = ISD::SETEQ;
11692       break;
11693     case Intrinsic::x86_sse_ucomilt_ss:
11694     case Intrinsic::x86_sse2_ucomilt_sd:
11695       Opc = X86ISD::UCOMI;
11696       CC = ISD::SETLT;
11697       break;
11698     case Intrinsic::x86_sse_ucomile_ss:
11699     case Intrinsic::x86_sse2_ucomile_sd:
11700       Opc = X86ISD::UCOMI;
11701       CC = ISD::SETLE;
11702       break;
11703     case Intrinsic::x86_sse_ucomigt_ss:
11704     case Intrinsic::x86_sse2_ucomigt_sd:
11705       Opc = X86ISD::UCOMI;
11706       CC = ISD::SETGT;
11707       break;
11708     case Intrinsic::x86_sse_ucomige_ss:
11709     case Intrinsic::x86_sse2_ucomige_sd:
11710       Opc = X86ISD::UCOMI;
11711       CC = ISD::SETGE;
11712       break;
11713     case Intrinsic::x86_sse_ucomineq_ss:
11714     case Intrinsic::x86_sse2_ucomineq_sd:
11715       Opc = X86ISD::UCOMI;
11716       CC = ISD::SETNE;
11717       break;
11718     }
11719
11720     SDValue LHS = Op.getOperand(1);
11721     SDValue RHS = Op.getOperand(2);
11722     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11723     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11724     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11725     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11726                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11727     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11728   }
11729
11730   // Arithmetic intrinsics.
11731   case Intrinsic::x86_sse2_pmulu_dq:
11732   case Intrinsic::x86_avx2_pmulu_dq:
11733     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11734                        Op.getOperand(1), Op.getOperand(2));
11735
11736   // SSE2/AVX2 sub with unsigned saturation intrinsics
11737   case Intrinsic::x86_sse2_psubus_b:
11738   case Intrinsic::x86_sse2_psubus_w:
11739   case Intrinsic::x86_avx2_psubus_b:
11740   case Intrinsic::x86_avx2_psubus_w:
11741     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11742                        Op.getOperand(1), Op.getOperand(2));
11743
11744   // SSE3/AVX horizontal add/sub intrinsics
11745   case Intrinsic::x86_sse3_hadd_ps:
11746   case Intrinsic::x86_sse3_hadd_pd:
11747   case Intrinsic::x86_avx_hadd_ps_256:
11748   case Intrinsic::x86_avx_hadd_pd_256:
11749   case Intrinsic::x86_sse3_hsub_ps:
11750   case Intrinsic::x86_sse3_hsub_pd:
11751   case Intrinsic::x86_avx_hsub_ps_256:
11752   case Intrinsic::x86_avx_hsub_pd_256:
11753   case Intrinsic::x86_ssse3_phadd_w_128:
11754   case Intrinsic::x86_ssse3_phadd_d_128:
11755   case Intrinsic::x86_avx2_phadd_w:
11756   case Intrinsic::x86_avx2_phadd_d:
11757   case Intrinsic::x86_ssse3_phsub_w_128:
11758   case Intrinsic::x86_ssse3_phsub_d_128:
11759   case Intrinsic::x86_avx2_phsub_w:
11760   case Intrinsic::x86_avx2_phsub_d: {
11761     unsigned Opcode;
11762     switch (IntNo) {
11763     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11764     case Intrinsic::x86_sse3_hadd_ps:
11765     case Intrinsic::x86_sse3_hadd_pd:
11766     case Intrinsic::x86_avx_hadd_ps_256:
11767     case Intrinsic::x86_avx_hadd_pd_256:
11768       Opcode = X86ISD::FHADD;
11769       break;
11770     case Intrinsic::x86_sse3_hsub_ps:
11771     case Intrinsic::x86_sse3_hsub_pd:
11772     case Intrinsic::x86_avx_hsub_ps_256:
11773     case Intrinsic::x86_avx_hsub_pd_256:
11774       Opcode = X86ISD::FHSUB;
11775       break;
11776     case Intrinsic::x86_ssse3_phadd_w_128:
11777     case Intrinsic::x86_ssse3_phadd_d_128:
11778     case Intrinsic::x86_avx2_phadd_w:
11779     case Intrinsic::x86_avx2_phadd_d:
11780       Opcode = X86ISD::HADD;
11781       break;
11782     case Intrinsic::x86_ssse3_phsub_w_128:
11783     case Intrinsic::x86_ssse3_phsub_d_128:
11784     case Intrinsic::x86_avx2_phsub_w:
11785     case Intrinsic::x86_avx2_phsub_d:
11786       Opcode = X86ISD::HSUB;
11787       break;
11788     }
11789     return DAG.getNode(Opcode, dl, Op.getValueType(),
11790                        Op.getOperand(1), Op.getOperand(2));
11791   }
11792
11793   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11794   case Intrinsic::x86_sse2_pmaxu_b:
11795   case Intrinsic::x86_sse41_pmaxuw:
11796   case Intrinsic::x86_sse41_pmaxud:
11797   case Intrinsic::x86_avx2_pmaxu_b:
11798   case Intrinsic::x86_avx2_pmaxu_w:
11799   case Intrinsic::x86_avx2_pmaxu_d:
11800   case Intrinsic::x86_sse2_pminu_b:
11801   case Intrinsic::x86_sse41_pminuw:
11802   case Intrinsic::x86_sse41_pminud:
11803   case Intrinsic::x86_avx2_pminu_b:
11804   case Intrinsic::x86_avx2_pminu_w:
11805   case Intrinsic::x86_avx2_pminu_d:
11806   case Intrinsic::x86_sse41_pmaxsb:
11807   case Intrinsic::x86_sse2_pmaxs_w:
11808   case Intrinsic::x86_sse41_pmaxsd:
11809   case Intrinsic::x86_avx2_pmaxs_b:
11810   case Intrinsic::x86_avx2_pmaxs_w:
11811   case Intrinsic::x86_avx2_pmaxs_d:
11812   case Intrinsic::x86_sse41_pminsb:
11813   case Intrinsic::x86_sse2_pmins_w:
11814   case Intrinsic::x86_sse41_pminsd:
11815   case Intrinsic::x86_avx2_pmins_b:
11816   case Intrinsic::x86_avx2_pmins_w:
11817   case Intrinsic::x86_avx2_pmins_d: {
11818     unsigned Opcode;
11819     switch (IntNo) {
11820     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11821     case Intrinsic::x86_sse2_pmaxu_b:
11822     case Intrinsic::x86_sse41_pmaxuw:
11823     case Intrinsic::x86_sse41_pmaxud:
11824     case Intrinsic::x86_avx2_pmaxu_b:
11825     case Intrinsic::x86_avx2_pmaxu_w:
11826     case Intrinsic::x86_avx2_pmaxu_d:
11827       Opcode = X86ISD::UMAX;
11828       break;
11829     case Intrinsic::x86_sse2_pminu_b:
11830     case Intrinsic::x86_sse41_pminuw:
11831     case Intrinsic::x86_sse41_pminud:
11832     case Intrinsic::x86_avx2_pminu_b:
11833     case Intrinsic::x86_avx2_pminu_w:
11834     case Intrinsic::x86_avx2_pminu_d:
11835       Opcode = X86ISD::UMIN;
11836       break;
11837     case Intrinsic::x86_sse41_pmaxsb:
11838     case Intrinsic::x86_sse2_pmaxs_w:
11839     case Intrinsic::x86_sse41_pmaxsd:
11840     case Intrinsic::x86_avx2_pmaxs_b:
11841     case Intrinsic::x86_avx2_pmaxs_w:
11842     case Intrinsic::x86_avx2_pmaxs_d:
11843       Opcode = X86ISD::SMAX;
11844       break;
11845     case Intrinsic::x86_sse41_pminsb:
11846     case Intrinsic::x86_sse2_pmins_w:
11847     case Intrinsic::x86_sse41_pminsd:
11848     case Intrinsic::x86_avx2_pmins_b:
11849     case Intrinsic::x86_avx2_pmins_w:
11850     case Intrinsic::x86_avx2_pmins_d:
11851       Opcode = X86ISD::SMIN;
11852       break;
11853     }
11854     return DAG.getNode(Opcode, dl, Op.getValueType(),
11855                        Op.getOperand(1), Op.getOperand(2));
11856   }
11857
11858   // SSE/SSE2/AVX floating point max/min intrinsics.
11859   case Intrinsic::x86_sse_max_ps:
11860   case Intrinsic::x86_sse2_max_pd:
11861   case Intrinsic::x86_avx_max_ps_256:
11862   case Intrinsic::x86_avx_max_pd_256:
11863   case Intrinsic::x86_sse_min_ps:
11864   case Intrinsic::x86_sse2_min_pd:
11865   case Intrinsic::x86_avx_min_ps_256:
11866   case Intrinsic::x86_avx_min_pd_256: {
11867     unsigned Opcode;
11868     switch (IntNo) {
11869     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11870     case Intrinsic::x86_sse_max_ps:
11871     case Intrinsic::x86_sse2_max_pd:
11872     case Intrinsic::x86_avx_max_ps_256:
11873     case Intrinsic::x86_avx_max_pd_256:
11874       Opcode = X86ISD::FMAX;
11875       break;
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       Opcode = X86ISD::FMIN;
11881       break;
11882     }
11883     return DAG.getNode(Opcode, dl, Op.getValueType(),
11884                        Op.getOperand(1), Op.getOperand(2));
11885   }
11886
11887   // AVX2 variable shift intrinsics
11888   case Intrinsic::x86_avx2_psllv_d:
11889   case Intrinsic::x86_avx2_psllv_q:
11890   case Intrinsic::x86_avx2_psllv_d_256:
11891   case Intrinsic::x86_avx2_psllv_q_256:
11892   case Intrinsic::x86_avx2_psrlv_d:
11893   case Intrinsic::x86_avx2_psrlv_q:
11894   case Intrinsic::x86_avx2_psrlv_d_256:
11895   case Intrinsic::x86_avx2_psrlv_q_256:
11896   case Intrinsic::x86_avx2_psrav_d:
11897   case Intrinsic::x86_avx2_psrav_d_256: {
11898     unsigned Opcode;
11899     switch (IntNo) {
11900     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
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       Opcode = ISD::SHL;
11906       break;
11907     case Intrinsic::x86_avx2_psrlv_d:
11908     case Intrinsic::x86_avx2_psrlv_q:
11909     case Intrinsic::x86_avx2_psrlv_d_256:
11910     case Intrinsic::x86_avx2_psrlv_q_256:
11911       Opcode = ISD::SRL;
11912       break;
11913     case Intrinsic::x86_avx2_psrav_d:
11914     case Intrinsic::x86_avx2_psrav_d_256:
11915       Opcode = ISD::SRA;
11916       break;
11917     }
11918     return DAG.getNode(Opcode, dl, Op.getValueType(),
11919                        Op.getOperand(1), Op.getOperand(2));
11920   }
11921
11922   case Intrinsic::x86_ssse3_pshuf_b_128:
11923   case Intrinsic::x86_avx2_pshuf_b:
11924     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11925                        Op.getOperand(1), Op.getOperand(2));
11926
11927   case Intrinsic::x86_ssse3_psign_b_128:
11928   case Intrinsic::x86_ssse3_psign_w_128:
11929   case Intrinsic::x86_ssse3_psign_d_128:
11930   case Intrinsic::x86_avx2_psign_b:
11931   case Intrinsic::x86_avx2_psign_w:
11932   case Intrinsic::x86_avx2_psign_d:
11933     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11934                        Op.getOperand(1), Op.getOperand(2));
11935
11936   case Intrinsic::x86_sse41_insertps:
11937     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11938                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11939
11940   case Intrinsic::x86_avx_vperm2f128_ps_256:
11941   case Intrinsic::x86_avx_vperm2f128_pd_256:
11942   case Intrinsic::x86_avx_vperm2f128_si_256:
11943   case Intrinsic::x86_avx2_vperm2i128:
11944     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11945                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11946
11947   case Intrinsic::x86_avx2_permd:
11948   case Intrinsic::x86_avx2_permps:
11949     // Operands intentionally swapped. Mask is last operand to intrinsic,
11950     // but second operand for node/instruction.
11951     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11952                        Op.getOperand(2), Op.getOperand(1));
11953
11954   case Intrinsic::x86_sse_sqrt_ps:
11955   case Intrinsic::x86_sse2_sqrt_pd:
11956   case Intrinsic::x86_avx_sqrt_ps_256:
11957   case Intrinsic::x86_avx_sqrt_pd_256:
11958     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11959
11960   // ptest and testp intrinsics. The intrinsic these come from are designed to
11961   // return an integer value, not just an instruction so lower it to the ptest
11962   // or testp pattern and a setcc for the result.
11963   case Intrinsic::x86_sse41_ptestz:
11964   case Intrinsic::x86_sse41_ptestc:
11965   case Intrinsic::x86_sse41_ptestnzc:
11966   case Intrinsic::x86_avx_ptestz_256:
11967   case Intrinsic::x86_avx_ptestc_256:
11968   case Intrinsic::x86_avx_ptestnzc_256:
11969   case Intrinsic::x86_avx_vtestz_ps:
11970   case Intrinsic::x86_avx_vtestc_ps:
11971   case Intrinsic::x86_avx_vtestnzc_ps:
11972   case Intrinsic::x86_avx_vtestz_pd:
11973   case Intrinsic::x86_avx_vtestc_pd:
11974   case Intrinsic::x86_avx_vtestnzc_pd:
11975   case Intrinsic::x86_avx_vtestz_ps_256:
11976   case Intrinsic::x86_avx_vtestc_ps_256:
11977   case Intrinsic::x86_avx_vtestnzc_ps_256:
11978   case Intrinsic::x86_avx_vtestz_pd_256:
11979   case Intrinsic::x86_avx_vtestc_pd_256:
11980   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11981     bool IsTestPacked = false;
11982     unsigned X86CC;
11983     switch (IntNo) {
11984     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11985     case Intrinsic::x86_avx_vtestz_ps:
11986     case Intrinsic::x86_avx_vtestz_pd:
11987     case Intrinsic::x86_avx_vtestz_ps_256:
11988     case Intrinsic::x86_avx_vtestz_pd_256:
11989       IsTestPacked = true; // Fallthrough
11990     case Intrinsic::x86_sse41_ptestz:
11991     case Intrinsic::x86_avx_ptestz_256:
11992       // ZF = 1
11993       X86CC = X86::COND_E;
11994       break;
11995     case Intrinsic::x86_avx_vtestc_ps:
11996     case Intrinsic::x86_avx_vtestc_pd:
11997     case Intrinsic::x86_avx_vtestc_ps_256:
11998     case Intrinsic::x86_avx_vtestc_pd_256:
11999       IsTestPacked = true; // Fallthrough
12000     case Intrinsic::x86_sse41_ptestc:
12001     case Intrinsic::x86_avx_ptestc_256:
12002       // CF = 1
12003       X86CC = X86::COND_B;
12004       break;
12005     case Intrinsic::x86_avx_vtestnzc_ps:
12006     case Intrinsic::x86_avx_vtestnzc_pd:
12007     case Intrinsic::x86_avx_vtestnzc_ps_256:
12008     case Intrinsic::x86_avx_vtestnzc_pd_256:
12009       IsTestPacked = true; // Fallthrough
12010     case Intrinsic::x86_sse41_ptestnzc:
12011     case Intrinsic::x86_avx_ptestnzc_256:
12012       // ZF and CF = 0
12013       X86CC = X86::COND_A;
12014       break;
12015     }
12016
12017     SDValue LHS = Op.getOperand(1);
12018     SDValue RHS = Op.getOperand(2);
12019     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12020     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12021     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12022     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12023     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12024   }
12025   case Intrinsic::x86_avx512_kortestz_w:
12026   case Intrinsic::x86_avx512_kortestc_w: {
12027     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12028     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12029     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12030     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12031     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12032     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12033     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12034   }
12035
12036   // SSE/AVX shift intrinsics
12037   case Intrinsic::x86_sse2_psll_w:
12038   case Intrinsic::x86_sse2_psll_d:
12039   case Intrinsic::x86_sse2_psll_q:
12040   case Intrinsic::x86_avx2_psll_w:
12041   case Intrinsic::x86_avx2_psll_d:
12042   case Intrinsic::x86_avx2_psll_q:
12043   case Intrinsic::x86_sse2_psrl_w:
12044   case Intrinsic::x86_sse2_psrl_d:
12045   case Intrinsic::x86_sse2_psrl_q:
12046   case Intrinsic::x86_avx2_psrl_w:
12047   case Intrinsic::x86_avx2_psrl_d:
12048   case Intrinsic::x86_avx2_psrl_q:
12049   case Intrinsic::x86_sse2_psra_w:
12050   case Intrinsic::x86_sse2_psra_d:
12051   case Intrinsic::x86_avx2_psra_w:
12052   case Intrinsic::x86_avx2_psra_d: {
12053     unsigned Opcode;
12054     switch (IntNo) {
12055     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12056     case Intrinsic::x86_sse2_psll_w:
12057     case Intrinsic::x86_sse2_psll_d:
12058     case Intrinsic::x86_sse2_psll_q:
12059     case Intrinsic::x86_avx2_psll_w:
12060     case Intrinsic::x86_avx2_psll_d:
12061     case Intrinsic::x86_avx2_psll_q:
12062       Opcode = X86ISD::VSHL;
12063       break;
12064     case Intrinsic::x86_sse2_psrl_w:
12065     case Intrinsic::x86_sse2_psrl_d:
12066     case Intrinsic::x86_sse2_psrl_q:
12067     case Intrinsic::x86_avx2_psrl_w:
12068     case Intrinsic::x86_avx2_psrl_d:
12069     case Intrinsic::x86_avx2_psrl_q:
12070       Opcode = X86ISD::VSRL;
12071       break;
12072     case Intrinsic::x86_sse2_psra_w:
12073     case Intrinsic::x86_sse2_psra_d:
12074     case Intrinsic::x86_avx2_psra_w:
12075     case Intrinsic::x86_avx2_psra_d:
12076       Opcode = X86ISD::VSRA;
12077       break;
12078     }
12079     return DAG.getNode(Opcode, dl, Op.getValueType(),
12080                        Op.getOperand(1), Op.getOperand(2));
12081   }
12082
12083   // SSE/AVX immediate shift intrinsics
12084   case Intrinsic::x86_sse2_pslli_w:
12085   case Intrinsic::x86_sse2_pslli_d:
12086   case Intrinsic::x86_sse2_pslli_q:
12087   case Intrinsic::x86_avx2_pslli_w:
12088   case Intrinsic::x86_avx2_pslli_d:
12089   case Intrinsic::x86_avx2_pslli_q:
12090   case Intrinsic::x86_sse2_psrli_w:
12091   case Intrinsic::x86_sse2_psrli_d:
12092   case Intrinsic::x86_sse2_psrli_q:
12093   case Intrinsic::x86_avx2_psrli_w:
12094   case Intrinsic::x86_avx2_psrli_d:
12095   case Intrinsic::x86_avx2_psrli_q:
12096   case Intrinsic::x86_sse2_psrai_w:
12097   case Intrinsic::x86_sse2_psrai_d:
12098   case Intrinsic::x86_avx2_psrai_w:
12099   case Intrinsic::x86_avx2_psrai_d: {
12100     unsigned Opcode;
12101     switch (IntNo) {
12102     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12103     case Intrinsic::x86_sse2_pslli_w:
12104     case Intrinsic::x86_sse2_pslli_d:
12105     case Intrinsic::x86_sse2_pslli_q:
12106     case Intrinsic::x86_avx2_pslli_w:
12107     case Intrinsic::x86_avx2_pslli_d:
12108     case Intrinsic::x86_avx2_pslli_q:
12109       Opcode = X86ISD::VSHLI;
12110       break;
12111     case Intrinsic::x86_sse2_psrli_w:
12112     case Intrinsic::x86_sse2_psrli_d:
12113     case Intrinsic::x86_sse2_psrli_q:
12114     case Intrinsic::x86_avx2_psrli_w:
12115     case Intrinsic::x86_avx2_psrli_d:
12116     case Intrinsic::x86_avx2_psrli_q:
12117       Opcode = X86ISD::VSRLI;
12118       break;
12119     case Intrinsic::x86_sse2_psrai_w:
12120     case Intrinsic::x86_sse2_psrai_d:
12121     case Intrinsic::x86_avx2_psrai_w:
12122     case Intrinsic::x86_avx2_psrai_d:
12123       Opcode = X86ISD::VSRAI;
12124       break;
12125     }
12126     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12127                                Op.getOperand(1), Op.getOperand(2), DAG);
12128   }
12129
12130   case Intrinsic::x86_sse42_pcmpistria128:
12131   case Intrinsic::x86_sse42_pcmpestria128:
12132   case Intrinsic::x86_sse42_pcmpistric128:
12133   case Intrinsic::x86_sse42_pcmpestric128:
12134   case Intrinsic::x86_sse42_pcmpistrio128:
12135   case Intrinsic::x86_sse42_pcmpestrio128:
12136   case Intrinsic::x86_sse42_pcmpistris128:
12137   case Intrinsic::x86_sse42_pcmpestris128:
12138   case Intrinsic::x86_sse42_pcmpistriz128:
12139   case Intrinsic::x86_sse42_pcmpestriz128: {
12140     unsigned Opcode;
12141     unsigned X86CC;
12142     switch (IntNo) {
12143     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12144     case Intrinsic::x86_sse42_pcmpistria128:
12145       Opcode = X86ISD::PCMPISTRI;
12146       X86CC = X86::COND_A;
12147       break;
12148     case Intrinsic::x86_sse42_pcmpestria128:
12149       Opcode = X86ISD::PCMPESTRI;
12150       X86CC = X86::COND_A;
12151       break;
12152     case Intrinsic::x86_sse42_pcmpistric128:
12153       Opcode = X86ISD::PCMPISTRI;
12154       X86CC = X86::COND_B;
12155       break;
12156     case Intrinsic::x86_sse42_pcmpestric128:
12157       Opcode = X86ISD::PCMPESTRI;
12158       X86CC = X86::COND_B;
12159       break;
12160     case Intrinsic::x86_sse42_pcmpistrio128:
12161       Opcode = X86ISD::PCMPISTRI;
12162       X86CC = X86::COND_O;
12163       break;
12164     case Intrinsic::x86_sse42_pcmpestrio128:
12165       Opcode = X86ISD::PCMPESTRI;
12166       X86CC = X86::COND_O;
12167       break;
12168     case Intrinsic::x86_sse42_pcmpistris128:
12169       Opcode = X86ISD::PCMPISTRI;
12170       X86CC = X86::COND_S;
12171       break;
12172     case Intrinsic::x86_sse42_pcmpestris128:
12173       Opcode = X86ISD::PCMPESTRI;
12174       X86CC = X86::COND_S;
12175       break;
12176     case Intrinsic::x86_sse42_pcmpistriz128:
12177       Opcode = X86ISD::PCMPISTRI;
12178       X86CC = X86::COND_E;
12179       break;
12180     case Intrinsic::x86_sse42_pcmpestriz128:
12181       Opcode = X86ISD::PCMPESTRI;
12182       X86CC = X86::COND_E;
12183       break;
12184     }
12185     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12186     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12187     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12188     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12189                                 DAG.getConstant(X86CC, MVT::i8),
12190                                 SDValue(PCMP.getNode(), 1));
12191     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12192   }
12193
12194   case Intrinsic::x86_sse42_pcmpistri128:
12195   case Intrinsic::x86_sse42_pcmpestri128: {
12196     unsigned Opcode;
12197     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12198       Opcode = X86ISD::PCMPISTRI;
12199     else
12200       Opcode = X86ISD::PCMPESTRI;
12201
12202     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12203     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12204     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12205   }
12206   case Intrinsic::x86_fma_vfmadd_ps:
12207   case Intrinsic::x86_fma_vfmadd_pd:
12208   case Intrinsic::x86_fma_vfmsub_ps:
12209   case Intrinsic::x86_fma_vfmsub_pd:
12210   case Intrinsic::x86_fma_vfnmadd_ps:
12211   case Intrinsic::x86_fma_vfnmadd_pd:
12212   case Intrinsic::x86_fma_vfnmsub_ps:
12213   case Intrinsic::x86_fma_vfnmsub_pd:
12214   case Intrinsic::x86_fma_vfmaddsub_ps:
12215   case Intrinsic::x86_fma_vfmaddsub_pd:
12216   case Intrinsic::x86_fma_vfmsubadd_ps:
12217   case Intrinsic::x86_fma_vfmsubadd_pd:
12218   case Intrinsic::x86_fma_vfmadd_ps_256:
12219   case Intrinsic::x86_fma_vfmadd_pd_256:
12220   case Intrinsic::x86_fma_vfmsub_ps_256:
12221   case Intrinsic::x86_fma_vfmsub_pd_256:
12222   case Intrinsic::x86_fma_vfnmadd_ps_256:
12223   case Intrinsic::x86_fma_vfnmadd_pd_256:
12224   case Intrinsic::x86_fma_vfnmsub_ps_256:
12225   case Intrinsic::x86_fma_vfnmsub_pd_256:
12226   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12227   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12228   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12229   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12230   case Intrinsic::x86_fma_vfmadd_ps_512:
12231   case Intrinsic::x86_fma_vfmadd_pd_512:
12232   case Intrinsic::x86_fma_vfmsub_ps_512:
12233   case Intrinsic::x86_fma_vfmsub_pd_512:
12234   case Intrinsic::x86_fma_vfnmadd_ps_512:
12235   case Intrinsic::x86_fma_vfnmadd_pd_512:
12236   case Intrinsic::x86_fma_vfnmsub_ps_512:
12237   case Intrinsic::x86_fma_vfnmsub_pd_512:
12238   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12239   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12240   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12241   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12242     unsigned Opc;
12243     switch (IntNo) {
12244     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12245     case Intrinsic::x86_fma_vfmadd_ps:
12246     case Intrinsic::x86_fma_vfmadd_pd:
12247     case Intrinsic::x86_fma_vfmadd_ps_256:
12248     case Intrinsic::x86_fma_vfmadd_pd_256:
12249     case Intrinsic::x86_fma_vfmadd_ps_512:
12250     case Intrinsic::x86_fma_vfmadd_pd_512:
12251       Opc = X86ISD::FMADD;
12252       break;
12253     case Intrinsic::x86_fma_vfmsub_ps:
12254     case Intrinsic::x86_fma_vfmsub_pd:
12255     case Intrinsic::x86_fma_vfmsub_ps_256:
12256     case Intrinsic::x86_fma_vfmsub_pd_256:
12257     case Intrinsic::x86_fma_vfmsub_ps_512:
12258     case Intrinsic::x86_fma_vfmsub_pd_512:
12259       Opc = X86ISD::FMSUB;
12260       break;
12261     case Intrinsic::x86_fma_vfnmadd_ps:
12262     case Intrinsic::x86_fma_vfnmadd_pd:
12263     case Intrinsic::x86_fma_vfnmadd_ps_256:
12264     case Intrinsic::x86_fma_vfnmadd_pd_256:
12265     case Intrinsic::x86_fma_vfnmadd_ps_512:
12266     case Intrinsic::x86_fma_vfnmadd_pd_512:
12267       Opc = X86ISD::FNMADD;
12268       break;
12269     case Intrinsic::x86_fma_vfnmsub_ps:
12270     case Intrinsic::x86_fma_vfnmsub_pd:
12271     case Intrinsic::x86_fma_vfnmsub_ps_256:
12272     case Intrinsic::x86_fma_vfnmsub_pd_256:
12273     case Intrinsic::x86_fma_vfnmsub_ps_512:
12274     case Intrinsic::x86_fma_vfnmsub_pd_512:
12275       Opc = X86ISD::FNMSUB;
12276       break;
12277     case Intrinsic::x86_fma_vfmaddsub_ps:
12278     case Intrinsic::x86_fma_vfmaddsub_pd:
12279     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12280     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12281     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12282     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12283       Opc = X86ISD::FMADDSUB;
12284       break;
12285     case Intrinsic::x86_fma_vfmsubadd_ps:
12286     case Intrinsic::x86_fma_vfmsubadd_pd:
12287     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12288     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12289     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12290     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12291       Opc = X86ISD::FMSUBADD;
12292       break;
12293     }
12294
12295     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12296                        Op.getOperand(2), Op.getOperand(3));
12297   }
12298   }
12299 }
12300
12301 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12302                              SDValue Base, SDValue Index,
12303                              SDValue ScaleOp, SDValue Chain,
12304                              const X86Subtarget * Subtarget) {
12305   SDLoc dl(Op);
12306   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12307   assert(C && "Invalid scale type");
12308   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12309   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12310   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12311                              Index.getSimpleValueType().getVectorNumElements());
12312   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12313   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12314   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12315   SDValue Segment = DAG.getRegister(0, MVT::i32);
12316   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12317   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12318   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12319   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12320 }
12321
12322 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12323                               SDValue Src, SDValue Mask, SDValue Base,
12324                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12325                               const X86Subtarget * Subtarget) {
12326   SDLoc dl(Op);
12327   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12328   assert(C && "Invalid scale type");
12329   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12330   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12331                              Index.getSimpleValueType().getVectorNumElements());
12332   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12333   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12334   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12335   SDValue Segment = DAG.getRegister(0, MVT::i32);
12336   if (Src.getOpcode() == ISD::UNDEF)
12337     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12338   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12339   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12340   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12341   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12342 }
12343
12344 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12345                               SDValue Src, SDValue Base, SDValue Index,
12346                               SDValue ScaleOp, SDValue Chain) {
12347   SDLoc dl(Op);
12348   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12349   assert(C && "Invalid scale type");
12350   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12351   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12352   SDValue Segment = DAG.getRegister(0, MVT::i32);
12353   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12354                              Index.getSimpleValueType().getVectorNumElements());
12355   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12356   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12357   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12358   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12359   return SDValue(Res, 1);
12360 }
12361
12362 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12363                                SDValue Src, SDValue Mask, SDValue Base,
12364                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12365   SDLoc dl(Op);
12366   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12367   assert(C && "Invalid scale type");
12368   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12369   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12370   SDValue Segment = DAG.getRegister(0, MVT::i32);
12371   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12372                              Index.getSimpleValueType().getVectorNumElements());
12373   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12374   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12375   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12376   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12377   return SDValue(Res, 1);
12378 }
12379
12380 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12381 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12382 // also used to custom lower READCYCLECOUNTER nodes.
12383 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12384                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12385                               SmallVectorImpl<SDValue> &Results) {
12386   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12387   SDValue TheChain = N->getOperand(0);
12388   SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12389   SDValue LO, HI;
12390
12391   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12392   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12393   // and the EAX register is loaded with the low-order 32 bits.
12394   if (Subtarget->is64Bit()) {
12395     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12396     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12397                             LO.getValue(2));
12398   } else {
12399     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12400     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12401                             LO.getValue(2));
12402   }
12403   SDValue Chain = HI.getValue(1);
12404
12405   if (Opcode == X86ISD::RDTSCP_DAG) {
12406     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12407
12408     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12409     // the ECX register. Add 'ecx' explicitly to the chain.
12410     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12411                                      HI.getValue(2));
12412     // Explicitly store the content of ECX at the location passed in input
12413     // to the 'rdtscp' intrinsic.
12414     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12415                          MachinePointerInfo(), false, false, 0);
12416   }
12417
12418   if (Subtarget->is64Bit()) {
12419     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12420     // the EAX register is loaded with the low-order 32 bits.
12421     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12422                               DAG.getConstant(32, MVT::i8));
12423     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12424     Results.push_back(Chain);
12425     return;
12426   }
12427
12428   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12429   SDValue Ops[] = { LO, HI };
12430   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12431                              array_lengthof(Ops));
12432   Results.push_back(Pair);
12433   Results.push_back(Chain);
12434 }
12435
12436 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12437                                      SelectionDAG &DAG) {
12438   SmallVector<SDValue, 2> Results;
12439   SDLoc DL(Op);
12440   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12441                           Results);
12442   return DAG.getMergeValues(&Results[0], Results.size(), DL);
12443 }
12444
12445 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12446                                       SelectionDAG &DAG) {
12447   SDLoc dl(Op);
12448   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12449   switch (IntNo) {
12450   default: return SDValue();    // Don't custom lower most intrinsics.
12451
12452   // RDRAND/RDSEED intrinsics.
12453   case Intrinsic::x86_rdrand_16:
12454   case Intrinsic::x86_rdrand_32:
12455   case Intrinsic::x86_rdrand_64:
12456   case Intrinsic::x86_rdseed_16:
12457   case Intrinsic::x86_rdseed_32:
12458   case Intrinsic::x86_rdseed_64: {
12459     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12460                        IntNo == Intrinsic::x86_rdseed_32 ||
12461                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12462                                                             X86ISD::RDRAND;
12463     // Emit the node with the right value type.
12464     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12465     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12466
12467     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12468     // Otherwise return the value from Rand, which is always 0, casted to i32.
12469     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12470                       DAG.getConstant(1, Op->getValueType(1)),
12471                       DAG.getConstant(X86::COND_B, MVT::i32),
12472                       SDValue(Result.getNode(), 1) };
12473     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12474                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12475                                   Ops, array_lengthof(Ops));
12476
12477     // Return { result, isValid, chain }.
12478     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12479                        SDValue(Result.getNode(), 2));
12480   }
12481   //int_gather(index, base, scale);
12482   case Intrinsic::x86_avx512_gather_qpd_512:
12483   case Intrinsic::x86_avx512_gather_qps_512:
12484   case Intrinsic::x86_avx512_gather_dpd_512:
12485   case Intrinsic::x86_avx512_gather_qpi_512:
12486   case Intrinsic::x86_avx512_gather_qpq_512:
12487   case Intrinsic::x86_avx512_gather_dpq_512:
12488   case Intrinsic::x86_avx512_gather_dps_512:
12489   case Intrinsic::x86_avx512_gather_dpi_512: {
12490     unsigned Opc;
12491     switch (IntNo) {
12492     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12493     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12494     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12495     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12496     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12497     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12498     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12499     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12500     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12501     }
12502     SDValue Chain = Op.getOperand(0);
12503     SDValue Index = Op.getOperand(2);
12504     SDValue Base  = Op.getOperand(3);
12505     SDValue Scale = Op.getOperand(4);
12506     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12507   }
12508   //int_gather_mask(v1, mask, index, base, scale);
12509   case Intrinsic::x86_avx512_gather_qps_mask_512:
12510   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12511   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12512   case Intrinsic::x86_avx512_gather_dps_mask_512:
12513   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12514   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12515   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12516   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12517     unsigned Opc;
12518     switch (IntNo) {
12519     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12520     case Intrinsic::x86_avx512_gather_qps_mask_512:
12521       Opc = X86::VGATHERQPSZrm; break;
12522     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12523       Opc = X86::VGATHERQPDZrm; break;
12524     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12525       Opc = X86::VGATHERDPDZrm; break;
12526     case Intrinsic::x86_avx512_gather_dps_mask_512:
12527       Opc = X86::VGATHERDPSZrm; break;
12528     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12529       Opc = X86::VPGATHERQDZrm; break;
12530     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12531       Opc = X86::VPGATHERQQZrm; break;
12532     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12533       Opc = X86::VPGATHERDDZrm; break;
12534     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12535       Opc = X86::VPGATHERDQZrm; break;
12536     }
12537     SDValue Chain = Op.getOperand(0);
12538     SDValue Src   = Op.getOperand(2);
12539     SDValue Mask  = Op.getOperand(3);
12540     SDValue Index = Op.getOperand(4);
12541     SDValue Base  = Op.getOperand(5);
12542     SDValue Scale = Op.getOperand(6);
12543     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12544                           Subtarget);
12545   }
12546   //int_scatter(base, index, v1, scale);
12547   case Intrinsic::x86_avx512_scatter_qpd_512:
12548   case Intrinsic::x86_avx512_scatter_qps_512:
12549   case Intrinsic::x86_avx512_scatter_dpd_512:
12550   case Intrinsic::x86_avx512_scatter_qpi_512:
12551   case Intrinsic::x86_avx512_scatter_qpq_512:
12552   case Intrinsic::x86_avx512_scatter_dpq_512:
12553   case Intrinsic::x86_avx512_scatter_dps_512:
12554   case Intrinsic::x86_avx512_scatter_dpi_512: {
12555     unsigned Opc;
12556     switch (IntNo) {
12557     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12558     case Intrinsic::x86_avx512_scatter_qpd_512:
12559       Opc = X86::VSCATTERQPDZmr; break;
12560     case Intrinsic::x86_avx512_scatter_qps_512:
12561       Opc = X86::VSCATTERQPSZmr; break;
12562     case Intrinsic::x86_avx512_scatter_dpd_512:
12563       Opc = X86::VSCATTERDPDZmr; break;
12564     case Intrinsic::x86_avx512_scatter_dps_512:
12565       Opc = X86::VSCATTERDPSZmr; break;
12566     case Intrinsic::x86_avx512_scatter_qpi_512:
12567       Opc = X86::VPSCATTERQDZmr; break;
12568     case Intrinsic::x86_avx512_scatter_qpq_512:
12569       Opc = X86::VPSCATTERQQZmr; break;
12570     case Intrinsic::x86_avx512_scatter_dpq_512:
12571       Opc = X86::VPSCATTERDQZmr; break;
12572     case Intrinsic::x86_avx512_scatter_dpi_512:
12573       Opc = X86::VPSCATTERDDZmr; break;
12574     }
12575     SDValue Chain = Op.getOperand(0);
12576     SDValue Base  = Op.getOperand(2);
12577     SDValue Index = Op.getOperand(3);
12578     SDValue Src   = Op.getOperand(4);
12579     SDValue Scale = Op.getOperand(5);
12580     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12581   }
12582   //int_scatter_mask(base, mask, index, v1, scale);
12583   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12584   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12585   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12586   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12587   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12588   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12589   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12590   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12591     unsigned Opc;
12592     switch (IntNo) {
12593     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12594     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12595       Opc = X86::VSCATTERQPDZmr; break;
12596     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12597       Opc = X86::VSCATTERQPSZmr; break;
12598     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12599       Opc = X86::VSCATTERDPDZmr; break;
12600     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12601       Opc = X86::VSCATTERDPSZmr; break;
12602     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12603       Opc = X86::VPSCATTERQDZmr; break;
12604     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12605       Opc = X86::VPSCATTERQQZmr; break;
12606     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12607       Opc = X86::VPSCATTERDQZmr; break;
12608     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12609       Opc = X86::VPSCATTERDDZmr; break;
12610     }
12611     SDValue Chain = Op.getOperand(0);
12612     SDValue Base  = Op.getOperand(2);
12613     SDValue Mask  = Op.getOperand(3);
12614     SDValue Index = Op.getOperand(4);
12615     SDValue Src   = Op.getOperand(5);
12616     SDValue Scale = Op.getOperand(6);
12617     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12618   }
12619   // Read Time Stamp Counter (RDTSC).
12620   case Intrinsic::x86_rdtsc:
12621   // Read Time Stamp Counter and Processor ID (RDTSCP).
12622   case Intrinsic::x86_rdtscp: {
12623     unsigned Opc;
12624     switch (IntNo) {
12625     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12626     case Intrinsic::x86_rdtsc:
12627       Opc = X86ISD::RDTSC_DAG; break;
12628     case Intrinsic::x86_rdtscp:
12629       Opc = X86ISD::RDTSCP_DAG; break;
12630     }
12631     SmallVector<SDValue, 2> Results;
12632     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12633     return DAG.getMergeValues(&Results[0], Results.size(), dl);
12634   }
12635   // XTEST intrinsics.
12636   case Intrinsic::x86_xtest: {
12637     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12638     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12639     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12640                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12641                                 InTrans);
12642     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12643     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12644                        Ret, SDValue(InTrans.getNode(), 1));
12645   }
12646   }
12647 }
12648
12649 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12650                                            SelectionDAG &DAG) const {
12651   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12652   MFI->setReturnAddressIsTaken(true);
12653
12654   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12655     return SDValue();
12656
12657   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12658   SDLoc dl(Op);
12659   EVT PtrVT = getPointerTy();
12660
12661   if (Depth > 0) {
12662     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12663     const X86RegisterInfo *RegInfo =
12664       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12665     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12666     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12667                        DAG.getNode(ISD::ADD, dl, PtrVT,
12668                                    FrameAddr, Offset),
12669                        MachinePointerInfo(), false, false, false, 0);
12670   }
12671
12672   // Just load the return address.
12673   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12674   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12675                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12676 }
12677
12678 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12679   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12680   MFI->setFrameAddressIsTaken(true);
12681
12682   EVT VT = Op.getValueType();
12683   SDLoc dl(Op);  // FIXME probably not meaningful
12684   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12685   const X86RegisterInfo *RegInfo =
12686     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12687   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12688   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12689           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12690          "Invalid Frame Register!");
12691   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12692   while (Depth--)
12693     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12694                             MachinePointerInfo(),
12695                             false, false, false, 0);
12696   return FrameAddr;
12697 }
12698
12699 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12700                                                      SelectionDAG &DAG) const {
12701   const X86RegisterInfo *RegInfo =
12702     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12703   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12704 }
12705
12706 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12707   SDValue Chain     = Op.getOperand(0);
12708   SDValue Offset    = Op.getOperand(1);
12709   SDValue Handler   = Op.getOperand(2);
12710   SDLoc dl      (Op);
12711
12712   EVT PtrVT = getPointerTy();
12713   const X86RegisterInfo *RegInfo =
12714     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12715   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12716   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12717           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12718          "Invalid Frame Register!");
12719   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12720   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12721
12722   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12723                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12724   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12725   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12726                        false, false, 0);
12727   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12728
12729   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12730                      DAG.getRegister(StoreAddrReg, PtrVT));
12731 }
12732
12733 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12734                                                SelectionDAG &DAG) const {
12735   SDLoc DL(Op);
12736   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12737                      DAG.getVTList(MVT::i32, MVT::Other),
12738                      Op.getOperand(0), Op.getOperand(1));
12739 }
12740
12741 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12742                                                 SelectionDAG &DAG) const {
12743   SDLoc DL(Op);
12744   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12745                      Op.getOperand(0), Op.getOperand(1));
12746 }
12747
12748 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12749   return Op.getOperand(0);
12750 }
12751
12752 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12753                                                 SelectionDAG &DAG) const {
12754   SDValue Root = Op.getOperand(0);
12755   SDValue Trmp = Op.getOperand(1); // trampoline
12756   SDValue FPtr = Op.getOperand(2); // nested function
12757   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12758   SDLoc dl (Op);
12759
12760   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12761   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12762
12763   if (Subtarget->is64Bit()) {
12764     SDValue OutChains[6];
12765
12766     // Large code-model.
12767     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12768     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12769
12770     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12771     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12772
12773     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12774
12775     // Load the pointer to the nested function into R11.
12776     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12777     SDValue Addr = Trmp;
12778     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12779                                 Addr, MachinePointerInfo(TrmpAddr),
12780                                 false, false, 0);
12781
12782     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12783                        DAG.getConstant(2, MVT::i64));
12784     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12785                                 MachinePointerInfo(TrmpAddr, 2),
12786                                 false, false, 2);
12787
12788     // Load the 'nest' parameter value into R10.
12789     // R10 is specified in X86CallingConv.td
12790     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12791     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12792                        DAG.getConstant(10, MVT::i64));
12793     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12794                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12795                                 false, false, 0);
12796
12797     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12798                        DAG.getConstant(12, MVT::i64));
12799     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12800                                 MachinePointerInfo(TrmpAddr, 12),
12801                                 false, false, 2);
12802
12803     // Jump to the nested function.
12804     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12805     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12806                        DAG.getConstant(20, MVT::i64));
12807     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12808                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12809                                 false, false, 0);
12810
12811     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12812     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12813                        DAG.getConstant(22, MVT::i64));
12814     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12815                                 MachinePointerInfo(TrmpAddr, 22),
12816                                 false, false, 0);
12817
12818     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12819   } else {
12820     const Function *Func =
12821       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12822     CallingConv::ID CC = Func->getCallingConv();
12823     unsigned NestReg;
12824
12825     switch (CC) {
12826     default:
12827       llvm_unreachable("Unsupported calling convention");
12828     case CallingConv::C:
12829     case CallingConv::X86_StdCall: {
12830       // Pass 'nest' parameter in ECX.
12831       // Must be kept in sync with X86CallingConv.td
12832       NestReg = X86::ECX;
12833
12834       // Check that ECX wasn't needed by an 'inreg' parameter.
12835       FunctionType *FTy = Func->getFunctionType();
12836       const AttributeSet &Attrs = Func->getAttributes();
12837
12838       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12839         unsigned InRegCount = 0;
12840         unsigned Idx = 1;
12841
12842         for (FunctionType::param_iterator I = FTy->param_begin(),
12843              E = FTy->param_end(); I != E; ++I, ++Idx)
12844           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12845             // FIXME: should only count parameters that are lowered to integers.
12846             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12847
12848         if (InRegCount > 2) {
12849           report_fatal_error("Nest register in use - reduce number of inreg"
12850                              " parameters!");
12851         }
12852       }
12853       break;
12854     }
12855     case CallingConv::X86_FastCall:
12856     case CallingConv::X86_ThisCall:
12857     case CallingConv::Fast:
12858       // Pass 'nest' parameter in EAX.
12859       // Must be kept in sync with X86CallingConv.td
12860       NestReg = X86::EAX;
12861       break;
12862     }
12863
12864     SDValue OutChains[4];
12865     SDValue Addr, Disp;
12866
12867     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12868                        DAG.getConstant(10, MVT::i32));
12869     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12870
12871     // This is storing the opcode for MOV32ri.
12872     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12873     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12874     OutChains[0] = DAG.getStore(Root, dl,
12875                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12876                                 Trmp, MachinePointerInfo(TrmpAddr),
12877                                 false, false, 0);
12878
12879     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12880                        DAG.getConstant(1, MVT::i32));
12881     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12882                                 MachinePointerInfo(TrmpAddr, 1),
12883                                 false, false, 1);
12884
12885     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12886     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12887                        DAG.getConstant(5, MVT::i32));
12888     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12889                                 MachinePointerInfo(TrmpAddr, 5),
12890                                 false, false, 1);
12891
12892     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12893                        DAG.getConstant(6, MVT::i32));
12894     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12895                                 MachinePointerInfo(TrmpAddr, 6),
12896                                 false, false, 1);
12897
12898     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12899   }
12900 }
12901
12902 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12903                                             SelectionDAG &DAG) const {
12904   /*
12905    The rounding mode is in bits 11:10 of FPSR, and has the following
12906    settings:
12907      00 Round to nearest
12908      01 Round to -inf
12909      10 Round to +inf
12910      11 Round to 0
12911
12912   FLT_ROUNDS, on the other hand, expects the following:
12913     -1 Undefined
12914      0 Round to 0
12915      1 Round to nearest
12916      2 Round to +inf
12917      3 Round to -inf
12918
12919   To perform the conversion, we do:
12920     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12921   */
12922
12923   MachineFunction &MF = DAG.getMachineFunction();
12924   const TargetMachine &TM = MF.getTarget();
12925   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12926   unsigned StackAlignment = TFI.getStackAlignment();
12927   MVT VT = Op.getSimpleValueType();
12928   SDLoc DL(Op);
12929
12930   // Save FP Control Word to stack slot
12931   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12932   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12933
12934   MachineMemOperand *MMO =
12935    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12936                            MachineMemOperand::MOStore, 2, 2);
12937
12938   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12939   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12940                                           DAG.getVTList(MVT::Other),
12941                                           Ops, array_lengthof(Ops), MVT::i16,
12942                                           MMO);
12943
12944   // Load FP Control Word from stack slot
12945   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12946                             MachinePointerInfo(), false, false, false, 0);
12947
12948   // Transform as necessary
12949   SDValue CWD1 =
12950     DAG.getNode(ISD::SRL, DL, MVT::i16,
12951                 DAG.getNode(ISD::AND, DL, MVT::i16,
12952                             CWD, DAG.getConstant(0x800, MVT::i16)),
12953                 DAG.getConstant(11, MVT::i8));
12954   SDValue CWD2 =
12955     DAG.getNode(ISD::SRL, DL, MVT::i16,
12956                 DAG.getNode(ISD::AND, DL, MVT::i16,
12957                             CWD, DAG.getConstant(0x400, MVT::i16)),
12958                 DAG.getConstant(9, MVT::i8));
12959
12960   SDValue RetVal =
12961     DAG.getNode(ISD::AND, DL, MVT::i16,
12962                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12963                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12964                             DAG.getConstant(1, MVT::i16)),
12965                 DAG.getConstant(3, MVT::i16));
12966
12967   return DAG.getNode((VT.getSizeInBits() < 16 ?
12968                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12969 }
12970
12971 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12972   MVT VT = Op.getSimpleValueType();
12973   EVT OpVT = VT;
12974   unsigned NumBits = VT.getSizeInBits();
12975   SDLoc dl(Op);
12976
12977   Op = Op.getOperand(0);
12978   if (VT == MVT::i8) {
12979     // Zero extend to i32 since there is not an i8 bsr.
12980     OpVT = MVT::i32;
12981     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12982   }
12983
12984   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12985   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12986   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12987
12988   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12989   SDValue Ops[] = {
12990     Op,
12991     DAG.getConstant(NumBits+NumBits-1, OpVT),
12992     DAG.getConstant(X86::COND_E, MVT::i8),
12993     Op.getValue(1)
12994   };
12995   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12996
12997   // Finally xor with NumBits-1.
12998   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12999
13000   if (VT == MVT::i8)
13001     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13002   return Op;
13003 }
13004
13005 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13006   MVT VT = Op.getSimpleValueType();
13007   EVT OpVT = VT;
13008   unsigned NumBits = VT.getSizeInBits();
13009   SDLoc dl(Op);
13010
13011   Op = Op.getOperand(0);
13012   if (VT == MVT::i8) {
13013     // Zero extend to i32 since there is not an i8 bsr.
13014     OpVT = MVT::i32;
13015     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13016   }
13017
13018   // Issue a bsr (scan bits in reverse).
13019   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13020   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13021
13022   // And xor with NumBits-1.
13023   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13024
13025   if (VT == MVT::i8)
13026     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13027   return Op;
13028 }
13029
13030 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13031   MVT VT = Op.getSimpleValueType();
13032   unsigned NumBits = VT.getSizeInBits();
13033   SDLoc dl(Op);
13034   Op = Op.getOperand(0);
13035
13036   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13037   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13038   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13039
13040   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13041   SDValue Ops[] = {
13042     Op,
13043     DAG.getConstant(NumBits, VT),
13044     DAG.getConstant(X86::COND_E, MVT::i8),
13045     Op.getValue(1)
13046   };
13047   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
13048 }
13049
13050 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13051 // ones, and then concatenate the result back.
13052 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13053   MVT VT = Op.getSimpleValueType();
13054
13055   assert(VT.is256BitVector() && VT.isInteger() &&
13056          "Unsupported value type for operation");
13057
13058   unsigned NumElems = VT.getVectorNumElements();
13059   SDLoc dl(Op);
13060
13061   // Extract the LHS vectors
13062   SDValue LHS = Op.getOperand(0);
13063   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13064   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13065
13066   // Extract the RHS vectors
13067   SDValue RHS = Op.getOperand(1);
13068   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13069   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13070
13071   MVT EltVT = VT.getVectorElementType();
13072   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13073
13074   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13075                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13076                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13077 }
13078
13079 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13080   assert(Op.getSimpleValueType().is256BitVector() &&
13081          Op.getSimpleValueType().isInteger() &&
13082          "Only handle AVX 256-bit vector integer operation");
13083   return Lower256IntArith(Op, DAG);
13084 }
13085
13086 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13087   assert(Op.getSimpleValueType().is256BitVector() &&
13088          Op.getSimpleValueType().isInteger() &&
13089          "Only handle AVX 256-bit vector integer operation");
13090   return Lower256IntArith(Op, DAG);
13091 }
13092
13093 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13094                         SelectionDAG &DAG) {
13095   SDLoc dl(Op);
13096   MVT VT = Op.getSimpleValueType();
13097
13098   // Decompose 256-bit ops into smaller 128-bit ops.
13099   if (VT.is256BitVector() && !Subtarget->hasInt256())
13100     return Lower256IntArith(Op, DAG);
13101
13102   SDValue A = Op.getOperand(0);
13103   SDValue B = Op.getOperand(1);
13104
13105   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13106   if (VT == MVT::v4i32) {
13107     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13108            "Should not custom lower when pmuldq is available!");
13109
13110     // Extract the odd parts.
13111     static const int UnpackMask[] = { 1, -1, 3, -1 };
13112     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13113     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13114
13115     // Multiply the even parts.
13116     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13117     // Now multiply odd parts.
13118     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13119
13120     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13121     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13122
13123     // Merge the two vectors back together with a shuffle. This expands into 2
13124     // shuffles.
13125     static const int ShufMask[] = { 0, 4, 2, 6 };
13126     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13127   }
13128
13129   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13130          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13131
13132   //  Ahi = psrlqi(a, 32);
13133   //  Bhi = psrlqi(b, 32);
13134   //
13135   //  AloBlo = pmuludq(a, b);
13136   //  AloBhi = pmuludq(a, Bhi);
13137   //  AhiBlo = pmuludq(Ahi, b);
13138
13139   //  AloBhi = psllqi(AloBhi, 32);
13140   //  AhiBlo = psllqi(AhiBlo, 32);
13141   //  return AloBlo + AloBhi + AhiBlo;
13142
13143   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13144   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13145
13146   // Bit cast to 32-bit vectors for MULUDQ
13147   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13148                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13149   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13150   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13151   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13152   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13153
13154   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13155   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13156   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13157
13158   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13159   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13160
13161   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13162   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13163 }
13164
13165 static SDValue LowerUMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13166                               SelectionDAG &DAG) {
13167   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13168   EVT VT = Op0.getValueType();
13169   SDLoc dl(Op);
13170
13171   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13172          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13173
13174   // Get the high parts.
13175   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13176   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13177   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13178
13179   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13180   // ints.
13181   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13182   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13183                              DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Op0, Op1));
13184   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13185                              DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Hi0, Hi1));
13186
13187   // Shuffle it back into the right order.
13188   const int HighMask[] = {1, 3, 5, 7, 9, 11, 13, 15};
13189   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13190   const int LowMask[] = {0, 2, 4, 6, 8, 10, 12, 14};
13191   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13192
13193   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13194 }
13195
13196 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
13197   MVT VT = Op.getSimpleValueType();
13198   MVT EltTy = VT.getVectorElementType();
13199   unsigned NumElts = VT.getVectorNumElements();
13200   SDValue N0 = Op.getOperand(0);
13201   SDLoc dl(Op);
13202
13203   // Lower sdiv X, pow2-const.
13204   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
13205   if (!C)
13206     return SDValue();
13207
13208   APInt SplatValue, SplatUndef;
13209   unsigned SplatBitSize;
13210   bool HasAnyUndefs;
13211   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
13212                           HasAnyUndefs) ||
13213       EltTy.getSizeInBits() < SplatBitSize)
13214     return SDValue();
13215
13216   if ((SplatValue != 0) &&
13217       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
13218     unsigned Lg2 = SplatValue.countTrailingZeros();
13219     // Splat the sign bit.
13220     SmallVector<SDValue, 16> Sz(NumElts,
13221                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
13222                                                 EltTy));
13223     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
13224                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
13225                                           NumElts));
13226     // Add (N0 < 0) ? abs2 - 1 : 0;
13227     SmallVector<SDValue, 16> Amt(NumElts,
13228                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
13229                                                  EltTy));
13230     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
13231                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
13232                                           NumElts));
13233     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
13234     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
13235     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
13236                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
13237                                           NumElts));
13238
13239     // If we're dividing by a positive value, we're done.  Otherwise, we must
13240     // negate the result.
13241     if (SplatValue.isNonNegative())
13242       return SRA;
13243
13244     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
13245     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
13246     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13247   }
13248   return SDValue();
13249 }
13250
13251 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13252                                          const X86Subtarget *Subtarget) {
13253   MVT VT = Op.getSimpleValueType();
13254   SDLoc dl(Op);
13255   SDValue R = Op.getOperand(0);
13256   SDValue Amt = Op.getOperand(1);
13257
13258   // Optimize shl/srl/sra with constant shift amount.
13259   if (isSplatVector(Amt.getNode())) {
13260     SDValue SclrAmt = Amt->getOperand(0);
13261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13262       uint64_t ShiftAmt = C->getZExtValue();
13263
13264       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13265           (Subtarget->hasInt256() &&
13266            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13267           (Subtarget->hasAVX512() &&
13268            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13269         if (Op.getOpcode() == ISD::SHL)
13270           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13271                                             DAG);
13272         if (Op.getOpcode() == ISD::SRL)
13273           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13274                                             DAG);
13275         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13276           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13277                                             DAG);
13278       }
13279
13280       if (VT == MVT::v16i8) {
13281         if (Op.getOpcode() == ISD::SHL) {
13282           // Make a large shift.
13283           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13284                                                    MVT::v8i16, R, ShiftAmt,
13285                                                    DAG);
13286           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13287           // Zero out the rightmost bits.
13288           SmallVector<SDValue, 16> V(16,
13289                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13290                                                      MVT::i8));
13291           return DAG.getNode(ISD::AND, dl, VT, SHL,
13292                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13293         }
13294         if (Op.getOpcode() == ISD::SRL) {
13295           // Make a large shift.
13296           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13297                                                    MVT::v8i16, R, ShiftAmt,
13298                                                    DAG);
13299           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13300           // Zero out the leftmost bits.
13301           SmallVector<SDValue, 16> V(16,
13302                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13303                                                      MVT::i8));
13304           return DAG.getNode(ISD::AND, dl, VT, SRL,
13305                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13306         }
13307         if (Op.getOpcode() == ISD::SRA) {
13308           if (ShiftAmt == 7) {
13309             // R s>> 7  ===  R s< 0
13310             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13311             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13312           }
13313
13314           // R s>> a === ((R u>> a) ^ m) - m
13315           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13316           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13317                                                          MVT::i8));
13318           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13319           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13320           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13321           return Res;
13322         }
13323         llvm_unreachable("Unknown shift opcode.");
13324       }
13325
13326       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13327         if (Op.getOpcode() == ISD::SHL) {
13328           // Make a large shift.
13329           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13330                                                    MVT::v16i16, R, ShiftAmt,
13331                                                    DAG);
13332           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13333           // Zero out the rightmost bits.
13334           SmallVector<SDValue, 32> V(32,
13335                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13336                                                      MVT::i8));
13337           return DAG.getNode(ISD::AND, dl, VT, SHL,
13338                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13339         }
13340         if (Op.getOpcode() == ISD::SRL) {
13341           // Make a large shift.
13342           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13343                                                    MVT::v16i16, R, ShiftAmt,
13344                                                    DAG);
13345           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13346           // Zero out the leftmost bits.
13347           SmallVector<SDValue, 32> V(32,
13348                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13349                                                      MVT::i8));
13350           return DAG.getNode(ISD::AND, dl, VT, SRL,
13351                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13352         }
13353         if (Op.getOpcode() == ISD::SRA) {
13354           if (ShiftAmt == 7) {
13355             // R s>> 7  ===  R s< 0
13356             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13357             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13358           }
13359
13360           // R s>> a === ((R u>> a) ^ m) - m
13361           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13362           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13363                                                          MVT::i8));
13364           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13365           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13366           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13367           return Res;
13368         }
13369         llvm_unreachable("Unknown shift opcode.");
13370       }
13371     }
13372   }
13373
13374   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13375   if (!Subtarget->is64Bit() &&
13376       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13377       Amt.getOpcode() == ISD::BITCAST &&
13378       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13379     Amt = Amt.getOperand(0);
13380     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13381                      VT.getVectorNumElements();
13382     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13383     uint64_t ShiftAmt = 0;
13384     for (unsigned i = 0; i != Ratio; ++i) {
13385       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13386       if (!C)
13387         return SDValue();
13388       // 6 == Log2(64)
13389       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13390     }
13391     // Check remaining shift amounts.
13392     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13393       uint64_t ShAmt = 0;
13394       for (unsigned j = 0; j != Ratio; ++j) {
13395         ConstantSDNode *C =
13396           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13397         if (!C)
13398           return SDValue();
13399         // 6 == Log2(64)
13400         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13401       }
13402       if (ShAmt != ShiftAmt)
13403         return SDValue();
13404     }
13405     switch (Op.getOpcode()) {
13406     default:
13407       llvm_unreachable("Unknown shift opcode!");
13408     case ISD::SHL:
13409       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13410                                         DAG);
13411     case ISD::SRL:
13412       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13413                                         DAG);
13414     case ISD::SRA:
13415       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13416                                         DAG);
13417     }
13418   }
13419
13420   return SDValue();
13421 }
13422
13423 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13424                                         const X86Subtarget* Subtarget) {
13425   MVT VT = Op.getSimpleValueType();
13426   SDLoc dl(Op);
13427   SDValue R = Op.getOperand(0);
13428   SDValue Amt = Op.getOperand(1);
13429
13430   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13431       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13432       (Subtarget->hasInt256() &&
13433        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13434         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13435        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13436     SDValue BaseShAmt;
13437     EVT EltVT = VT.getVectorElementType();
13438
13439     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13440       unsigned NumElts = VT.getVectorNumElements();
13441       unsigned i, j;
13442       for (i = 0; i != NumElts; ++i) {
13443         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13444           continue;
13445         break;
13446       }
13447       for (j = i; j != NumElts; ++j) {
13448         SDValue Arg = Amt.getOperand(j);
13449         if (Arg.getOpcode() == ISD::UNDEF) continue;
13450         if (Arg != Amt.getOperand(i))
13451           break;
13452       }
13453       if (i != NumElts && j == NumElts)
13454         BaseShAmt = Amt.getOperand(i);
13455     } else {
13456       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13457         Amt = Amt.getOperand(0);
13458       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13459                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13460         SDValue InVec = Amt.getOperand(0);
13461         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13462           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13463           unsigned i = 0;
13464           for (; i != NumElts; ++i) {
13465             SDValue Arg = InVec.getOperand(i);
13466             if (Arg.getOpcode() == ISD::UNDEF) continue;
13467             BaseShAmt = Arg;
13468             break;
13469           }
13470         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13471            if (ConstantSDNode *C =
13472                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13473              unsigned SplatIdx =
13474                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13475              if (C->getZExtValue() == SplatIdx)
13476                BaseShAmt = InVec.getOperand(1);
13477            }
13478         }
13479         if (!BaseShAmt.getNode())
13480           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13481                                   DAG.getIntPtrConstant(0));
13482       }
13483     }
13484
13485     if (BaseShAmt.getNode()) {
13486       if (EltVT.bitsGT(MVT::i32))
13487         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13488       else if (EltVT.bitsLT(MVT::i32))
13489         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13490
13491       switch (Op.getOpcode()) {
13492       default:
13493         llvm_unreachable("Unknown shift opcode!");
13494       case ISD::SHL:
13495         switch (VT.SimpleTy) {
13496         default: return SDValue();
13497         case MVT::v2i64:
13498         case MVT::v4i32:
13499         case MVT::v8i16:
13500         case MVT::v4i64:
13501         case MVT::v8i32:
13502         case MVT::v16i16:
13503         case MVT::v16i32:
13504         case MVT::v8i64:
13505           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13506         }
13507       case ISD::SRA:
13508         switch (VT.SimpleTy) {
13509         default: return SDValue();
13510         case MVT::v4i32:
13511         case MVT::v8i16:
13512         case MVT::v8i32:
13513         case MVT::v16i16:
13514         case MVT::v16i32:
13515         case MVT::v8i64:
13516           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13517         }
13518       case ISD::SRL:
13519         switch (VT.SimpleTy) {
13520         default: return SDValue();
13521         case MVT::v2i64:
13522         case MVT::v4i32:
13523         case MVT::v8i16:
13524         case MVT::v4i64:
13525         case MVT::v8i32:
13526         case MVT::v16i16:
13527         case MVT::v16i32:
13528         case MVT::v8i64:
13529           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13530         }
13531       }
13532     }
13533   }
13534
13535   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13536   if (!Subtarget->is64Bit() &&
13537       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13538       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13539       Amt.getOpcode() == ISD::BITCAST &&
13540       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13541     Amt = Amt.getOperand(0);
13542     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13543                      VT.getVectorNumElements();
13544     std::vector<SDValue> Vals(Ratio);
13545     for (unsigned i = 0; i != Ratio; ++i)
13546       Vals[i] = Amt.getOperand(i);
13547     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13548       for (unsigned j = 0; j != Ratio; ++j)
13549         if (Vals[j] != Amt.getOperand(i + j))
13550           return SDValue();
13551     }
13552     switch (Op.getOpcode()) {
13553     default:
13554       llvm_unreachable("Unknown shift opcode!");
13555     case ISD::SHL:
13556       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13557     case ISD::SRL:
13558       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13559     case ISD::SRA:
13560       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13561     }
13562   }
13563
13564   return SDValue();
13565 }
13566
13567 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13568                           SelectionDAG &DAG) {
13569
13570   MVT VT = Op.getSimpleValueType();
13571   SDLoc dl(Op);
13572   SDValue R = Op.getOperand(0);
13573   SDValue Amt = Op.getOperand(1);
13574   SDValue V;
13575
13576   if (!Subtarget->hasSSE2())
13577     return SDValue();
13578
13579   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13580   if (V.getNode())
13581     return V;
13582
13583   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13584   if (V.getNode())
13585       return V;
13586
13587   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13588     return Op;
13589   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13590   if (Subtarget->hasInt256()) {
13591     if (Op.getOpcode() == ISD::SRL &&
13592         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13593          VT == MVT::v4i64 || VT == MVT::v8i32))
13594       return Op;
13595     if (Op.getOpcode() == ISD::SHL &&
13596         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13597          VT == MVT::v4i64 || VT == MVT::v8i32))
13598       return Op;
13599     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13600       return Op;
13601   }
13602
13603   // If possible, lower this packed shift into a vector multiply instead of
13604   // expanding it into a sequence of scalar shifts.
13605   // Do this only if the vector shift count is a constant build_vector.
13606   if (Op.getOpcode() == ISD::SHL && 
13607       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13608        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13609       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13610     SmallVector<SDValue, 8> Elts;
13611     EVT SVT = VT.getScalarType();
13612     unsigned SVTBits = SVT.getSizeInBits();
13613     const APInt &One = APInt(SVTBits, 1);
13614     unsigned NumElems = VT.getVectorNumElements();
13615
13616     for (unsigned i=0; i !=NumElems; ++i) {
13617       SDValue Op = Amt->getOperand(i);
13618       if (Op->getOpcode() == ISD::UNDEF) {
13619         Elts.push_back(Op);
13620         continue;
13621       }
13622
13623       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13624       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13625       uint64_t ShAmt = C.getZExtValue();
13626       if (ShAmt >= SVTBits) {
13627         Elts.push_back(DAG.getUNDEF(SVT));
13628         continue;
13629       }
13630       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13631     }
13632     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13633     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13634   }
13635
13636   // Lower SHL with variable shift amount.
13637   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13638     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13639
13640     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13641     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13642     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13643     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13644   }
13645
13646   // If possible, lower this shift as a sequence of two shifts by
13647   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13648   // Example:
13649   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13650   //
13651   // Could be rewritten as:
13652   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13653   //
13654   // The advantage is that the two shifts from the example would be
13655   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13656   // the vector shift into four scalar shifts plus four pairs of vector
13657   // insert/extract.
13658   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13659       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13660     unsigned TargetOpcode = X86ISD::MOVSS;
13661     bool CanBeSimplified;
13662     // The splat value for the first packed shift (the 'X' from the example).
13663     SDValue Amt1 = Amt->getOperand(0);
13664     // The splat value for the second packed shift (the 'Y' from the example).
13665     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13666                                         Amt->getOperand(2);
13667
13668     // See if it is possible to replace this node with a sequence of
13669     // two shifts followed by a MOVSS/MOVSD
13670     if (VT == MVT::v4i32) {
13671       // Check if it is legal to use a MOVSS.
13672       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13673                         Amt2 == Amt->getOperand(3);
13674       if (!CanBeSimplified) {
13675         // Otherwise, check if we can still simplify this node using a MOVSD.
13676         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13677                           Amt->getOperand(2) == Amt->getOperand(3);
13678         TargetOpcode = X86ISD::MOVSD;
13679         Amt2 = Amt->getOperand(2);
13680       }
13681     } else {
13682       // Do similar checks for the case where the machine value type
13683       // is MVT::v8i16.
13684       CanBeSimplified = Amt1 == Amt->getOperand(1);
13685       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13686         CanBeSimplified = Amt2 == Amt->getOperand(i);
13687
13688       if (!CanBeSimplified) {
13689         TargetOpcode = X86ISD::MOVSD;
13690         CanBeSimplified = true;
13691         Amt2 = Amt->getOperand(4);
13692         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13693           CanBeSimplified = Amt1 == Amt->getOperand(i);
13694         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13695           CanBeSimplified = Amt2 == Amt->getOperand(j);
13696       }
13697     }
13698     
13699     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13700         isa<ConstantSDNode>(Amt2)) {
13701       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13702       EVT CastVT = MVT::v4i32;
13703       SDValue Splat1 = 
13704         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13705       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13706       SDValue Splat2 = 
13707         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13708       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13709       if (TargetOpcode == X86ISD::MOVSD)
13710         CastVT = MVT::v2i64;
13711       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13712       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13713       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13714                                             BitCast1, DAG);
13715       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13716     }
13717   }
13718
13719   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13720     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13721
13722     // a = a << 5;
13723     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13724     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13725
13726     // Turn 'a' into a mask suitable for VSELECT
13727     SDValue VSelM = DAG.getConstant(0x80, VT);
13728     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13729     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13730
13731     SDValue CM1 = DAG.getConstant(0x0f, VT);
13732     SDValue CM2 = DAG.getConstant(0x3f, VT);
13733
13734     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13735     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13736     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13737     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13738     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13739
13740     // a += a
13741     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13742     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13743     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13744
13745     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13746     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13747     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13748     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13749     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13750
13751     // a += a
13752     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13753     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13754     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13755
13756     // return VSELECT(r, r+r, a);
13757     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13758                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13759     return R;
13760   }
13761
13762   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13763   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13764   // solution better.
13765   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13766     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13767     unsigned ExtOpc =
13768         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13769     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13770     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13771     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13772                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13773     }
13774
13775   // Decompose 256-bit shifts into smaller 128-bit shifts.
13776   if (VT.is256BitVector()) {
13777     unsigned NumElems = VT.getVectorNumElements();
13778     MVT EltVT = VT.getVectorElementType();
13779     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13780
13781     // Extract the two vectors
13782     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13783     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13784
13785     // Recreate the shift amount vectors
13786     SDValue Amt1, Amt2;
13787     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13788       // Constant shift amount
13789       SmallVector<SDValue, 4> Amt1Csts;
13790       SmallVector<SDValue, 4> Amt2Csts;
13791       for (unsigned i = 0; i != NumElems/2; ++i)
13792         Amt1Csts.push_back(Amt->getOperand(i));
13793       for (unsigned i = NumElems/2; i != NumElems; ++i)
13794         Amt2Csts.push_back(Amt->getOperand(i));
13795
13796       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13797                                  &Amt1Csts[0], NumElems/2);
13798       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13799                                  &Amt2Csts[0], NumElems/2);
13800     } else {
13801       // Variable shift amount
13802       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13803       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13804     }
13805
13806     // Issue new vector shifts for the smaller types
13807     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13808     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13809
13810     // Concatenate the result back
13811     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13812   }
13813
13814   return SDValue();
13815 }
13816
13817 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13818   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13819   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13820   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13821   // has only one use.
13822   SDNode *N = Op.getNode();
13823   SDValue LHS = N->getOperand(0);
13824   SDValue RHS = N->getOperand(1);
13825   unsigned BaseOp = 0;
13826   unsigned Cond = 0;
13827   SDLoc DL(Op);
13828   switch (Op.getOpcode()) {
13829   default: llvm_unreachable("Unknown ovf instruction!");
13830   case ISD::SADDO:
13831     // A subtract of one will be selected as a INC. Note that INC doesn't
13832     // set CF, so we can't do this for UADDO.
13833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13834       if (C->isOne()) {
13835         BaseOp = X86ISD::INC;
13836         Cond = X86::COND_O;
13837         break;
13838       }
13839     BaseOp = X86ISD::ADD;
13840     Cond = X86::COND_O;
13841     break;
13842   case ISD::UADDO:
13843     BaseOp = X86ISD::ADD;
13844     Cond = X86::COND_B;
13845     break;
13846   case ISD::SSUBO:
13847     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13848     // set CF, so we can't do this for USUBO.
13849     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13850       if (C->isOne()) {
13851         BaseOp = X86ISD::DEC;
13852         Cond = X86::COND_O;
13853         break;
13854       }
13855     BaseOp = X86ISD::SUB;
13856     Cond = X86::COND_O;
13857     break;
13858   case ISD::USUBO:
13859     BaseOp = X86ISD::SUB;
13860     Cond = X86::COND_B;
13861     break;
13862   case ISD::SMULO:
13863     BaseOp = X86ISD::SMUL;
13864     Cond = X86::COND_O;
13865     break;
13866   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13867     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13868                                  MVT::i32);
13869     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13870
13871     SDValue SetCC =
13872       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13873                   DAG.getConstant(X86::COND_O, MVT::i32),
13874                   SDValue(Sum.getNode(), 2));
13875
13876     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13877   }
13878   }
13879
13880   // Also sets EFLAGS.
13881   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13882   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13883
13884   SDValue SetCC =
13885     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13886                 DAG.getConstant(Cond, MVT::i32),
13887                 SDValue(Sum.getNode(), 1));
13888
13889   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13890 }
13891
13892 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13893                                                   SelectionDAG &DAG) const {
13894   SDLoc dl(Op);
13895   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13896   MVT VT = Op.getSimpleValueType();
13897
13898   if (!Subtarget->hasSSE2() || !VT.isVector())
13899     return SDValue();
13900
13901   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13902                       ExtraVT.getScalarType().getSizeInBits();
13903
13904   switch (VT.SimpleTy) {
13905     default: return SDValue();
13906     case MVT::v8i32:
13907     case MVT::v16i16:
13908       if (!Subtarget->hasFp256())
13909         return SDValue();
13910       if (!Subtarget->hasInt256()) {
13911         // needs to be split
13912         unsigned NumElems = VT.getVectorNumElements();
13913
13914         // Extract the LHS vectors
13915         SDValue LHS = Op.getOperand(0);
13916         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13917         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13918
13919         MVT EltVT = VT.getVectorElementType();
13920         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13921
13922         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13923         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13924         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13925                                    ExtraNumElems/2);
13926         SDValue Extra = DAG.getValueType(ExtraVT);
13927
13928         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13929         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13930
13931         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13932       }
13933       // fall through
13934     case MVT::v4i32:
13935     case MVT::v8i16: {
13936       SDValue Op0 = Op.getOperand(0);
13937       SDValue Op00 = Op0.getOperand(0);
13938       SDValue Tmp1;
13939       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13940       if (Op0.getOpcode() == ISD::BITCAST &&
13941           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13942         // (sext (vzext x)) -> (vsext x)
13943         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13944         if (Tmp1.getNode()) {
13945           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13946           // This folding is only valid when the in-reg type is a vector of i8,
13947           // i16, or i32.
13948           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13949               ExtraEltVT == MVT::i32) {
13950             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13951             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13952                    "This optimization is invalid without a VZEXT.");
13953             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13954           }
13955           Op0 = Tmp1;
13956         }
13957       }
13958
13959       // If the above didn't work, then just use Shift-Left + Shift-Right.
13960       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13961                                         DAG);
13962       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13963                                         DAG);
13964     }
13965   }
13966 }
13967
13968 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13969                                  SelectionDAG &DAG) {
13970   SDLoc dl(Op);
13971   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13972     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13973   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13974     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13975
13976   // The only fence that needs an instruction is a sequentially-consistent
13977   // cross-thread fence.
13978   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13979     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13980     // no-sse2). There isn't any reason to disable it if the target processor
13981     // supports it.
13982     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13983       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13984
13985     SDValue Chain = Op.getOperand(0);
13986     SDValue Zero = DAG.getConstant(0, MVT::i32);
13987     SDValue Ops[] = {
13988       DAG.getRegister(X86::ESP, MVT::i32), // Base
13989       DAG.getTargetConstant(1, MVT::i8),   // Scale
13990       DAG.getRegister(0, MVT::i32),        // Index
13991       DAG.getTargetConstant(0, MVT::i32),  // Disp
13992       DAG.getRegister(0, MVT::i32),        // Segment.
13993       Zero,
13994       Chain
13995     };
13996     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13997     return SDValue(Res, 0);
13998   }
13999
14000   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14001   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14002 }
14003
14004 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14005                              SelectionDAG &DAG) {
14006   MVT T = Op.getSimpleValueType();
14007   SDLoc DL(Op);
14008   unsigned Reg = 0;
14009   unsigned size = 0;
14010   switch(T.SimpleTy) {
14011   default: llvm_unreachable("Invalid value type!");
14012   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14013   case MVT::i16: Reg = X86::AX;  size = 2; break;
14014   case MVT::i32: Reg = X86::EAX; size = 4; break;
14015   case MVT::i64:
14016     assert(Subtarget->is64Bit() && "Node not type legal!");
14017     Reg = X86::RAX; size = 8;
14018     break;
14019   }
14020   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14021                                     Op.getOperand(2), SDValue());
14022   SDValue Ops[] = { cpIn.getValue(0),
14023                     Op.getOperand(1),
14024                     Op.getOperand(3),
14025                     DAG.getTargetConstant(size, MVT::i8),
14026                     cpIn.getValue(1) };
14027   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14028   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14029   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14030                                            Ops, array_lengthof(Ops), T, MMO);
14031   SDValue cpOut =
14032     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14033   return cpOut;
14034 }
14035
14036 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14037                             SelectionDAG &DAG) {
14038   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14039   MVT DstVT = Op.getSimpleValueType();
14040   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14041          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14042   assert((DstVT == MVT::i64 ||
14043           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14044          "Unexpected custom BITCAST");
14045   // i64 <=> MMX conversions are Legal.
14046   if (SrcVT==MVT::i64 && DstVT.isVector())
14047     return Op;
14048   if (DstVT==MVT::i64 && SrcVT.isVector())
14049     return Op;
14050   // MMX <=> MMX conversions are Legal.
14051   if (SrcVT.isVector() && DstVT.isVector())
14052     return Op;
14053   // All other conversions need to be expanded.
14054   return SDValue();
14055 }
14056
14057 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14058   SDNode *Node = Op.getNode();
14059   SDLoc dl(Node);
14060   EVT T = Node->getValueType(0);
14061   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14062                               DAG.getConstant(0, T), Node->getOperand(2));
14063   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14064                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14065                        Node->getOperand(0),
14066                        Node->getOperand(1), negOp,
14067                        cast<AtomicSDNode>(Node)->getMemOperand(),
14068                        cast<AtomicSDNode>(Node)->getOrdering(),
14069                        cast<AtomicSDNode>(Node)->getSynchScope());
14070 }
14071
14072 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14073   SDNode *Node = Op.getNode();
14074   SDLoc dl(Node);
14075   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14076
14077   // Convert seq_cst store -> xchg
14078   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14079   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14080   //        (The only way to get a 16-byte store is cmpxchg16b)
14081   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14082   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14083       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14084     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14085                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14086                                  Node->getOperand(0),
14087                                  Node->getOperand(1), Node->getOperand(2),
14088                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14089                                  cast<AtomicSDNode>(Node)->getOrdering(),
14090                                  cast<AtomicSDNode>(Node)->getSynchScope());
14091     return Swap.getValue(1);
14092   }
14093   // Other atomic stores have a simple pattern.
14094   return Op;
14095 }
14096
14097 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14098   EVT VT = Op.getNode()->getSimpleValueType(0);
14099
14100   // Let legalize expand this if it isn't a legal type yet.
14101   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14102     return SDValue();
14103
14104   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14105
14106   unsigned Opc;
14107   bool ExtraOp = false;
14108   switch (Op.getOpcode()) {
14109   default: llvm_unreachable("Invalid code");
14110   case ISD::ADDC: Opc = X86ISD::ADD; break;
14111   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14112   case ISD::SUBC: Opc = X86ISD::SUB; break;
14113   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14114   }
14115
14116   if (!ExtraOp)
14117     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14118                        Op.getOperand(1));
14119   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14120                      Op.getOperand(1), Op.getOperand(2));
14121 }
14122
14123 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14124                             SelectionDAG &DAG) {
14125   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14126
14127   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14128   // which returns the values as { float, float } (in XMM0) or
14129   // { double, double } (which is returned in XMM0, XMM1).
14130   SDLoc dl(Op);
14131   SDValue Arg = Op.getOperand(0);
14132   EVT ArgVT = Arg.getValueType();
14133   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14134
14135   TargetLowering::ArgListTy Args;
14136   TargetLowering::ArgListEntry Entry;
14137
14138   Entry.Node = Arg;
14139   Entry.Ty = ArgTy;
14140   Entry.isSExt = false;
14141   Entry.isZExt = false;
14142   Args.push_back(Entry);
14143
14144   bool isF64 = ArgVT == MVT::f64;
14145   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14146   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14147   // the results are returned via SRet in memory.
14148   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14150   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14151
14152   Type *RetTy = isF64
14153     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14154     : (Type*)VectorType::get(ArgTy, 4);
14155   TargetLowering::
14156     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14157                          false, false, false, false, 0,
14158                          CallingConv::C, /*isTaillCall=*/false,
14159                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14160                          Callee, Args, DAG, dl);
14161   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14162
14163   if (isF64)
14164     // Returned in xmm0 and xmm1.
14165     return CallResult.first;
14166
14167   // Returned in bits 0:31 and 32:64 xmm0.
14168   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14169                                CallResult.first, DAG.getIntPtrConstant(0));
14170   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14171                                CallResult.first, DAG.getIntPtrConstant(1));
14172   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14173   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14174 }
14175
14176 /// LowerOperation - Provide custom lowering hooks for some operations.
14177 ///
14178 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14179   switch (Op.getOpcode()) {
14180   default: llvm_unreachable("Should not custom lower this!");
14181   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14182   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14183   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14184   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14185   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14186   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14187   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14188   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14189   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14190   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14191   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14192   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14193   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14194   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14195   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14196   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14197   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14198   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14199   case ISD::SHL_PARTS:
14200   case ISD::SRA_PARTS:
14201   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14202   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14203   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14204   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14205   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14206   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14207   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14208   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14209   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14210   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14211   case ISD::FABS:               return LowerFABS(Op, DAG);
14212   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14213   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14214   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14215   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14216   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14217   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14218   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14219   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14220   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14221   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14222   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14223   case ISD::INTRINSIC_VOID:
14224   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14225   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14226   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14227   case ISD::FRAME_TO_ARGS_OFFSET:
14228                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14229   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14230   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14231   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14232   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14233   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14234   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14235   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14236   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14237   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14238   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14239   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14240   case ISD::UMUL_LOHI:          return LowerUMUL_LOHI(Op, Subtarget, DAG);
14241   case ISD::SRA:
14242   case ISD::SRL:
14243   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14244   case ISD::SADDO:
14245   case ISD::UADDO:
14246   case ISD::SSUBO:
14247   case ISD::USUBO:
14248   case ISD::SMULO:
14249   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14250   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14251   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14252   case ISD::ADDC:
14253   case ISD::ADDE:
14254   case ISD::SUBC:
14255   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14256   case ISD::ADD:                return LowerADD(Op, DAG);
14257   case ISD::SUB:                return LowerSUB(Op, DAG);
14258   case ISD::SDIV:               return LowerSDIV(Op, DAG);
14259   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14260   }
14261 }
14262
14263 static void ReplaceATOMIC_LOAD(SDNode *Node,
14264                                   SmallVectorImpl<SDValue> &Results,
14265                                   SelectionDAG &DAG) {
14266   SDLoc dl(Node);
14267   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14268
14269   // Convert wide load -> cmpxchg8b/cmpxchg16b
14270   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14271   //        (The only way to get a 16-byte load is cmpxchg16b)
14272   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14273   SDValue Zero = DAG.getConstant(0, VT);
14274   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14275                                Node->getOperand(0),
14276                                Node->getOperand(1), Zero, Zero,
14277                                cast<AtomicSDNode>(Node)->getMemOperand(),
14278                                cast<AtomicSDNode>(Node)->getOrdering(),
14279                                cast<AtomicSDNode>(Node)->getOrdering(),
14280                                cast<AtomicSDNode>(Node)->getSynchScope());
14281   Results.push_back(Swap.getValue(0));
14282   Results.push_back(Swap.getValue(1));
14283 }
14284
14285 static void
14286 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14287                         SelectionDAG &DAG, unsigned NewOp) {
14288   SDLoc dl(Node);
14289   assert (Node->getValueType(0) == MVT::i64 &&
14290           "Only know how to expand i64 atomics");
14291
14292   SDValue Chain = Node->getOperand(0);
14293   SDValue In1 = Node->getOperand(1);
14294   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14295                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14296   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14297                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14298   SDValue Ops[] = { Chain, In1, In2L, In2H };
14299   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14300   SDValue Result =
14301     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14302                             cast<MemSDNode>(Node)->getMemOperand());
14303   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14304   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14305   Results.push_back(Result.getValue(2));
14306 }
14307
14308 /// ReplaceNodeResults - Replace a node with an illegal result type
14309 /// with a new node built out of custom code.
14310 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14311                                            SmallVectorImpl<SDValue>&Results,
14312                                            SelectionDAG &DAG) const {
14313   SDLoc dl(N);
14314   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14315   switch (N->getOpcode()) {
14316   default:
14317     llvm_unreachable("Do not know how to custom type legalize this operation!");
14318   case ISD::SIGN_EXTEND_INREG:
14319   case ISD::ADDC:
14320   case ISD::ADDE:
14321   case ISD::SUBC:
14322   case ISD::SUBE:
14323     // We don't want to expand or promote these.
14324     return;
14325   case ISD::FP_TO_SINT:
14326   case ISD::FP_TO_UINT: {
14327     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14328
14329     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14330       return;
14331
14332     std::pair<SDValue,SDValue> Vals =
14333         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14334     SDValue FIST = Vals.first, StackSlot = Vals.second;
14335     if (FIST.getNode()) {
14336       EVT VT = N->getValueType(0);
14337       // Return a load from the stack slot.
14338       if (StackSlot.getNode())
14339         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14340                                       MachinePointerInfo(),
14341                                       false, false, false, 0));
14342       else
14343         Results.push_back(FIST);
14344     }
14345     return;
14346   }
14347   case ISD::UINT_TO_FP: {
14348     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14349     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14350         N->getValueType(0) != MVT::v2f32)
14351       return;
14352     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14353                                  N->getOperand(0));
14354     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14355                                      MVT::f64);
14356     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14357     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14358                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14359     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14360     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14361     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14362     return;
14363   }
14364   case ISD::FP_ROUND: {
14365     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14366         return;
14367     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14368     Results.push_back(V);
14369     return;
14370   }
14371   case ISD::INTRINSIC_W_CHAIN: {
14372     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14373     switch (IntNo) {
14374     default : llvm_unreachable("Do not know how to custom type "
14375                                "legalize this intrinsic operation!");
14376     case Intrinsic::x86_rdtsc:
14377       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14378                                      Results);
14379     case Intrinsic::x86_rdtscp:
14380       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14381                                      Results);
14382     }
14383   }
14384   case ISD::READCYCLECOUNTER: {
14385     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14386                                    Results);
14387   }
14388   case ISD::ATOMIC_CMP_SWAP: {
14389     EVT T = N->getValueType(0);
14390     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14391     bool Regs64bit = T == MVT::i128;
14392     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14393     SDValue cpInL, cpInH;
14394     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14395                         DAG.getConstant(0, HalfT));
14396     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14397                         DAG.getConstant(1, HalfT));
14398     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14399                              Regs64bit ? X86::RAX : X86::EAX,
14400                              cpInL, SDValue());
14401     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14402                              Regs64bit ? X86::RDX : X86::EDX,
14403                              cpInH, cpInL.getValue(1));
14404     SDValue swapInL, swapInH;
14405     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14406                           DAG.getConstant(0, HalfT));
14407     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14408                           DAG.getConstant(1, HalfT));
14409     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14410                                Regs64bit ? X86::RBX : X86::EBX,
14411                                swapInL, cpInH.getValue(1));
14412     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14413                                Regs64bit ? X86::RCX : X86::ECX,
14414                                swapInH, swapInL.getValue(1));
14415     SDValue Ops[] = { swapInH.getValue(0),
14416                       N->getOperand(1),
14417                       swapInH.getValue(1) };
14418     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14419     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14420     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14421                                   X86ISD::LCMPXCHG8_DAG;
14422     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14423                                              Ops, array_lengthof(Ops), T, MMO);
14424     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14425                                         Regs64bit ? X86::RAX : X86::EAX,
14426                                         HalfT, Result.getValue(1));
14427     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14428                                         Regs64bit ? X86::RDX : X86::EDX,
14429                                         HalfT, cpOutL.getValue(2));
14430     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14431     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14432     Results.push_back(cpOutH.getValue(1));
14433     return;
14434   }
14435   case ISD::ATOMIC_LOAD_ADD:
14436   case ISD::ATOMIC_LOAD_AND:
14437   case ISD::ATOMIC_LOAD_NAND:
14438   case ISD::ATOMIC_LOAD_OR:
14439   case ISD::ATOMIC_LOAD_SUB:
14440   case ISD::ATOMIC_LOAD_XOR:
14441   case ISD::ATOMIC_LOAD_MAX:
14442   case ISD::ATOMIC_LOAD_MIN:
14443   case ISD::ATOMIC_LOAD_UMAX:
14444   case ISD::ATOMIC_LOAD_UMIN:
14445   case ISD::ATOMIC_SWAP: {
14446     unsigned Opc;
14447     switch (N->getOpcode()) {
14448     default: llvm_unreachable("Unexpected opcode");
14449     case ISD::ATOMIC_LOAD_ADD:
14450       Opc = X86ISD::ATOMADD64_DAG;
14451       break;
14452     case ISD::ATOMIC_LOAD_AND:
14453       Opc = X86ISD::ATOMAND64_DAG;
14454       break;
14455     case ISD::ATOMIC_LOAD_NAND:
14456       Opc = X86ISD::ATOMNAND64_DAG;
14457       break;
14458     case ISD::ATOMIC_LOAD_OR:
14459       Opc = X86ISD::ATOMOR64_DAG;
14460       break;
14461     case ISD::ATOMIC_LOAD_SUB:
14462       Opc = X86ISD::ATOMSUB64_DAG;
14463       break;
14464     case ISD::ATOMIC_LOAD_XOR:
14465       Opc = X86ISD::ATOMXOR64_DAG;
14466       break;
14467     case ISD::ATOMIC_LOAD_MAX:
14468       Opc = X86ISD::ATOMMAX64_DAG;
14469       break;
14470     case ISD::ATOMIC_LOAD_MIN:
14471       Opc = X86ISD::ATOMMIN64_DAG;
14472       break;
14473     case ISD::ATOMIC_LOAD_UMAX:
14474       Opc = X86ISD::ATOMUMAX64_DAG;
14475       break;
14476     case ISD::ATOMIC_LOAD_UMIN:
14477       Opc = X86ISD::ATOMUMIN64_DAG;
14478       break;
14479     case ISD::ATOMIC_SWAP:
14480       Opc = X86ISD::ATOMSWAP64_DAG;
14481       break;
14482     }
14483     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14484     return;
14485   }
14486   case ISD::ATOMIC_LOAD:
14487     ReplaceATOMIC_LOAD(N, Results, DAG);
14488   }
14489 }
14490
14491 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14492   switch (Opcode) {
14493   default: return nullptr;
14494   case X86ISD::BSF:                return "X86ISD::BSF";
14495   case X86ISD::BSR:                return "X86ISD::BSR";
14496   case X86ISD::SHLD:               return "X86ISD::SHLD";
14497   case X86ISD::SHRD:               return "X86ISD::SHRD";
14498   case X86ISD::FAND:               return "X86ISD::FAND";
14499   case X86ISD::FANDN:              return "X86ISD::FANDN";
14500   case X86ISD::FOR:                return "X86ISD::FOR";
14501   case X86ISD::FXOR:               return "X86ISD::FXOR";
14502   case X86ISD::FSRL:               return "X86ISD::FSRL";
14503   case X86ISD::FILD:               return "X86ISD::FILD";
14504   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14505   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14506   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14507   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14508   case X86ISD::FLD:                return "X86ISD::FLD";
14509   case X86ISD::FST:                return "X86ISD::FST";
14510   case X86ISD::CALL:               return "X86ISD::CALL";
14511   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14512   case X86ISD::BT:                 return "X86ISD::BT";
14513   case X86ISD::CMP:                return "X86ISD::CMP";
14514   case X86ISD::COMI:               return "X86ISD::COMI";
14515   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14516   case X86ISD::CMPM:               return "X86ISD::CMPM";
14517   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14518   case X86ISD::SETCC:              return "X86ISD::SETCC";
14519   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14520   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14521   case X86ISD::CMOV:               return "X86ISD::CMOV";
14522   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14523   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14524   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14525   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14526   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14527   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14528   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14529   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14530   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14531   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14532   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14533   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14534   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14535   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14536   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14537   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14538   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14539   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14540   case X86ISD::HADD:               return "X86ISD::HADD";
14541   case X86ISD::HSUB:               return "X86ISD::HSUB";
14542   case X86ISD::FHADD:              return "X86ISD::FHADD";
14543   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14544   case X86ISD::UMAX:               return "X86ISD::UMAX";
14545   case X86ISD::UMIN:               return "X86ISD::UMIN";
14546   case X86ISD::SMAX:               return "X86ISD::SMAX";
14547   case X86ISD::SMIN:               return "X86ISD::SMIN";
14548   case X86ISD::FMAX:               return "X86ISD::FMAX";
14549   case X86ISD::FMIN:               return "X86ISD::FMIN";
14550   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14551   case X86ISD::FMINC:              return "X86ISD::FMINC";
14552   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14553   case X86ISD::FRCP:               return "X86ISD::FRCP";
14554   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14555   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14556   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14557   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14558   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14559   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14560   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14561   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14562   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14563   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14564   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14565   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14566   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14567   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14568   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14569   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14570   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14571   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14572   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14573   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14574   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14575   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14576   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14577   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14578   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14579   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14580   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14581   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14582   case X86ISD::VSHL:               return "X86ISD::VSHL";
14583   case X86ISD::VSRL:               return "X86ISD::VSRL";
14584   case X86ISD::VSRA:               return "X86ISD::VSRA";
14585   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14586   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14587   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14588   case X86ISD::CMPP:               return "X86ISD::CMPP";
14589   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14590   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14591   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14592   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14593   case X86ISD::ADD:                return "X86ISD::ADD";
14594   case X86ISD::SUB:                return "X86ISD::SUB";
14595   case X86ISD::ADC:                return "X86ISD::ADC";
14596   case X86ISD::SBB:                return "X86ISD::SBB";
14597   case X86ISD::SMUL:               return "X86ISD::SMUL";
14598   case X86ISD::UMUL:               return "X86ISD::UMUL";
14599   case X86ISD::INC:                return "X86ISD::INC";
14600   case X86ISD::DEC:                return "X86ISD::DEC";
14601   case X86ISD::OR:                 return "X86ISD::OR";
14602   case X86ISD::XOR:                return "X86ISD::XOR";
14603   case X86ISD::AND:                return "X86ISD::AND";
14604   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14605   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14606   case X86ISD::PTEST:              return "X86ISD::PTEST";
14607   case X86ISD::TESTP:              return "X86ISD::TESTP";
14608   case X86ISD::TESTM:              return "X86ISD::TESTM";
14609   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14610   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14611   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14612   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14613   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14614   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14615   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14616   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14617   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14618   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14619   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14620   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14621   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14622   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14623   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14624   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14625   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14626   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14627   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14628   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14629   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14630   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14631   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14632   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14633   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14634   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14635   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14636   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14637   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14638   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14639   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14640   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14641   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14642   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14643   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14644   case X86ISD::SAHF:               return "X86ISD::SAHF";
14645   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14646   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14647   case X86ISD::FMADD:              return "X86ISD::FMADD";
14648   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14649   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14650   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14651   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14652   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14653   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14654   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14655   case X86ISD::XTEST:              return "X86ISD::XTEST";
14656   }
14657 }
14658
14659 // isLegalAddressingMode - Return true if the addressing mode represented
14660 // by AM is legal for this target, for a load/store of the specified type.
14661 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14662                                               Type *Ty) const {
14663   // X86 supports extremely general addressing modes.
14664   CodeModel::Model M = getTargetMachine().getCodeModel();
14665   Reloc::Model R = getTargetMachine().getRelocationModel();
14666
14667   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14668   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14669     return false;
14670
14671   if (AM.BaseGV) {
14672     unsigned GVFlags =
14673       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14674
14675     // If a reference to this global requires an extra load, we can't fold it.
14676     if (isGlobalStubReference(GVFlags))
14677       return false;
14678
14679     // If BaseGV requires a register for the PIC base, we cannot also have a
14680     // BaseReg specified.
14681     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14682       return false;
14683
14684     // If lower 4G is not available, then we must use rip-relative addressing.
14685     if ((M != CodeModel::Small || R != Reloc::Static) &&
14686         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14687       return false;
14688   }
14689
14690   switch (AM.Scale) {
14691   case 0:
14692   case 1:
14693   case 2:
14694   case 4:
14695   case 8:
14696     // These scales always work.
14697     break;
14698   case 3:
14699   case 5:
14700   case 9:
14701     // These scales are formed with basereg+scalereg.  Only accept if there is
14702     // no basereg yet.
14703     if (AM.HasBaseReg)
14704       return false;
14705     break;
14706   default:  // Other stuff never works.
14707     return false;
14708   }
14709
14710   return true;
14711 }
14712
14713 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14714   unsigned Bits = Ty->getScalarSizeInBits();
14715
14716   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14717   // particularly cheaper than those without.
14718   if (Bits == 8)
14719     return false;
14720
14721   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14722   // variable shifts just as cheap as scalar ones.
14723   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14724     return false;
14725
14726   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14727   // fully general vector.
14728   return true;
14729 }
14730
14731 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14732   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14733     return false;
14734   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14735   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14736   return NumBits1 > NumBits2;
14737 }
14738
14739 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14740   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14741     return false;
14742
14743   if (!isTypeLegal(EVT::getEVT(Ty1)))
14744     return false;
14745
14746   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14747
14748   // Assuming the caller doesn't have a zeroext or signext return parameter,
14749   // truncation all the way down to i1 is valid.
14750   return true;
14751 }
14752
14753 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14754   return isInt<32>(Imm);
14755 }
14756
14757 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14758   // Can also use sub to handle negated immediates.
14759   return isInt<32>(Imm);
14760 }
14761
14762 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14763   if (!VT1.isInteger() || !VT2.isInteger())
14764     return false;
14765   unsigned NumBits1 = VT1.getSizeInBits();
14766   unsigned NumBits2 = VT2.getSizeInBits();
14767   return NumBits1 > NumBits2;
14768 }
14769
14770 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14771   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14772   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14773 }
14774
14775 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14776   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14777   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14778 }
14779
14780 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14781   EVT VT1 = Val.getValueType();
14782   if (isZExtFree(VT1, VT2))
14783     return true;
14784
14785   if (Val.getOpcode() != ISD::LOAD)
14786     return false;
14787
14788   if (!VT1.isSimple() || !VT1.isInteger() ||
14789       !VT2.isSimple() || !VT2.isInteger())
14790     return false;
14791
14792   switch (VT1.getSimpleVT().SimpleTy) {
14793   default: break;
14794   case MVT::i8:
14795   case MVT::i16:
14796   case MVT::i32:
14797     // X86 has 8, 16, and 32-bit zero-extending loads.
14798     return true;
14799   }
14800
14801   return false;
14802 }
14803
14804 bool
14805 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14806   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14807     return false;
14808
14809   VT = VT.getScalarType();
14810
14811   if (!VT.isSimple())
14812     return false;
14813
14814   switch (VT.getSimpleVT().SimpleTy) {
14815   case MVT::f32:
14816   case MVT::f64:
14817     return true;
14818   default:
14819     break;
14820   }
14821
14822   return false;
14823 }
14824
14825 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14826   // i16 instructions are longer (0x66 prefix) and potentially slower.
14827   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14828 }
14829
14830 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14831 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14832 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14833 /// are assumed to be legal.
14834 bool
14835 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14836                                       EVT VT) const {
14837   if (!VT.isSimple())
14838     return false;
14839
14840   MVT SVT = VT.getSimpleVT();
14841
14842   // Very little shuffling can be done for 64-bit vectors right now.
14843   if (VT.getSizeInBits() == 64)
14844     return false;
14845
14846   // FIXME: pshufb, blends, shifts.
14847   return (SVT.getVectorNumElements() == 2 ||
14848           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14849           isMOVLMask(M, SVT) ||
14850           isSHUFPMask(M, SVT) ||
14851           isPSHUFDMask(M, SVT) ||
14852           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14853           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14854           isPALIGNRMask(M, SVT, Subtarget) ||
14855           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14856           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14857           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14858           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14859 }
14860
14861 bool
14862 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14863                                           EVT VT) const {
14864   if (!VT.isSimple())
14865     return false;
14866
14867   MVT SVT = VT.getSimpleVT();
14868   unsigned NumElts = SVT.getVectorNumElements();
14869   // FIXME: This collection of masks seems suspect.
14870   if (NumElts == 2)
14871     return true;
14872   if (NumElts == 4 && SVT.is128BitVector()) {
14873     return (isMOVLMask(Mask, SVT)  ||
14874             isCommutedMOVLMask(Mask, SVT, true) ||
14875             isSHUFPMask(Mask, SVT) ||
14876             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14877   }
14878   return false;
14879 }
14880
14881 //===----------------------------------------------------------------------===//
14882 //                           X86 Scheduler Hooks
14883 //===----------------------------------------------------------------------===//
14884
14885 /// Utility function to emit xbegin specifying the start of an RTM region.
14886 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14887                                      const TargetInstrInfo *TII) {
14888   DebugLoc DL = MI->getDebugLoc();
14889
14890   const BasicBlock *BB = MBB->getBasicBlock();
14891   MachineFunction::iterator I = MBB;
14892   ++I;
14893
14894   // For the v = xbegin(), we generate
14895   //
14896   // thisMBB:
14897   //  xbegin sinkMBB
14898   //
14899   // mainMBB:
14900   //  eax = -1
14901   //
14902   // sinkMBB:
14903   //  v = eax
14904
14905   MachineBasicBlock *thisMBB = MBB;
14906   MachineFunction *MF = MBB->getParent();
14907   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14908   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14909   MF->insert(I, mainMBB);
14910   MF->insert(I, sinkMBB);
14911
14912   // Transfer the remainder of BB and its successor edges to sinkMBB.
14913   sinkMBB->splice(sinkMBB->begin(), MBB,
14914                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14915   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14916
14917   // thisMBB:
14918   //  xbegin sinkMBB
14919   //  # fallthrough to mainMBB
14920   //  # abortion to sinkMBB
14921   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14922   thisMBB->addSuccessor(mainMBB);
14923   thisMBB->addSuccessor(sinkMBB);
14924
14925   // mainMBB:
14926   //  EAX = -1
14927   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14928   mainMBB->addSuccessor(sinkMBB);
14929
14930   // sinkMBB:
14931   // EAX is live into the sinkMBB
14932   sinkMBB->addLiveIn(X86::EAX);
14933   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14934           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14935     .addReg(X86::EAX);
14936
14937   MI->eraseFromParent();
14938   return sinkMBB;
14939 }
14940
14941 // Get CMPXCHG opcode for the specified data type.
14942 static unsigned getCmpXChgOpcode(EVT VT) {
14943   switch (VT.getSimpleVT().SimpleTy) {
14944   case MVT::i8:  return X86::LCMPXCHG8;
14945   case MVT::i16: return X86::LCMPXCHG16;
14946   case MVT::i32: return X86::LCMPXCHG32;
14947   case MVT::i64: return X86::LCMPXCHG64;
14948   default:
14949     break;
14950   }
14951   llvm_unreachable("Invalid operand size!");
14952 }
14953
14954 // Get LOAD opcode for the specified data type.
14955 static unsigned getLoadOpcode(EVT VT) {
14956   switch (VT.getSimpleVT().SimpleTy) {
14957   case MVT::i8:  return X86::MOV8rm;
14958   case MVT::i16: return X86::MOV16rm;
14959   case MVT::i32: return X86::MOV32rm;
14960   case MVT::i64: return X86::MOV64rm;
14961   default:
14962     break;
14963   }
14964   llvm_unreachable("Invalid operand size!");
14965 }
14966
14967 // Get opcode of the non-atomic one from the specified atomic instruction.
14968 static unsigned getNonAtomicOpcode(unsigned Opc) {
14969   switch (Opc) {
14970   case X86::ATOMAND8:  return X86::AND8rr;
14971   case X86::ATOMAND16: return X86::AND16rr;
14972   case X86::ATOMAND32: return X86::AND32rr;
14973   case X86::ATOMAND64: return X86::AND64rr;
14974   case X86::ATOMOR8:   return X86::OR8rr;
14975   case X86::ATOMOR16:  return X86::OR16rr;
14976   case X86::ATOMOR32:  return X86::OR32rr;
14977   case X86::ATOMOR64:  return X86::OR64rr;
14978   case X86::ATOMXOR8:  return X86::XOR8rr;
14979   case X86::ATOMXOR16: return X86::XOR16rr;
14980   case X86::ATOMXOR32: return X86::XOR32rr;
14981   case X86::ATOMXOR64: return X86::XOR64rr;
14982   }
14983   llvm_unreachable("Unhandled atomic-load-op opcode!");
14984 }
14985
14986 // Get opcode of the non-atomic one from the specified atomic instruction with
14987 // extra opcode.
14988 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14989                                                unsigned &ExtraOpc) {
14990   switch (Opc) {
14991   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14992   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14993   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14994   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14995   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14996   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14997   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14998   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14999   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15000   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15001   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15002   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15003   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15004   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15005   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15006   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15007   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15008   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15009   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15010   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15011   }
15012   llvm_unreachable("Unhandled atomic-load-op opcode!");
15013 }
15014
15015 // Get opcode of the non-atomic one from the specified atomic instruction for
15016 // 64-bit data type on 32-bit target.
15017 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15018   switch (Opc) {
15019   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15020   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15021   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15022   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15023   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15024   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15025   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15026   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15027   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15028   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15029   }
15030   llvm_unreachable("Unhandled atomic-load-op opcode!");
15031 }
15032
15033 // Get opcode of the non-atomic one from the specified atomic instruction for
15034 // 64-bit data type on 32-bit target with extra opcode.
15035 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15036                                                    unsigned &HiOpc,
15037                                                    unsigned &ExtraOpc) {
15038   switch (Opc) {
15039   case X86::ATOMNAND6432:
15040     ExtraOpc = X86::NOT32r;
15041     HiOpc = X86::AND32rr;
15042     return X86::AND32rr;
15043   }
15044   llvm_unreachable("Unhandled atomic-load-op opcode!");
15045 }
15046
15047 // Get pseudo CMOV opcode from the specified data type.
15048 static unsigned getPseudoCMOVOpc(EVT VT) {
15049   switch (VT.getSimpleVT().SimpleTy) {
15050   case MVT::i8:  return X86::CMOV_GR8;
15051   case MVT::i16: return X86::CMOV_GR16;
15052   case MVT::i32: return X86::CMOV_GR32;
15053   default:
15054     break;
15055   }
15056   llvm_unreachable("Unknown CMOV opcode!");
15057 }
15058
15059 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15060 // They will be translated into a spin-loop or compare-exchange loop from
15061 //
15062 //    ...
15063 //    dst = atomic-fetch-op MI.addr, MI.val
15064 //    ...
15065 //
15066 // to
15067 //
15068 //    ...
15069 //    t1 = LOAD MI.addr
15070 // loop:
15071 //    t4 = phi(t1, t3 / loop)
15072 //    t2 = OP MI.val, t4
15073 //    EAX = t4
15074 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15075 //    t3 = EAX
15076 //    JNE loop
15077 // sink:
15078 //    dst = t3
15079 //    ...
15080 MachineBasicBlock *
15081 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15082                                        MachineBasicBlock *MBB) const {
15083   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15084   DebugLoc DL = MI->getDebugLoc();
15085
15086   MachineFunction *MF = MBB->getParent();
15087   MachineRegisterInfo &MRI = MF->getRegInfo();
15088
15089   const BasicBlock *BB = MBB->getBasicBlock();
15090   MachineFunction::iterator I = MBB;
15091   ++I;
15092
15093   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15094          "Unexpected number of operands");
15095
15096   assert(MI->hasOneMemOperand() &&
15097          "Expected atomic-load-op to have one memoperand");
15098
15099   // Memory Reference
15100   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15101   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15102
15103   unsigned DstReg, SrcReg;
15104   unsigned MemOpndSlot;
15105
15106   unsigned CurOp = 0;
15107
15108   DstReg = MI->getOperand(CurOp++).getReg();
15109   MemOpndSlot = CurOp;
15110   CurOp += X86::AddrNumOperands;
15111   SrcReg = MI->getOperand(CurOp++).getReg();
15112
15113   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15114   MVT::SimpleValueType VT = *RC->vt_begin();
15115   unsigned t1 = MRI.createVirtualRegister(RC);
15116   unsigned t2 = MRI.createVirtualRegister(RC);
15117   unsigned t3 = MRI.createVirtualRegister(RC);
15118   unsigned t4 = MRI.createVirtualRegister(RC);
15119   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15120
15121   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15122   unsigned LOADOpc = getLoadOpcode(VT);
15123
15124   // For the atomic load-arith operator, we generate
15125   //
15126   //  thisMBB:
15127   //    t1 = LOAD [MI.addr]
15128   //  mainMBB:
15129   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15130   //    t1 = OP MI.val, EAX
15131   //    EAX = t4
15132   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15133   //    t3 = EAX
15134   //    JNE mainMBB
15135   //  sinkMBB:
15136   //    dst = t3
15137
15138   MachineBasicBlock *thisMBB = MBB;
15139   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15140   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15141   MF->insert(I, mainMBB);
15142   MF->insert(I, sinkMBB);
15143
15144   MachineInstrBuilder MIB;
15145
15146   // Transfer the remainder of BB and its successor edges to sinkMBB.
15147   sinkMBB->splice(sinkMBB->begin(), MBB,
15148                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15149   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15150
15151   // thisMBB:
15152   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15153   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15154     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15155     if (NewMO.isReg())
15156       NewMO.setIsKill(false);
15157     MIB.addOperand(NewMO);
15158   }
15159   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15160     unsigned flags = (*MMOI)->getFlags();
15161     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15162     MachineMemOperand *MMO =
15163       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15164                                (*MMOI)->getSize(),
15165                                (*MMOI)->getBaseAlignment(),
15166                                (*MMOI)->getTBAAInfo(),
15167                                (*MMOI)->getRanges());
15168     MIB.addMemOperand(MMO);
15169   }
15170
15171   thisMBB->addSuccessor(mainMBB);
15172
15173   // mainMBB:
15174   MachineBasicBlock *origMainMBB = mainMBB;
15175
15176   // Add a PHI.
15177   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15178                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15179
15180   unsigned Opc = MI->getOpcode();
15181   switch (Opc) {
15182   default:
15183     llvm_unreachable("Unhandled atomic-load-op opcode!");
15184   case X86::ATOMAND8:
15185   case X86::ATOMAND16:
15186   case X86::ATOMAND32:
15187   case X86::ATOMAND64:
15188   case X86::ATOMOR8:
15189   case X86::ATOMOR16:
15190   case X86::ATOMOR32:
15191   case X86::ATOMOR64:
15192   case X86::ATOMXOR8:
15193   case X86::ATOMXOR16:
15194   case X86::ATOMXOR32:
15195   case X86::ATOMXOR64: {
15196     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15197     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15198       .addReg(t4);
15199     break;
15200   }
15201   case X86::ATOMNAND8:
15202   case X86::ATOMNAND16:
15203   case X86::ATOMNAND32:
15204   case X86::ATOMNAND64: {
15205     unsigned Tmp = MRI.createVirtualRegister(RC);
15206     unsigned NOTOpc;
15207     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15208     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15209       .addReg(t4);
15210     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15211     break;
15212   }
15213   case X86::ATOMMAX8:
15214   case X86::ATOMMAX16:
15215   case X86::ATOMMAX32:
15216   case X86::ATOMMAX64:
15217   case X86::ATOMMIN8:
15218   case X86::ATOMMIN16:
15219   case X86::ATOMMIN32:
15220   case X86::ATOMMIN64:
15221   case X86::ATOMUMAX8:
15222   case X86::ATOMUMAX16:
15223   case X86::ATOMUMAX32:
15224   case X86::ATOMUMAX64:
15225   case X86::ATOMUMIN8:
15226   case X86::ATOMUMIN16:
15227   case X86::ATOMUMIN32:
15228   case X86::ATOMUMIN64: {
15229     unsigned CMPOpc;
15230     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15231
15232     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15233       .addReg(SrcReg)
15234       .addReg(t4);
15235
15236     if (Subtarget->hasCMov()) {
15237       if (VT != MVT::i8) {
15238         // Native support
15239         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15240           .addReg(SrcReg)
15241           .addReg(t4);
15242       } else {
15243         // Promote i8 to i32 to use CMOV32
15244         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15245         const TargetRegisterClass *RC32 =
15246           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15247         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15248         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15249         unsigned Tmp = MRI.createVirtualRegister(RC32);
15250
15251         unsigned Undef = MRI.createVirtualRegister(RC32);
15252         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15253
15254         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15255           .addReg(Undef)
15256           .addReg(SrcReg)
15257           .addImm(X86::sub_8bit);
15258         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15259           .addReg(Undef)
15260           .addReg(t4)
15261           .addImm(X86::sub_8bit);
15262
15263         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15264           .addReg(SrcReg32)
15265           .addReg(AccReg32);
15266
15267         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15268           .addReg(Tmp, 0, X86::sub_8bit);
15269       }
15270     } else {
15271       // Use pseudo select and lower them.
15272       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15273              "Invalid atomic-load-op transformation!");
15274       unsigned SelOpc = getPseudoCMOVOpc(VT);
15275       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15276       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15277       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15278               .addReg(SrcReg).addReg(t4)
15279               .addImm(CC);
15280       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15281       // Replace the original PHI node as mainMBB is changed after CMOV
15282       // lowering.
15283       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15284         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15285       Phi->eraseFromParent();
15286     }
15287     break;
15288   }
15289   }
15290
15291   // Copy PhyReg back from virtual register.
15292   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15293     .addReg(t4);
15294
15295   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15296   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15297     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15298     if (NewMO.isReg())
15299       NewMO.setIsKill(false);
15300     MIB.addOperand(NewMO);
15301   }
15302   MIB.addReg(t2);
15303   MIB.setMemRefs(MMOBegin, MMOEnd);
15304
15305   // Copy PhyReg back to virtual register.
15306   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15307     .addReg(PhyReg);
15308
15309   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15310
15311   mainMBB->addSuccessor(origMainMBB);
15312   mainMBB->addSuccessor(sinkMBB);
15313
15314   // sinkMBB:
15315   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15316           TII->get(TargetOpcode::COPY), DstReg)
15317     .addReg(t3);
15318
15319   MI->eraseFromParent();
15320   return sinkMBB;
15321 }
15322
15323 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15324 // instructions. They will be translated into a spin-loop or compare-exchange
15325 // loop from
15326 //
15327 //    ...
15328 //    dst = atomic-fetch-op MI.addr, MI.val
15329 //    ...
15330 //
15331 // to
15332 //
15333 //    ...
15334 //    t1L = LOAD [MI.addr + 0]
15335 //    t1H = LOAD [MI.addr + 4]
15336 // loop:
15337 //    t4L = phi(t1L, t3L / loop)
15338 //    t4H = phi(t1H, t3H / loop)
15339 //    t2L = OP MI.val.lo, t4L
15340 //    t2H = OP MI.val.hi, t4H
15341 //    EAX = t4L
15342 //    EDX = t4H
15343 //    EBX = t2L
15344 //    ECX = t2H
15345 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15346 //    t3L = EAX
15347 //    t3H = EDX
15348 //    JNE loop
15349 // sink:
15350 //    dstL = t3L
15351 //    dstH = t3H
15352 //    ...
15353 MachineBasicBlock *
15354 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15355                                            MachineBasicBlock *MBB) const {
15356   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15357   DebugLoc DL = MI->getDebugLoc();
15358
15359   MachineFunction *MF = MBB->getParent();
15360   MachineRegisterInfo &MRI = MF->getRegInfo();
15361
15362   const BasicBlock *BB = MBB->getBasicBlock();
15363   MachineFunction::iterator I = MBB;
15364   ++I;
15365
15366   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15367          "Unexpected number of operands");
15368
15369   assert(MI->hasOneMemOperand() &&
15370          "Expected atomic-load-op32 to have one memoperand");
15371
15372   // Memory Reference
15373   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15374   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15375
15376   unsigned DstLoReg, DstHiReg;
15377   unsigned SrcLoReg, SrcHiReg;
15378   unsigned MemOpndSlot;
15379
15380   unsigned CurOp = 0;
15381
15382   DstLoReg = MI->getOperand(CurOp++).getReg();
15383   DstHiReg = MI->getOperand(CurOp++).getReg();
15384   MemOpndSlot = CurOp;
15385   CurOp += X86::AddrNumOperands;
15386   SrcLoReg = MI->getOperand(CurOp++).getReg();
15387   SrcHiReg = MI->getOperand(CurOp++).getReg();
15388
15389   const TargetRegisterClass *RC = &X86::GR32RegClass;
15390   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15391
15392   unsigned t1L = MRI.createVirtualRegister(RC);
15393   unsigned t1H = MRI.createVirtualRegister(RC);
15394   unsigned t2L = MRI.createVirtualRegister(RC);
15395   unsigned t2H = MRI.createVirtualRegister(RC);
15396   unsigned t3L = MRI.createVirtualRegister(RC);
15397   unsigned t3H = MRI.createVirtualRegister(RC);
15398   unsigned t4L = MRI.createVirtualRegister(RC);
15399   unsigned t4H = MRI.createVirtualRegister(RC);
15400
15401   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15402   unsigned LOADOpc = X86::MOV32rm;
15403
15404   // For the atomic load-arith operator, we generate
15405   //
15406   //  thisMBB:
15407   //    t1L = LOAD [MI.addr + 0]
15408   //    t1H = LOAD [MI.addr + 4]
15409   //  mainMBB:
15410   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15411   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15412   //    t2L = OP MI.val.lo, t4L
15413   //    t2H = OP MI.val.hi, t4H
15414   //    EBX = t2L
15415   //    ECX = t2H
15416   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15417   //    t3L = EAX
15418   //    t3H = EDX
15419   //    JNE loop
15420   //  sinkMBB:
15421   //    dstL = t3L
15422   //    dstH = t3H
15423
15424   MachineBasicBlock *thisMBB = MBB;
15425   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15426   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15427   MF->insert(I, mainMBB);
15428   MF->insert(I, sinkMBB);
15429
15430   MachineInstrBuilder MIB;
15431
15432   // Transfer the remainder of BB and its successor edges to sinkMBB.
15433   sinkMBB->splice(sinkMBB->begin(), MBB,
15434                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15435   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15436
15437   // thisMBB:
15438   // Lo
15439   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15440   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15441     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15442     if (NewMO.isReg())
15443       NewMO.setIsKill(false);
15444     MIB.addOperand(NewMO);
15445   }
15446   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15447     unsigned flags = (*MMOI)->getFlags();
15448     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15449     MachineMemOperand *MMO =
15450       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15451                                (*MMOI)->getSize(),
15452                                (*MMOI)->getBaseAlignment(),
15453                                (*MMOI)->getTBAAInfo(),
15454                                (*MMOI)->getRanges());
15455     MIB.addMemOperand(MMO);
15456   };
15457   MachineInstr *LowMI = MIB;
15458
15459   // Hi
15460   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15461   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15462     if (i == X86::AddrDisp) {
15463       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15464     } else {
15465       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15466       if (NewMO.isReg())
15467         NewMO.setIsKill(false);
15468       MIB.addOperand(NewMO);
15469     }
15470   }
15471   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15472
15473   thisMBB->addSuccessor(mainMBB);
15474
15475   // mainMBB:
15476   MachineBasicBlock *origMainMBB = mainMBB;
15477
15478   // Add PHIs.
15479   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15480                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15481   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15482                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15483
15484   unsigned Opc = MI->getOpcode();
15485   switch (Opc) {
15486   default:
15487     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15488   case X86::ATOMAND6432:
15489   case X86::ATOMOR6432:
15490   case X86::ATOMXOR6432:
15491   case X86::ATOMADD6432:
15492   case X86::ATOMSUB6432: {
15493     unsigned HiOpc;
15494     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15495     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15496       .addReg(SrcLoReg);
15497     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15498       .addReg(SrcHiReg);
15499     break;
15500   }
15501   case X86::ATOMNAND6432: {
15502     unsigned HiOpc, NOTOpc;
15503     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15504     unsigned TmpL = MRI.createVirtualRegister(RC);
15505     unsigned TmpH = MRI.createVirtualRegister(RC);
15506     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15507       .addReg(t4L);
15508     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15509       .addReg(t4H);
15510     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15511     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15512     break;
15513   }
15514   case X86::ATOMMAX6432:
15515   case X86::ATOMMIN6432:
15516   case X86::ATOMUMAX6432:
15517   case X86::ATOMUMIN6432: {
15518     unsigned HiOpc;
15519     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15520     unsigned cL = MRI.createVirtualRegister(RC8);
15521     unsigned cH = MRI.createVirtualRegister(RC8);
15522     unsigned cL32 = MRI.createVirtualRegister(RC);
15523     unsigned cH32 = MRI.createVirtualRegister(RC);
15524     unsigned cc = MRI.createVirtualRegister(RC);
15525     // cl := cmp src_lo, lo
15526     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15527       .addReg(SrcLoReg).addReg(t4L);
15528     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15529     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15530     // ch := cmp src_hi, hi
15531     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15532       .addReg(SrcHiReg).addReg(t4H);
15533     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15534     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15535     // cc := if (src_hi == hi) ? cl : ch;
15536     if (Subtarget->hasCMov()) {
15537       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15538         .addReg(cH32).addReg(cL32);
15539     } else {
15540       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15541               .addReg(cH32).addReg(cL32)
15542               .addImm(X86::COND_E);
15543       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15544     }
15545     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15546     if (Subtarget->hasCMov()) {
15547       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15548         .addReg(SrcLoReg).addReg(t4L);
15549       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15550         .addReg(SrcHiReg).addReg(t4H);
15551     } else {
15552       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15553               .addReg(SrcLoReg).addReg(t4L)
15554               .addImm(X86::COND_NE);
15555       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15556       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15557       // 2nd CMOV lowering.
15558       mainMBB->addLiveIn(X86::EFLAGS);
15559       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15560               .addReg(SrcHiReg).addReg(t4H)
15561               .addImm(X86::COND_NE);
15562       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15563       // Replace the original PHI node as mainMBB is changed after CMOV
15564       // lowering.
15565       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15566         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15567       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15568         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15569       PhiL->eraseFromParent();
15570       PhiH->eraseFromParent();
15571     }
15572     break;
15573   }
15574   case X86::ATOMSWAP6432: {
15575     unsigned HiOpc;
15576     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15577     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15578     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15579     break;
15580   }
15581   }
15582
15583   // Copy EDX:EAX back from HiReg:LoReg
15584   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15585   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15586   // Copy ECX:EBX from t1H:t1L
15587   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15588   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15589
15590   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15591   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15592     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15593     if (NewMO.isReg())
15594       NewMO.setIsKill(false);
15595     MIB.addOperand(NewMO);
15596   }
15597   MIB.setMemRefs(MMOBegin, MMOEnd);
15598
15599   // Copy EDX:EAX back to t3H:t3L
15600   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15601   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15602
15603   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15604
15605   mainMBB->addSuccessor(origMainMBB);
15606   mainMBB->addSuccessor(sinkMBB);
15607
15608   // sinkMBB:
15609   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15610           TII->get(TargetOpcode::COPY), DstLoReg)
15611     .addReg(t3L);
15612   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15613           TII->get(TargetOpcode::COPY), DstHiReg)
15614     .addReg(t3H);
15615
15616   MI->eraseFromParent();
15617   return sinkMBB;
15618 }
15619
15620 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15621 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15622 // in the .td file.
15623 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15624                                        const TargetInstrInfo *TII) {
15625   unsigned Opc;
15626   switch (MI->getOpcode()) {
15627   default: llvm_unreachable("illegal opcode!");
15628   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15629   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15630   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15631   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15632   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15633   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15634   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15635   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15636   }
15637
15638   DebugLoc dl = MI->getDebugLoc();
15639   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15640
15641   unsigned NumArgs = MI->getNumOperands();
15642   for (unsigned i = 1; i < NumArgs; ++i) {
15643     MachineOperand &Op = MI->getOperand(i);
15644     if (!(Op.isReg() && Op.isImplicit()))
15645       MIB.addOperand(Op);
15646   }
15647   if (MI->hasOneMemOperand())
15648     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15649
15650   BuildMI(*BB, MI, dl,
15651     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15652     .addReg(X86::XMM0);
15653
15654   MI->eraseFromParent();
15655   return BB;
15656 }
15657
15658 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15659 // defs in an instruction pattern
15660 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15661                                        const TargetInstrInfo *TII) {
15662   unsigned Opc;
15663   switch (MI->getOpcode()) {
15664   default: llvm_unreachable("illegal opcode!");
15665   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15666   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15667   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15668   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15669   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15670   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15671   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15672   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15673   }
15674
15675   DebugLoc dl = MI->getDebugLoc();
15676   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15677
15678   unsigned NumArgs = MI->getNumOperands(); // remove the results
15679   for (unsigned i = 1; i < NumArgs; ++i) {
15680     MachineOperand &Op = MI->getOperand(i);
15681     if (!(Op.isReg() && Op.isImplicit()))
15682       MIB.addOperand(Op);
15683   }
15684   if (MI->hasOneMemOperand())
15685     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15686
15687   BuildMI(*BB, MI, dl,
15688     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15689     .addReg(X86::ECX);
15690
15691   MI->eraseFromParent();
15692   return BB;
15693 }
15694
15695 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15696                                        const TargetInstrInfo *TII,
15697                                        const X86Subtarget* Subtarget) {
15698   DebugLoc dl = MI->getDebugLoc();
15699
15700   // Address into RAX/EAX, other two args into ECX, EDX.
15701   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15702   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15703   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15704   for (int i = 0; i < X86::AddrNumOperands; ++i)
15705     MIB.addOperand(MI->getOperand(i));
15706
15707   unsigned ValOps = X86::AddrNumOperands;
15708   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15709     .addReg(MI->getOperand(ValOps).getReg());
15710   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15711     .addReg(MI->getOperand(ValOps+1).getReg());
15712
15713   // The instruction doesn't actually take any operands though.
15714   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15715
15716   MI->eraseFromParent(); // The pseudo is gone now.
15717   return BB;
15718 }
15719
15720 MachineBasicBlock *
15721 X86TargetLowering::EmitVAARG64WithCustomInserter(
15722                    MachineInstr *MI,
15723                    MachineBasicBlock *MBB) const {
15724   // Emit va_arg instruction on X86-64.
15725
15726   // Operands to this pseudo-instruction:
15727   // 0  ) Output        : destination address (reg)
15728   // 1-5) Input         : va_list address (addr, i64mem)
15729   // 6  ) ArgSize       : Size (in bytes) of vararg type
15730   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15731   // 8  ) Align         : Alignment of type
15732   // 9  ) EFLAGS (implicit-def)
15733
15734   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15735   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15736
15737   unsigned DestReg = MI->getOperand(0).getReg();
15738   MachineOperand &Base = MI->getOperand(1);
15739   MachineOperand &Scale = MI->getOperand(2);
15740   MachineOperand &Index = MI->getOperand(3);
15741   MachineOperand &Disp = MI->getOperand(4);
15742   MachineOperand &Segment = MI->getOperand(5);
15743   unsigned ArgSize = MI->getOperand(6).getImm();
15744   unsigned ArgMode = MI->getOperand(7).getImm();
15745   unsigned Align = MI->getOperand(8).getImm();
15746
15747   // Memory Reference
15748   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15749   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15750   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15751
15752   // Machine Information
15753   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15754   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15755   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15756   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15757   DebugLoc DL = MI->getDebugLoc();
15758
15759   // struct va_list {
15760   //   i32   gp_offset
15761   //   i32   fp_offset
15762   //   i64   overflow_area (address)
15763   //   i64   reg_save_area (address)
15764   // }
15765   // sizeof(va_list) = 24
15766   // alignment(va_list) = 8
15767
15768   unsigned TotalNumIntRegs = 6;
15769   unsigned TotalNumXMMRegs = 8;
15770   bool UseGPOffset = (ArgMode == 1);
15771   bool UseFPOffset = (ArgMode == 2);
15772   unsigned MaxOffset = TotalNumIntRegs * 8 +
15773                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15774
15775   /* Align ArgSize to a multiple of 8 */
15776   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15777   bool NeedsAlign = (Align > 8);
15778
15779   MachineBasicBlock *thisMBB = MBB;
15780   MachineBasicBlock *overflowMBB;
15781   MachineBasicBlock *offsetMBB;
15782   MachineBasicBlock *endMBB;
15783
15784   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15785   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15786   unsigned OffsetReg = 0;
15787
15788   if (!UseGPOffset && !UseFPOffset) {
15789     // If we only pull from the overflow region, we don't create a branch.
15790     // We don't need to alter control flow.
15791     OffsetDestReg = 0; // unused
15792     OverflowDestReg = DestReg;
15793
15794     offsetMBB = nullptr;
15795     overflowMBB = thisMBB;
15796     endMBB = thisMBB;
15797   } else {
15798     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15799     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15800     // If not, pull from overflow_area. (branch to overflowMBB)
15801     //
15802     //       thisMBB
15803     //         |     .
15804     //         |        .
15805     //     offsetMBB   overflowMBB
15806     //         |        .
15807     //         |     .
15808     //        endMBB
15809
15810     // Registers for the PHI in endMBB
15811     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15812     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15813
15814     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15815     MachineFunction *MF = MBB->getParent();
15816     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15817     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15818     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15819
15820     MachineFunction::iterator MBBIter = MBB;
15821     ++MBBIter;
15822
15823     // Insert the new basic blocks
15824     MF->insert(MBBIter, offsetMBB);
15825     MF->insert(MBBIter, overflowMBB);
15826     MF->insert(MBBIter, endMBB);
15827
15828     // Transfer the remainder of MBB and its successor edges to endMBB.
15829     endMBB->splice(endMBB->begin(), thisMBB,
15830                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15831     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15832
15833     // Make offsetMBB and overflowMBB successors of thisMBB
15834     thisMBB->addSuccessor(offsetMBB);
15835     thisMBB->addSuccessor(overflowMBB);
15836
15837     // endMBB is a successor of both offsetMBB and overflowMBB
15838     offsetMBB->addSuccessor(endMBB);
15839     overflowMBB->addSuccessor(endMBB);
15840
15841     // Load the offset value into a register
15842     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15843     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15844       .addOperand(Base)
15845       .addOperand(Scale)
15846       .addOperand(Index)
15847       .addDisp(Disp, UseFPOffset ? 4 : 0)
15848       .addOperand(Segment)
15849       .setMemRefs(MMOBegin, MMOEnd);
15850
15851     // Check if there is enough room left to pull this argument.
15852     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15853       .addReg(OffsetReg)
15854       .addImm(MaxOffset + 8 - ArgSizeA8);
15855
15856     // Branch to "overflowMBB" if offset >= max
15857     // Fall through to "offsetMBB" otherwise
15858     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15859       .addMBB(overflowMBB);
15860   }
15861
15862   // In offsetMBB, emit code to use the reg_save_area.
15863   if (offsetMBB) {
15864     assert(OffsetReg != 0);
15865
15866     // Read the reg_save_area address.
15867     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15868     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15869       .addOperand(Base)
15870       .addOperand(Scale)
15871       .addOperand(Index)
15872       .addDisp(Disp, 16)
15873       .addOperand(Segment)
15874       .setMemRefs(MMOBegin, MMOEnd);
15875
15876     // Zero-extend the offset
15877     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15878       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15879         .addImm(0)
15880         .addReg(OffsetReg)
15881         .addImm(X86::sub_32bit);
15882
15883     // Add the offset to the reg_save_area to get the final address.
15884     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15885       .addReg(OffsetReg64)
15886       .addReg(RegSaveReg);
15887
15888     // Compute the offset for the next argument
15889     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15890     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15891       .addReg(OffsetReg)
15892       .addImm(UseFPOffset ? 16 : 8);
15893
15894     // Store it back into the va_list.
15895     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15896       .addOperand(Base)
15897       .addOperand(Scale)
15898       .addOperand(Index)
15899       .addDisp(Disp, UseFPOffset ? 4 : 0)
15900       .addOperand(Segment)
15901       .addReg(NextOffsetReg)
15902       .setMemRefs(MMOBegin, MMOEnd);
15903
15904     // Jump to endMBB
15905     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15906       .addMBB(endMBB);
15907   }
15908
15909   //
15910   // Emit code to use overflow area
15911   //
15912
15913   // Load the overflow_area address into a register.
15914   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15915   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15916     .addOperand(Base)
15917     .addOperand(Scale)
15918     .addOperand(Index)
15919     .addDisp(Disp, 8)
15920     .addOperand(Segment)
15921     .setMemRefs(MMOBegin, MMOEnd);
15922
15923   // If we need to align it, do so. Otherwise, just copy the address
15924   // to OverflowDestReg.
15925   if (NeedsAlign) {
15926     // Align the overflow address
15927     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15928     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15929
15930     // aligned_addr = (addr + (align-1)) & ~(align-1)
15931     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15932       .addReg(OverflowAddrReg)
15933       .addImm(Align-1);
15934
15935     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15936       .addReg(TmpReg)
15937       .addImm(~(uint64_t)(Align-1));
15938   } else {
15939     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15940       .addReg(OverflowAddrReg);
15941   }
15942
15943   // Compute the next overflow address after this argument.
15944   // (the overflow address should be kept 8-byte aligned)
15945   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15946   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15947     .addReg(OverflowDestReg)
15948     .addImm(ArgSizeA8);
15949
15950   // Store the new overflow address.
15951   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15952     .addOperand(Base)
15953     .addOperand(Scale)
15954     .addOperand(Index)
15955     .addDisp(Disp, 8)
15956     .addOperand(Segment)
15957     .addReg(NextAddrReg)
15958     .setMemRefs(MMOBegin, MMOEnd);
15959
15960   // If we branched, emit the PHI to the front of endMBB.
15961   if (offsetMBB) {
15962     BuildMI(*endMBB, endMBB->begin(), DL,
15963             TII->get(X86::PHI), DestReg)
15964       .addReg(OffsetDestReg).addMBB(offsetMBB)
15965       .addReg(OverflowDestReg).addMBB(overflowMBB);
15966   }
15967
15968   // Erase the pseudo instruction
15969   MI->eraseFromParent();
15970
15971   return endMBB;
15972 }
15973
15974 MachineBasicBlock *
15975 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15976                                                  MachineInstr *MI,
15977                                                  MachineBasicBlock *MBB) const {
15978   // Emit code to save XMM registers to the stack. The ABI says that the
15979   // number of registers to save is given in %al, so it's theoretically
15980   // possible to do an indirect jump trick to avoid saving all of them,
15981   // however this code takes a simpler approach and just executes all
15982   // of the stores if %al is non-zero. It's less code, and it's probably
15983   // easier on the hardware branch predictor, and stores aren't all that
15984   // expensive anyway.
15985
15986   // Create the new basic blocks. One block contains all the XMM stores,
15987   // and one block is the final destination regardless of whether any
15988   // stores were performed.
15989   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15990   MachineFunction *F = MBB->getParent();
15991   MachineFunction::iterator MBBIter = MBB;
15992   ++MBBIter;
15993   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15994   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15995   F->insert(MBBIter, XMMSaveMBB);
15996   F->insert(MBBIter, EndMBB);
15997
15998   // Transfer the remainder of MBB and its successor edges to EndMBB.
15999   EndMBB->splice(EndMBB->begin(), MBB,
16000                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16001   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16002
16003   // The original block will now fall through to the XMM save block.
16004   MBB->addSuccessor(XMMSaveMBB);
16005   // The XMMSaveMBB will fall through to the end block.
16006   XMMSaveMBB->addSuccessor(EndMBB);
16007
16008   // Now add the instructions.
16009   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16010   DebugLoc DL = MI->getDebugLoc();
16011
16012   unsigned CountReg = MI->getOperand(0).getReg();
16013   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16014   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16015
16016   if (!Subtarget->isTargetWin64()) {
16017     // If %al is 0, branch around the XMM save block.
16018     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16019     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16020     MBB->addSuccessor(EndMBB);
16021   }
16022
16023   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16024   // that was just emitted, but clearly shouldn't be "saved".
16025   assert((MI->getNumOperands() <= 3 ||
16026           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16027           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16028          && "Expected last argument to be EFLAGS");
16029   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16030   // In the XMM save block, save all the XMM argument registers.
16031   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16032     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16033     MachineMemOperand *MMO =
16034       F->getMachineMemOperand(
16035           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16036         MachineMemOperand::MOStore,
16037         /*Size=*/16, /*Align=*/16);
16038     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16039       .addFrameIndex(RegSaveFrameIndex)
16040       .addImm(/*Scale=*/1)
16041       .addReg(/*IndexReg=*/0)
16042       .addImm(/*Disp=*/Offset)
16043       .addReg(/*Segment=*/0)
16044       .addReg(MI->getOperand(i).getReg())
16045       .addMemOperand(MMO);
16046   }
16047
16048   MI->eraseFromParent();   // The pseudo instruction is gone now.
16049
16050   return EndMBB;
16051 }
16052
16053 // The EFLAGS operand of SelectItr might be missing a kill marker
16054 // because there were multiple uses of EFLAGS, and ISel didn't know
16055 // which to mark. Figure out whether SelectItr should have had a
16056 // kill marker, and set it if it should. Returns the correct kill
16057 // marker value.
16058 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16059                                      MachineBasicBlock* BB,
16060                                      const TargetRegisterInfo* TRI) {
16061   // Scan forward through BB for a use/def of EFLAGS.
16062   MachineBasicBlock::iterator miI(std::next(SelectItr));
16063   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16064     const MachineInstr& mi = *miI;
16065     if (mi.readsRegister(X86::EFLAGS))
16066       return false;
16067     if (mi.definesRegister(X86::EFLAGS))
16068       break; // Should have kill-flag - update below.
16069   }
16070
16071   // If we hit the end of the block, check whether EFLAGS is live into a
16072   // successor.
16073   if (miI == BB->end()) {
16074     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16075                                           sEnd = BB->succ_end();
16076          sItr != sEnd; ++sItr) {
16077       MachineBasicBlock* succ = *sItr;
16078       if (succ->isLiveIn(X86::EFLAGS))
16079         return false;
16080     }
16081   }
16082
16083   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16084   // out. SelectMI should have a kill flag on EFLAGS.
16085   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16086   return true;
16087 }
16088
16089 MachineBasicBlock *
16090 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16091                                      MachineBasicBlock *BB) const {
16092   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16093   DebugLoc DL = MI->getDebugLoc();
16094
16095   // To "insert" a SELECT_CC instruction, we actually have to insert the
16096   // diamond control-flow pattern.  The incoming instruction knows the
16097   // destination vreg to set, the condition code register to branch on, the
16098   // true/false values to select between, and a branch opcode to use.
16099   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16100   MachineFunction::iterator It = BB;
16101   ++It;
16102
16103   //  thisMBB:
16104   //  ...
16105   //   TrueVal = ...
16106   //   cmpTY ccX, r1, r2
16107   //   bCC copy1MBB
16108   //   fallthrough --> copy0MBB
16109   MachineBasicBlock *thisMBB = BB;
16110   MachineFunction *F = BB->getParent();
16111   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16112   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16113   F->insert(It, copy0MBB);
16114   F->insert(It, sinkMBB);
16115
16116   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16117   // live into the sink and copy blocks.
16118   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16119   if (!MI->killsRegister(X86::EFLAGS) &&
16120       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16121     copy0MBB->addLiveIn(X86::EFLAGS);
16122     sinkMBB->addLiveIn(X86::EFLAGS);
16123   }
16124
16125   // Transfer the remainder of BB and its successor edges to sinkMBB.
16126   sinkMBB->splice(sinkMBB->begin(), BB,
16127                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16128   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16129
16130   // Add the true and fallthrough blocks as its successors.
16131   BB->addSuccessor(copy0MBB);
16132   BB->addSuccessor(sinkMBB);
16133
16134   // Create the conditional branch instruction.
16135   unsigned Opc =
16136     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16137   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16138
16139   //  copy0MBB:
16140   //   %FalseValue = ...
16141   //   # fallthrough to sinkMBB
16142   copy0MBB->addSuccessor(sinkMBB);
16143
16144   //  sinkMBB:
16145   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16146   //  ...
16147   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16148           TII->get(X86::PHI), MI->getOperand(0).getReg())
16149     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16150     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16151
16152   MI->eraseFromParent();   // The pseudo instruction is gone now.
16153   return sinkMBB;
16154 }
16155
16156 MachineBasicBlock *
16157 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16158                                         bool Is64Bit) const {
16159   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16160   DebugLoc DL = MI->getDebugLoc();
16161   MachineFunction *MF = BB->getParent();
16162   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16163
16164   assert(MF->shouldSplitStack());
16165
16166   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16167   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16168
16169   // BB:
16170   //  ... [Till the alloca]
16171   // If stacklet is not large enough, jump to mallocMBB
16172   //
16173   // bumpMBB:
16174   //  Allocate by subtracting from RSP
16175   //  Jump to continueMBB
16176   //
16177   // mallocMBB:
16178   //  Allocate by call to runtime
16179   //
16180   // continueMBB:
16181   //  ...
16182   //  [rest of original BB]
16183   //
16184
16185   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16186   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16187   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16188
16189   MachineRegisterInfo &MRI = MF->getRegInfo();
16190   const TargetRegisterClass *AddrRegClass =
16191     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16192
16193   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16194     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16195     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16196     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16197     sizeVReg = MI->getOperand(1).getReg(),
16198     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16199
16200   MachineFunction::iterator MBBIter = BB;
16201   ++MBBIter;
16202
16203   MF->insert(MBBIter, bumpMBB);
16204   MF->insert(MBBIter, mallocMBB);
16205   MF->insert(MBBIter, continueMBB);
16206
16207   continueMBB->splice(continueMBB->begin(), BB,
16208                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16209   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16210
16211   // Add code to the main basic block to check if the stack limit has been hit,
16212   // and if so, jump to mallocMBB otherwise to bumpMBB.
16213   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16214   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16215     .addReg(tmpSPVReg).addReg(sizeVReg);
16216   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16217     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16218     .addReg(SPLimitVReg);
16219   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16220
16221   // bumpMBB simply decreases the stack pointer, since we know the current
16222   // stacklet has enough space.
16223   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16224     .addReg(SPLimitVReg);
16225   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16226     .addReg(SPLimitVReg);
16227   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16228
16229   // Calls into a routine in libgcc to allocate more space from the heap.
16230   const uint32_t *RegMask =
16231     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16232   if (Is64Bit) {
16233     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16234       .addReg(sizeVReg);
16235     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16236       .addExternalSymbol("__morestack_allocate_stack_space")
16237       .addRegMask(RegMask)
16238       .addReg(X86::RDI, RegState::Implicit)
16239       .addReg(X86::RAX, RegState::ImplicitDefine);
16240   } else {
16241     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16242       .addImm(12);
16243     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16244     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16245       .addExternalSymbol("__morestack_allocate_stack_space")
16246       .addRegMask(RegMask)
16247       .addReg(X86::EAX, RegState::ImplicitDefine);
16248   }
16249
16250   if (!Is64Bit)
16251     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16252       .addImm(16);
16253
16254   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16255     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16256   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16257
16258   // Set up the CFG correctly.
16259   BB->addSuccessor(bumpMBB);
16260   BB->addSuccessor(mallocMBB);
16261   mallocMBB->addSuccessor(continueMBB);
16262   bumpMBB->addSuccessor(continueMBB);
16263
16264   // Take care of the PHI nodes.
16265   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16266           MI->getOperand(0).getReg())
16267     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16268     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16269
16270   // Delete the original pseudo instruction.
16271   MI->eraseFromParent();
16272
16273   // And we're done.
16274   return continueMBB;
16275 }
16276
16277 MachineBasicBlock *
16278 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16279                                           MachineBasicBlock *BB) const {
16280   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16281   DebugLoc DL = MI->getDebugLoc();
16282
16283   assert(!Subtarget->isTargetMacho());
16284
16285   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16286   // non-trivial part is impdef of ESP.
16287
16288   if (Subtarget->isTargetWin64()) {
16289     if (Subtarget->isTargetCygMing()) {
16290       // ___chkstk(Mingw64):
16291       // Clobbers R10, R11, RAX and EFLAGS.
16292       // Updates RSP.
16293       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16294         .addExternalSymbol("___chkstk")
16295         .addReg(X86::RAX, RegState::Implicit)
16296         .addReg(X86::RSP, RegState::Implicit)
16297         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16298         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16299         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16300     } else {
16301       // __chkstk(MSVCRT): does not update stack pointer.
16302       // Clobbers R10, R11 and EFLAGS.
16303       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16304         .addExternalSymbol("__chkstk")
16305         .addReg(X86::RAX, RegState::Implicit)
16306         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16307       // RAX has the offset to be subtracted from RSP.
16308       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16309         .addReg(X86::RSP)
16310         .addReg(X86::RAX);
16311     }
16312   } else {
16313     const char *StackProbeSymbol =
16314       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16315
16316     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16317       .addExternalSymbol(StackProbeSymbol)
16318       .addReg(X86::EAX, RegState::Implicit)
16319       .addReg(X86::ESP, RegState::Implicit)
16320       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16321       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16322       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16323   }
16324
16325   MI->eraseFromParent();   // The pseudo instruction is gone now.
16326   return BB;
16327 }
16328
16329 MachineBasicBlock *
16330 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16331                                       MachineBasicBlock *BB) const {
16332   // This is pretty easy.  We're taking the value that we received from
16333   // our load from the relocation, sticking it in either RDI (x86-64)
16334   // or EAX and doing an indirect call.  The return value will then
16335   // be in the normal return register.
16336   const X86InstrInfo *TII
16337     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16338   DebugLoc DL = MI->getDebugLoc();
16339   MachineFunction *F = BB->getParent();
16340
16341   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16342   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16343
16344   // Get a register mask for the lowered call.
16345   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16346   // proper register mask.
16347   const uint32_t *RegMask =
16348     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16349   if (Subtarget->is64Bit()) {
16350     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16351                                       TII->get(X86::MOV64rm), X86::RDI)
16352     .addReg(X86::RIP)
16353     .addImm(0).addReg(0)
16354     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16355                       MI->getOperand(3).getTargetFlags())
16356     .addReg(0);
16357     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16358     addDirectMem(MIB, X86::RDI);
16359     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16360   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16361     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16362                                       TII->get(X86::MOV32rm), X86::EAX)
16363     .addReg(0)
16364     .addImm(0).addReg(0)
16365     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16366                       MI->getOperand(3).getTargetFlags())
16367     .addReg(0);
16368     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16369     addDirectMem(MIB, X86::EAX);
16370     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16371   } else {
16372     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16373                                       TII->get(X86::MOV32rm), X86::EAX)
16374     .addReg(TII->getGlobalBaseReg(F))
16375     .addImm(0).addReg(0)
16376     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16377                       MI->getOperand(3).getTargetFlags())
16378     .addReg(0);
16379     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16380     addDirectMem(MIB, X86::EAX);
16381     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16382   }
16383
16384   MI->eraseFromParent(); // The pseudo instruction is gone now.
16385   return BB;
16386 }
16387
16388 MachineBasicBlock *
16389 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16390                                     MachineBasicBlock *MBB) const {
16391   DebugLoc DL = MI->getDebugLoc();
16392   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16393
16394   MachineFunction *MF = MBB->getParent();
16395   MachineRegisterInfo &MRI = MF->getRegInfo();
16396
16397   const BasicBlock *BB = MBB->getBasicBlock();
16398   MachineFunction::iterator I = MBB;
16399   ++I;
16400
16401   // Memory Reference
16402   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16403   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16404
16405   unsigned DstReg;
16406   unsigned MemOpndSlot = 0;
16407
16408   unsigned CurOp = 0;
16409
16410   DstReg = MI->getOperand(CurOp++).getReg();
16411   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16412   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16413   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16414   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16415
16416   MemOpndSlot = CurOp;
16417
16418   MVT PVT = getPointerTy();
16419   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16420          "Invalid Pointer Size!");
16421
16422   // For v = setjmp(buf), we generate
16423   //
16424   // thisMBB:
16425   //  buf[LabelOffset] = restoreMBB
16426   //  SjLjSetup restoreMBB
16427   //
16428   // mainMBB:
16429   //  v_main = 0
16430   //
16431   // sinkMBB:
16432   //  v = phi(main, restore)
16433   //
16434   // restoreMBB:
16435   //  v_restore = 1
16436
16437   MachineBasicBlock *thisMBB = MBB;
16438   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16439   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16440   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16441   MF->insert(I, mainMBB);
16442   MF->insert(I, sinkMBB);
16443   MF->push_back(restoreMBB);
16444
16445   MachineInstrBuilder MIB;
16446
16447   // Transfer the remainder of BB and its successor edges to sinkMBB.
16448   sinkMBB->splice(sinkMBB->begin(), MBB,
16449                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16450   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16451
16452   // thisMBB:
16453   unsigned PtrStoreOpc = 0;
16454   unsigned LabelReg = 0;
16455   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16456   Reloc::Model RM = getTargetMachine().getRelocationModel();
16457   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16458                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16459
16460   // Prepare IP either in reg or imm.
16461   if (!UseImmLabel) {
16462     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16463     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16464     LabelReg = MRI.createVirtualRegister(PtrRC);
16465     if (Subtarget->is64Bit()) {
16466       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16467               .addReg(X86::RIP)
16468               .addImm(0)
16469               .addReg(0)
16470               .addMBB(restoreMBB)
16471               .addReg(0);
16472     } else {
16473       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16474       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16475               .addReg(XII->getGlobalBaseReg(MF))
16476               .addImm(0)
16477               .addReg(0)
16478               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16479               .addReg(0);
16480     }
16481   } else
16482     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16483   // Store IP
16484   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16485   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16486     if (i == X86::AddrDisp)
16487       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16488     else
16489       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16490   }
16491   if (!UseImmLabel)
16492     MIB.addReg(LabelReg);
16493   else
16494     MIB.addMBB(restoreMBB);
16495   MIB.setMemRefs(MMOBegin, MMOEnd);
16496   // Setup
16497   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16498           .addMBB(restoreMBB);
16499
16500   const X86RegisterInfo *RegInfo =
16501     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16502   MIB.addRegMask(RegInfo->getNoPreservedMask());
16503   thisMBB->addSuccessor(mainMBB);
16504   thisMBB->addSuccessor(restoreMBB);
16505
16506   // mainMBB:
16507   //  EAX = 0
16508   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16509   mainMBB->addSuccessor(sinkMBB);
16510
16511   // sinkMBB:
16512   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16513           TII->get(X86::PHI), DstReg)
16514     .addReg(mainDstReg).addMBB(mainMBB)
16515     .addReg(restoreDstReg).addMBB(restoreMBB);
16516
16517   // restoreMBB:
16518   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16519   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16520   restoreMBB->addSuccessor(sinkMBB);
16521
16522   MI->eraseFromParent();
16523   return sinkMBB;
16524 }
16525
16526 MachineBasicBlock *
16527 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16528                                      MachineBasicBlock *MBB) const {
16529   DebugLoc DL = MI->getDebugLoc();
16530   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16531
16532   MachineFunction *MF = MBB->getParent();
16533   MachineRegisterInfo &MRI = MF->getRegInfo();
16534
16535   // Memory Reference
16536   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16537   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16538
16539   MVT PVT = getPointerTy();
16540   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16541          "Invalid Pointer Size!");
16542
16543   const TargetRegisterClass *RC =
16544     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16545   unsigned Tmp = MRI.createVirtualRegister(RC);
16546   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16547   const X86RegisterInfo *RegInfo =
16548     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16549   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16550   unsigned SP = RegInfo->getStackRegister();
16551
16552   MachineInstrBuilder MIB;
16553
16554   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16555   const int64_t SPOffset = 2 * PVT.getStoreSize();
16556
16557   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16558   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16559
16560   // Reload FP
16561   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16562   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16563     MIB.addOperand(MI->getOperand(i));
16564   MIB.setMemRefs(MMOBegin, MMOEnd);
16565   // Reload IP
16566   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16567   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16568     if (i == X86::AddrDisp)
16569       MIB.addDisp(MI->getOperand(i), LabelOffset);
16570     else
16571       MIB.addOperand(MI->getOperand(i));
16572   }
16573   MIB.setMemRefs(MMOBegin, MMOEnd);
16574   // Reload SP
16575   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16576   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16577     if (i == X86::AddrDisp)
16578       MIB.addDisp(MI->getOperand(i), SPOffset);
16579     else
16580       MIB.addOperand(MI->getOperand(i));
16581   }
16582   MIB.setMemRefs(MMOBegin, MMOEnd);
16583   // Jump
16584   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16585
16586   MI->eraseFromParent();
16587   return MBB;
16588 }
16589
16590 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16591 // accumulator loops. Writing back to the accumulator allows the coalescer
16592 // to remove extra copies in the loop.   
16593 MachineBasicBlock *
16594 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16595                                  MachineBasicBlock *MBB) const {
16596   MachineOperand &AddendOp = MI->getOperand(3);
16597
16598   // Bail out early if the addend isn't a register - we can't switch these.
16599   if (!AddendOp.isReg())
16600     return MBB;
16601
16602   MachineFunction &MF = *MBB->getParent();
16603   MachineRegisterInfo &MRI = MF.getRegInfo();
16604
16605   // Check whether the addend is defined by a PHI:
16606   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16607   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16608   if (!AddendDef.isPHI())
16609     return MBB;
16610
16611   // Look for the following pattern:
16612   // loop:
16613   //   %addend = phi [%entry, 0], [%loop, %result]
16614   //   ...
16615   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16616
16617   // Replace with:
16618   //   loop:
16619   //   %addend = phi [%entry, 0], [%loop, %result]
16620   //   ...
16621   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16622
16623   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16624     assert(AddendDef.getOperand(i).isReg());
16625     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16626     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16627     if (&PHISrcInst == MI) {
16628       // Found a matching instruction.
16629       unsigned NewFMAOpc = 0;
16630       switch (MI->getOpcode()) {
16631         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16632         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16633         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16634         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16635         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16636         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16637         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16638         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16639         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16640         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16641         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16642         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16643         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16644         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16645         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16646         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16647         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16648         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16649         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16650         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16651         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16652         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16653         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16654         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16655         default: llvm_unreachable("Unrecognized FMA variant.");
16656       }
16657
16658       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16659       MachineInstrBuilder MIB =
16660         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16661         .addOperand(MI->getOperand(0))
16662         .addOperand(MI->getOperand(3))
16663         .addOperand(MI->getOperand(2))
16664         .addOperand(MI->getOperand(1));
16665       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16666       MI->eraseFromParent();
16667     }
16668   }
16669
16670   return MBB;
16671 }
16672
16673 MachineBasicBlock *
16674 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16675                                                MachineBasicBlock *BB) const {
16676   switch (MI->getOpcode()) {
16677   default: llvm_unreachable("Unexpected instr type to insert");
16678   case X86::TAILJMPd64:
16679   case X86::TAILJMPr64:
16680   case X86::TAILJMPm64:
16681     llvm_unreachable("TAILJMP64 would not be touched here.");
16682   case X86::TCRETURNdi64:
16683   case X86::TCRETURNri64:
16684   case X86::TCRETURNmi64:
16685     return BB;
16686   case X86::WIN_ALLOCA:
16687     return EmitLoweredWinAlloca(MI, BB);
16688   case X86::SEG_ALLOCA_32:
16689     return EmitLoweredSegAlloca(MI, BB, false);
16690   case X86::SEG_ALLOCA_64:
16691     return EmitLoweredSegAlloca(MI, BB, true);
16692   case X86::TLSCall_32:
16693   case X86::TLSCall_64:
16694     return EmitLoweredTLSCall(MI, BB);
16695   case X86::CMOV_GR8:
16696   case X86::CMOV_FR32:
16697   case X86::CMOV_FR64:
16698   case X86::CMOV_V4F32:
16699   case X86::CMOV_V2F64:
16700   case X86::CMOV_V2I64:
16701   case X86::CMOV_V8F32:
16702   case X86::CMOV_V4F64:
16703   case X86::CMOV_V4I64:
16704   case X86::CMOV_V16F32:
16705   case X86::CMOV_V8F64:
16706   case X86::CMOV_V8I64:
16707   case X86::CMOV_GR16:
16708   case X86::CMOV_GR32:
16709   case X86::CMOV_RFP32:
16710   case X86::CMOV_RFP64:
16711   case X86::CMOV_RFP80:
16712     return EmitLoweredSelect(MI, BB);
16713
16714   case X86::FP32_TO_INT16_IN_MEM:
16715   case X86::FP32_TO_INT32_IN_MEM:
16716   case X86::FP32_TO_INT64_IN_MEM:
16717   case X86::FP64_TO_INT16_IN_MEM:
16718   case X86::FP64_TO_INT32_IN_MEM:
16719   case X86::FP64_TO_INT64_IN_MEM:
16720   case X86::FP80_TO_INT16_IN_MEM:
16721   case X86::FP80_TO_INT32_IN_MEM:
16722   case X86::FP80_TO_INT64_IN_MEM: {
16723     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16724     DebugLoc DL = MI->getDebugLoc();
16725
16726     // Change the floating point control register to use "round towards zero"
16727     // mode when truncating to an integer value.
16728     MachineFunction *F = BB->getParent();
16729     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16730     addFrameReference(BuildMI(*BB, MI, DL,
16731                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16732
16733     // Load the old value of the high byte of the control word...
16734     unsigned OldCW =
16735       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16736     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16737                       CWFrameIdx);
16738
16739     // Set the high part to be round to zero...
16740     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16741       .addImm(0xC7F);
16742
16743     // Reload the modified control word now...
16744     addFrameReference(BuildMI(*BB, MI, DL,
16745                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16746
16747     // Restore the memory image of control word to original value
16748     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16749       .addReg(OldCW);
16750
16751     // Get the X86 opcode to use.
16752     unsigned Opc;
16753     switch (MI->getOpcode()) {
16754     default: llvm_unreachable("illegal opcode!");
16755     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16756     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16757     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16758     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16759     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16760     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16761     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16762     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16763     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16764     }
16765
16766     X86AddressMode AM;
16767     MachineOperand &Op = MI->getOperand(0);
16768     if (Op.isReg()) {
16769       AM.BaseType = X86AddressMode::RegBase;
16770       AM.Base.Reg = Op.getReg();
16771     } else {
16772       AM.BaseType = X86AddressMode::FrameIndexBase;
16773       AM.Base.FrameIndex = Op.getIndex();
16774     }
16775     Op = MI->getOperand(1);
16776     if (Op.isImm())
16777       AM.Scale = Op.getImm();
16778     Op = MI->getOperand(2);
16779     if (Op.isImm())
16780       AM.IndexReg = Op.getImm();
16781     Op = MI->getOperand(3);
16782     if (Op.isGlobal()) {
16783       AM.GV = Op.getGlobal();
16784     } else {
16785       AM.Disp = Op.getImm();
16786     }
16787     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16788                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16789
16790     // Reload the original control word now.
16791     addFrameReference(BuildMI(*BB, MI, DL,
16792                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16793
16794     MI->eraseFromParent();   // The pseudo instruction is gone now.
16795     return BB;
16796   }
16797     // String/text processing lowering.
16798   case X86::PCMPISTRM128REG:
16799   case X86::VPCMPISTRM128REG:
16800   case X86::PCMPISTRM128MEM:
16801   case X86::VPCMPISTRM128MEM:
16802   case X86::PCMPESTRM128REG:
16803   case X86::VPCMPESTRM128REG:
16804   case X86::PCMPESTRM128MEM:
16805   case X86::VPCMPESTRM128MEM:
16806     assert(Subtarget->hasSSE42() &&
16807            "Target must have SSE4.2 or AVX features enabled");
16808     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16809
16810   // String/text processing lowering.
16811   case X86::PCMPISTRIREG:
16812   case X86::VPCMPISTRIREG:
16813   case X86::PCMPISTRIMEM:
16814   case X86::VPCMPISTRIMEM:
16815   case X86::PCMPESTRIREG:
16816   case X86::VPCMPESTRIREG:
16817   case X86::PCMPESTRIMEM:
16818   case X86::VPCMPESTRIMEM:
16819     assert(Subtarget->hasSSE42() &&
16820            "Target must have SSE4.2 or AVX features enabled");
16821     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16822
16823   // Thread synchronization.
16824   case X86::MONITOR:
16825     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16826
16827   // xbegin
16828   case X86::XBEGIN:
16829     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16830
16831   // Atomic Lowering.
16832   case X86::ATOMAND8:
16833   case X86::ATOMAND16:
16834   case X86::ATOMAND32:
16835   case X86::ATOMAND64:
16836     // Fall through
16837   case X86::ATOMOR8:
16838   case X86::ATOMOR16:
16839   case X86::ATOMOR32:
16840   case X86::ATOMOR64:
16841     // Fall through
16842   case X86::ATOMXOR16:
16843   case X86::ATOMXOR8:
16844   case X86::ATOMXOR32:
16845   case X86::ATOMXOR64:
16846     // Fall through
16847   case X86::ATOMNAND8:
16848   case X86::ATOMNAND16:
16849   case X86::ATOMNAND32:
16850   case X86::ATOMNAND64:
16851     // Fall through
16852   case X86::ATOMMAX8:
16853   case X86::ATOMMAX16:
16854   case X86::ATOMMAX32:
16855   case X86::ATOMMAX64:
16856     // Fall through
16857   case X86::ATOMMIN8:
16858   case X86::ATOMMIN16:
16859   case X86::ATOMMIN32:
16860   case X86::ATOMMIN64:
16861     // Fall through
16862   case X86::ATOMUMAX8:
16863   case X86::ATOMUMAX16:
16864   case X86::ATOMUMAX32:
16865   case X86::ATOMUMAX64:
16866     // Fall through
16867   case X86::ATOMUMIN8:
16868   case X86::ATOMUMIN16:
16869   case X86::ATOMUMIN32:
16870   case X86::ATOMUMIN64:
16871     return EmitAtomicLoadArith(MI, BB);
16872
16873   // This group does 64-bit operations on a 32-bit host.
16874   case X86::ATOMAND6432:
16875   case X86::ATOMOR6432:
16876   case X86::ATOMXOR6432:
16877   case X86::ATOMNAND6432:
16878   case X86::ATOMADD6432:
16879   case X86::ATOMSUB6432:
16880   case X86::ATOMMAX6432:
16881   case X86::ATOMMIN6432:
16882   case X86::ATOMUMAX6432:
16883   case X86::ATOMUMIN6432:
16884   case X86::ATOMSWAP6432:
16885     return EmitAtomicLoadArith6432(MI, BB);
16886
16887   case X86::VASTART_SAVE_XMM_REGS:
16888     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16889
16890   case X86::VAARG_64:
16891     return EmitVAARG64WithCustomInserter(MI, BB);
16892
16893   case X86::EH_SjLj_SetJmp32:
16894   case X86::EH_SjLj_SetJmp64:
16895     return emitEHSjLjSetJmp(MI, BB);
16896
16897   case X86::EH_SjLj_LongJmp32:
16898   case X86::EH_SjLj_LongJmp64:
16899     return emitEHSjLjLongJmp(MI, BB);
16900
16901   case TargetOpcode::STACKMAP:
16902   case TargetOpcode::PATCHPOINT:
16903     return emitPatchPoint(MI, BB);
16904
16905   case X86::VFMADDPDr213r:
16906   case X86::VFMADDPSr213r:
16907   case X86::VFMADDSDr213r:
16908   case X86::VFMADDSSr213r:
16909   case X86::VFMSUBPDr213r:
16910   case X86::VFMSUBPSr213r:
16911   case X86::VFMSUBSDr213r:
16912   case X86::VFMSUBSSr213r:
16913   case X86::VFNMADDPDr213r:
16914   case X86::VFNMADDPSr213r:
16915   case X86::VFNMADDSDr213r:
16916   case X86::VFNMADDSSr213r:
16917   case X86::VFNMSUBPDr213r:
16918   case X86::VFNMSUBPSr213r:
16919   case X86::VFNMSUBSDr213r:
16920   case X86::VFNMSUBSSr213r:
16921   case X86::VFMADDPDr213rY:
16922   case X86::VFMADDPSr213rY:
16923   case X86::VFMSUBPDr213rY:
16924   case X86::VFMSUBPSr213rY:
16925   case X86::VFNMADDPDr213rY:
16926   case X86::VFNMADDPSr213rY:
16927   case X86::VFNMSUBPDr213rY:
16928   case X86::VFNMSUBPSr213rY:
16929     return emitFMA3Instr(MI, BB);
16930   }
16931 }
16932
16933 //===----------------------------------------------------------------------===//
16934 //                           X86 Optimization Hooks
16935 //===----------------------------------------------------------------------===//
16936
16937 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16938                                                        APInt &KnownZero,
16939                                                        APInt &KnownOne,
16940                                                        const SelectionDAG &DAG,
16941                                                        unsigned Depth) const {
16942   unsigned BitWidth = KnownZero.getBitWidth();
16943   unsigned Opc = Op.getOpcode();
16944   assert((Opc >= ISD::BUILTIN_OP_END ||
16945           Opc == ISD::INTRINSIC_WO_CHAIN ||
16946           Opc == ISD::INTRINSIC_W_CHAIN ||
16947           Opc == ISD::INTRINSIC_VOID) &&
16948          "Should use MaskedValueIsZero if you don't know whether Op"
16949          " is a target node!");
16950
16951   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16952   switch (Opc) {
16953   default: break;
16954   case X86ISD::ADD:
16955   case X86ISD::SUB:
16956   case X86ISD::ADC:
16957   case X86ISD::SBB:
16958   case X86ISD::SMUL:
16959   case X86ISD::UMUL:
16960   case X86ISD::INC:
16961   case X86ISD::DEC:
16962   case X86ISD::OR:
16963   case X86ISD::XOR:
16964   case X86ISD::AND:
16965     // These nodes' second result is a boolean.
16966     if (Op.getResNo() == 0)
16967       break;
16968     // Fallthrough
16969   case X86ISD::SETCC:
16970     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16971     break;
16972   case ISD::INTRINSIC_WO_CHAIN: {
16973     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16974     unsigned NumLoBits = 0;
16975     switch (IntId) {
16976     default: break;
16977     case Intrinsic::x86_sse_movmsk_ps:
16978     case Intrinsic::x86_avx_movmsk_ps_256:
16979     case Intrinsic::x86_sse2_movmsk_pd:
16980     case Intrinsic::x86_avx_movmsk_pd_256:
16981     case Intrinsic::x86_mmx_pmovmskb:
16982     case Intrinsic::x86_sse2_pmovmskb_128:
16983     case Intrinsic::x86_avx2_pmovmskb: {
16984       // High bits of movmskp{s|d}, pmovmskb are known zero.
16985       switch (IntId) {
16986         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16987         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16988         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16989         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16990         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16991         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16992         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16993         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16994       }
16995       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16996       break;
16997     }
16998     }
16999     break;
17000   }
17001   }
17002 }
17003
17004 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17005   SDValue Op,
17006   const SelectionDAG &,
17007   unsigned Depth) const {
17008   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17009   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17010     return Op.getValueType().getScalarType().getSizeInBits();
17011
17012   // Fallback case.
17013   return 1;
17014 }
17015
17016 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17017 /// node is a GlobalAddress + offset.
17018 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17019                                        const GlobalValue* &GA,
17020                                        int64_t &Offset) const {
17021   if (N->getOpcode() == X86ISD::Wrapper) {
17022     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17023       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17024       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17025       return true;
17026     }
17027   }
17028   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17029 }
17030
17031 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17032 /// same as extracting the high 128-bit part of 256-bit vector and then
17033 /// inserting the result into the low part of a new 256-bit vector
17034 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17035   EVT VT = SVOp->getValueType(0);
17036   unsigned NumElems = VT.getVectorNumElements();
17037
17038   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17039   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17040     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17041         SVOp->getMaskElt(j) >= 0)
17042       return false;
17043
17044   return true;
17045 }
17046
17047 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17048 /// same as extracting the low 128-bit part of 256-bit vector and then
17049 /// inserting the result into the high part of a new 256-bit vector
17050 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17051   EVT VT = SVOp->getValueType(0);
17052   unsigned NumElems = VT.getVectorNumElements();
17053
17054   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17055   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17056     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17057         SVOp->getMaskElt(j) >= 0)
17058       return false;
17059
17060   return true;
17061 }
17062
17063 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17064 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17065                                         TargetLowering::DAGCombinerInfo &DCI,
17066                                         const X86Subtarget* Subtarget) {
17067   SDLoc dl(N);
17068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17069   SDValue V1 = SVOp->getOperand(0);
17070   SDValue V2 = SVOp->getOperand(1);
17071   EVT VT = SVOp->getValueType(0);
17072   unsigned NumElems = VT.getVectorNumElements();
17073
17074   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17075       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17076     //
17077     //                   0,0,0,...
17078     //                      |
17079     //    V      UNDEF    BUILD_VECTOR    UNDEF
17080     //     \      /           \           /
17081     //  CONCAT_VECTOR         CONCAT_VECTOR
17082     //         \                  /
17083     //          \                /
17084     //          RESULT: V + zero extended
17085     //
17086     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17087         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17088         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17089       return SDValue();
17090
17091     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17092       return SDValue();
17093
17094     // To match the shuffle mask, the first half of the mask should
17095     // be exactly the first vector, and all the rest a splat with the
17096     // first element of the second one.
17097     for (unsigned i = 0; i != NumElems/2; ++i)
17098       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17099           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17100         return SDValue();
17101
17102     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17103     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17104       if (Ld->hasNUsesOfValue(1, 0)) {
17105         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17106         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17107         SDValue ResNode =
17108           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17109                                   array_lengthof(Ops),
17110                                   Ld->getMemoryVT(),
17111                                   Ld->getPointerInfo(),
17112                                   Ld->getAlignment(),
17113                                   false/*isVolatile*/, true/*ReadMem*/,
17114                                   false/*WriteMem*/);
17115
17116         // Make sure the newly-created LOAD is in the same position as Ld in
17117         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17118         // and update uses of Ld's output chain to use the TokenFactor.
17119         if (Ld->hasAnyUseOfValue(1)) {
17120           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17121                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17122           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17123           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17124                                  SDValue(ResNode.getNode(), 1));
17125         }
17126
17127         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17128       }
17129     }
17130
17131     // Emit a zeroed vector and insert the desired subvector on its
17132     // first half.
17133     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17134     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17135     return DCI.CombineTo(N, InsV);
17136   }
17137
17138   //===--------------------------------------------------------------------===//
17139   // Combine some shuffles into subvector extracts and inserts:
17140   //
17141
17142   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17143   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17144     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17145     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17146     return DCI.CombineTo(N, InsV);
17147   }
17148
17149   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17150   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17151     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17152     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17153     return DCI.CombineTo(N, InsV);
17154   }
17155
17156   return SDValue();
17157 }
17158
17159 /// PerformShuffleCombine - Performs several different shuffle combines.
17160 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17161                                      TargetLowering::DAGCombinerInfo &DCI,
17162                                      const X86Subtarget *Subtarget) {
17163   SDLoc dl(N);
17164   EVT VT = N->getValueType(0);
17165
17166   // Don't create instructions with illegal types after legalize types has run.
17167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17168   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17169     return SDValue();
17170
17171   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17172   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17173       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17174     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17175
17176   // Only handle 128 wide vector from here on.
17177   if (!VT.is128BitVector())
17178     return SDValue();
17179
17180   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17181   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17182   // consecutive, non-overlapping, and in the right order.
17183   SmallVector<SDValue, 16> Elts;
17184   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17185     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17186
17187   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17188 }
17189
17190 /// PerformTruncateCombine - Converts truncate operation to
17191 /// a sequence of vector shuffle operations.
17192 /// It is possible when we truncate 256-bit vector to 128-bit vector
17193 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17194                                       TargetLowering::DAGCombinerInfo &DCI,
17195                                       const X86Subtarget *Subtarget)  {
17196   return SDValue();
17197 }
17198
17199 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17200 /// specific shuffle of a load can be folded into a single element load.
17201 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17202 /// shuffles have been customed lowered so we need to handle those here.
17203 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17204                                          TargetLowering::DAGCombinerInfo &DCI) {
17205   if (DCI.isBeforeLegalizeOps())
17206     return SDValue();
17207
17208   SDValue InVec = N->getOperand(0);
17209   SDValue EltNo = N->getOperand(1);
17210
17211   if (!isa<ConstantSDNode>(EltNo))
17212     return SDValue();
17213
17214   EVT VT = InVec.getValueType();
17215
17216   bool HasShuffleIntoBitcast = false;
17217   if (InVec.getOpcode() == ISD::BITCAST) {
17218     // Don't duplicate a load with other uses.
17219     if (!InVec.hasOneUse())
17220       return SDValue();
17221     EVT BCVT = InVec.getOperand(0).getValueType();
17222     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17223       return SDValue();
17224     InVec = InVec.getOperand(0);
17225     HasShuffleIntoBitcast = true;
17226   }
17227
17228   if (!isTargetShuffle(InVec.getOpcode()))
17229     return SDValue();
17230
17231   // Don't duplicate a load with other uses.
17232   if (!InVec.hasOneUse())
17233     return SDValue();
17234
17235   SmallVector<int, 16> ShuffleMask;
17236   bool UnaryShuffle;
17237   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17238                             UnaryShuffle))
17239     return SDValue();
17240
17241   // Select the input vector, guarding against out of range extract vector.
17242   unsigned NumElems = VT.getVectorNumElements();
17243   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17244   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17245   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17246                                          : InVec.getOperand(1);
17247
17248   // If inputs to shuffle are the same for both ops, then allow 2 uses
17249   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17250
17251   if (LdNode.getOpcode() == ISD::BITCAST) {
17252     // Don't duplicate a load with other uses.
17253     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17254       return SDValue();
17255
17256     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17257     LdNode = LdNode.getOperand(0);
17258   }
17259
17260   if (!ISD::isNormalLoad(LdNode.getNode()))
17261     return SDValue();
17262
17263   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17264
17265   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17266     return SDValue();
17267
17268   if (HasShuffleIntoBitcast) {
17269     // If there's a bitcast before the shuffle, check if the load type and
17270     // alignment is valid.
17271     unsigned Align = LN0->getAlignment();
17272     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17273     unsigned NewAlign = TLI.getDataLayout()->
17274       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17275
17276     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17277       return SDValue();
17278   }
17279
17280   // All checks match so transform back to vector_shuffle so that DAG combiner
17281   // can finish the job
17282   SDLoc dl(N);
17283
17284   // Create shuffle node taking into account the case that its a unary shuffle
17285   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17286   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17287                                  InVec.getOperand(0), Shuffle,
17288                                  &ShuffleMask[0]);
17289   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17290   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17291                      EltNo);
17292 }
17293
17294 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17295 /// generation and convert it from being a bunch of shuffles and extracts
17296 /// to a simple store and scalar loads to extract the elements.
17297 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17298                                          TargetLowering::DAGCombinerInfo &DCI) {
17299   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17300   if (NewOp.getNode())
17301     return NewOp;
17302
17303   SDValue InputVector = N->getOperand(0);
17304
17305   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17306   // from mmx to v2i32 has a single usage.
17307   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17308       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17309       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17310     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17311                        N->getValueType(0),
17312                        InputVector.getNode()->getOperand(0));
17313
17314   // Only operate on vectors of 4 elements, where the alternative shuffling
17315   // gets to be more expensive.
17316   if (InputVector.getValueType() != MVT::v4i32)
17317     return SDValue();
17318
17319   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17320   // single use which is a sign-extend or zero-extend, and all elements are
17321   // used.
17322   SmallVector<SDNode *, 4> Uses;
17323   unsigned ExtractedElements = 0;
17324   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17325        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17326     if (UI.getUse().getResNo() != InputVector.getResNo())
17327       return SDValue();
17328
17329     SDNode *Extract = *UI;
17330     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17331       return SDValue();
17332
17333     if (Extract->getValueType(0) != MVT::i32)
17334       return SDValue();
17335     if (!Extract->hasOneUse())
17336       return SDValue();
17337     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17338         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17339       return SDValue();
17340     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17341       return SDValue();
17342
17343     // Record which element was extracted.
17344     ExtractedElements |=
17345       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17346
17347     Uses.push_back(Extract);
17348   }
17349
17350   // If not all the elements were used, this may not be worthwhile.
17351   if (ExtractedElements != 15)
17352     return SDValue();
17353
17354   // Ok, we've now decided to do the transformation.
17355   SDLoc dl(InputVector);
17356
17357   // Store the value to a temporary stack slot.
17358   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17359   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17360                             MachinePointerInfo(), false, false, 0);
17361
17362   // Replace each use (extract) with a load of the appropriate element.
17363   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17364        UE = Uses.end(); UI != UE; ++UI) {
17365     SDNode *Extract = *UI;
17366
17367     // cOMpute the element's address.
17368     SDValue Idx = Extract->getOperand(1);
17369     unsigned EltSize =
17370         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17371     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17372     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17373     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17374
17375     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17376                                      StackPtr, OffsetVal);
17377
17378     // Load the scalar.
17379     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17380                                      ScalarAddr, MachinePointerInfo(),
17381                                      false, false, false, 0);
17382
17383     // Replace the exact with the load.
17384     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17385   }
17386
17387   // The replacement was made in place; don't return anything.
17388   return SDValue();
17389 }
17390
17391 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17392 static std::pair<unsigned, bool>
17393 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17394                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17395   if (!VT.isVector())
17396     return std::make_pair(0, false);
17397
17398   bool NeedSplit = false;
17399   switch (VT.getSimpleVT().SimpleTy) {
17400   default: return std::make_pair(0, false);
17401   case MVT::v32i8:
17402   case MVT::v16i16:
17403   case MVT::v8i32:
17404     if (!Subtarget->hasAVX2())
17405       NeedSplit = true;
17406     if (!Subtarget->hasAVX())
17407       return std::make_pair(0, false);
17408     break;
17409   case MVT::v16i8:
17410   case MVT::v8i16:
17411   case MVT::v4i32:
17412     if (!Subtarget->hasSSE2())
17413       return std::make_pair(0, false);
17414   }
17415
17416   // SSE2 has only a small subset of the operations.
17417   bool hasUnsigned = Subtarget->hasSSE41() ||
17418                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17419   bool hasSigned = Subtarget->hasSSE41() ||
17420                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17421
17422   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17423
17424   unsigned Opc = 0;
17425   // Check for x CC y ? x : y.
17426   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17427       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17428     switch (CC) {
17429     default: break;
17430     case ISD::SETULT:
17431     case ISD::SETULE:
17432       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17433     case ISD::SETUGT:
17434     case ISD::SETUGE:
17435       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17436     case ISD::SETLT:
17437     case ISD::SETLE:
17438       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17439     case ISD::SETGT:
17440     case ISD::SETGE:
17441       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17442     }
17443   // Check for x CC y ? y : x -- a min/max with reversed arms.
17444   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17445              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17446     switch (CC) {
17447     default: break;
17448     case ISD::SETULT:
17449     case ISD::SETULE:
17450       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17451     case ISD::SETUGT:
17452     case ISD::SETUGE:
17453       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17454     case ISD::SETLT:
17455     case ISD::SETLE:
17456       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17457     case ISD::SETGT:
17458     case ISD::SETGE:
17459       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17460     }
17461   }
17462
17463   return std::make_pair(Opc, NeedSplit);
17464 }
17465
17466 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17467 /// nodes.
17468 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17469                                     TargetLowering::DAGCombinerInfo &DCI,
17470                                     const X86Subtarget *Subtarget) {
17471   SDLoc DL(N);
17472   SDValue Cond = N->getOperand(0);
17473   // Get the LHS/RHS of the select.
17474   SDValue LHS = N->getOperand(1);
17475   SDValue RHS = N->getOperand(2);
17476   EVT VT = LHS.getValueType();
17477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17478
17479   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17480   // instructions match the semantics of the common C idiom x<y?x:y but not
17481   // x<=y?x:y, because of how they handle negative zero (which can be
17482   // ignored in unsafe-math mode).
17483   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17484       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17485       (Subtarget->hasSSE2() ||
17486        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17487     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17488
17489     unsigned Opcode = 0;
17490     // Check for x CC y ? x : y.
17491     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17492         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17493       switch (CC) {
17494       default: break;
17495       case ISD::SETULT:
17496         // Converting this to a min would handle NaNs incorrectly, and swapping
17497         // the operands would cause it to handle comparisons between positive
17498         // and negative zero incorrectly.
17499         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17500           if (!DAG.getTarget().Options.UnsafeFPMath &&
17501               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17502             break;
17503           std::swap(LHS, RHS);
17504         }
17505         Opcode = X86ISD::FMIN;
17506         break;
17507       case ISD::SETOLE:
17508         // Converting this to a min would handle comparisons between positive
17509         // and negative zero incorrectly.
17510         if (!DAG.getTarget().Options.UnsafeFPMath &&
17511             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17512           break;
17513         Opcode = X86ISD::FMIN;
17514         break;
17515       case ISD::SETULE:
17516         // Converting this to a min would handle both negative zeros and NaNs
17517         // incorrectly, but we can swap the operands to fix both.
17518         std::swap(LHS, RHS);
17519       case ISD::SETOLT:
17520       case ISD::SETLT:
17521       case ISD::SETLE:
17522         Opcode = X86ISD::FMIN;
17523         break;
17524
17525       case ISD::SETOGE:
17526         // Converting this to a max would handle comparisons between positive
17527         // and negative zero incorrectly.
17528         if (!DAG.getTarget().Options.UnsafeFPMath &&
17529             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17530           break;
17531         Opcode = X86ISD::FMAX;
17532         break;
17533       case ISD::SETUGT:
17534         // Converting this to a max would handle NaNs incorrectly, and swapping
17535         // the operands would cause it to handle comparisons between positive
17536         // and negative zero incorrectly.
17537         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17538           if (!DAG.getTarget().Options.UnsafeFPMath &&
17539               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17540             break;
17541           std::swap(LHS, RHS);
17542         }
17543         Opcode = X86ISD::FMAX;
17544         break;
17545       case ISD::SETUGE:
17546         // Converting this to a max would handle both negative zeros and NaNs
17547         // incorrectly, but we can swap the operands to fix both.
17548         std::swap(LHS, RHS);
17549       case ISD::SETOGT:
17550       case ISD::SETGT:
17551       case ISD::SETGE:
17552         Opcode = X86ISD::FMAX;
17553         break;
17554       }
17555     // Check for x CC y ? y : x -- a min/max with reversed arms.
17556     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17557                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17558       switch (CC) {
17559       default: break;
17560       case ISD::SETOGE:
17561         // Converting this to a min would handle comparisons between positive
17562         // and negative zero incorrectly, and swapping the operands would
17563         // cause it to handle NaNs incorrectly.
17564         if (!DAG.getTarget().Options.UnsafeFPMath &&
17565             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17566           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17567             break;
17568           std::swap(LHS, RHS);
17569         }
17570         Opcode = X86ISD::FMIN;
17571         break;
17572       case ISD::SETUGT:
17573         // Converting this to a min would handle NaNs incorrectly.
17574         if (!DAG.getTarget().Options.UnsafeFPMath &&
17575             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17576           break;
17577         Opcode = X86ISD::FMIN;
17578         break;
17579       case ISD::SETUGE:
17580         // Converting this to a min would handle both negative zeros and NaNs
17581         // incorrectly, but we can swap the operands to fix both.
17582         std::swap(LHS, RHS);
17583       case ISD::SETOGT:
17584       case ISD::SETGT:
17585       case ISD::SETGE:
17586         Opcode = X86ISD::FMIN;
17587         break;
17588
17589       case ISD::SETULT:
17590         // Converting this to a max would handle NaNs incorrectly.
17591         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17592           break;
17593         Opcode = X86ISD::FMAX;
17594         break;
17595       case ISD::SETOLE:
17596         // Converting this to a max would handle comparisons between positive
17597         // and negative zero incorrectly, and swapping the operands would
17598         // cause it to handle NaNs incorrectly.
17599         if (!DAG.getTarget().Options.UnsafeFPMath &&
17600             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17601           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17602             break;
17603           std::swap(LHS, RHS);
17604         }
17605         Opcode = X86ISD::FMAX;
17606         break;
17607       case ISD::SETULE:
17608         // Converting this to a max would handle both negative zeros and NaNs
17609         // incorrectly, but we can swap the operands to fix both.
17610         std::swap(LHS, RHS);
17611       case ISD::SETOLT:
17612       case ISD::SETLT:
17613       case ISD::SETLE:
17614         Opcode = X86ISD::FMAX;
17615         break;
17616       }
17617     }
17618
17619     if (Opcode)
17620       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17621   }
17622
17623   EVT CondVT = Cond.getValueType();
17624   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17625       CondVT.getVectorElementType() == MVT::i1) {
17626     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17627     // lowering on AVX-512. In this case we convert it to
17628     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17629     // The same situation for all 128 and 256-bit vectors of i8 and i16
17630     EVT OpVT = LHS.getValueType();
17631     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17632         (OpVT.getVectorElementType() == MVT::i8 ||
17633          OpVT.getVectorElementType() == MVT::i16)) {
17634       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17635       DCI.AddToWorklist(Cond.getNode());
17636       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17637     }
17638   }
17639   // If this is a select between two integer constants, try to do some
17640   // optimizations.
17641   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17642     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17643       // Don't do this for crazy integer types.
17644       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17645         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17646         // so that TrueC (the true value) is larger than FalseC.
17647         bool NeedsCondInvert = false;
17648
17649         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17650             // Efficiently invertible.
17651             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17652              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17653               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17654           NeedsCondInvert = true;
17655           std::swap(TrueC, FalseC);
17656         }
17657
17658         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17659         if (FalseC->getAPIntValue() == 0 &&
17660             TrueC->getAPIntValue().isPowerOf2()) {
17661           if (NeedsCondInvert) // Invert the condition if needed.
17662             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17663                                DAG.getConstant(1, Cond.getValueType()));
17664
17665           // Zero extend the condition if needed.
17666           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17667
17668           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17669           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17670                              DAG.getConstant(ShAmt, MVT::i8));
17671         }
17672
17673         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17674         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17675           if (NeedsCondInvert) // Invert the condition if needed.
17676             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17677                                DAG.getConstant(1, Cond.getValueType()));
17678
17679           // Zero extend the condition if needed.
17680           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17681                              FalseC->getValueType(0), Cond);
17682           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17683                              SDValue(FalseC, 0));
17684         }
17685
17686         // Optimize cases that will turn into an LEA instruction.  This requires
17687         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17688         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17689           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17690           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17691
17692           bool isFastMultiplier = false;
17693           if (Diff < 10) {
17694             switch ((unsigned char)Diff) {
17695               default: break;
17696               case 1:  // result = add base, cond
17697               case 2:  // result = lea base(    , cond*2)
17698               case 3:  // result = lea base(cond, cond*2)
17699               case 4:  // result = lea base(    , cond*4)
17700               case 5:  // result = lea base(cond, cond*4)
17701               case 8:  // result = lea base(    , cond*8)
17702               case 9:  // result = lea base(cond, cond*8)
17703                 isFastMultiplier = true;
17704                 break;
17705             }
17706           }
17707
17708           if (isFastMultiplier) {
17709             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17710             if (NeedsCondInvert) // Invert the condition if needed.
17711               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17712                                  DAG.getConstant(1, Cond.getValueType()));
17713
17714             // Zero extend the condition if needed.
17715             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17716                                Cond);
17717             // Scale the condition by the difference.
17718             if (Diff != 1)
17719               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17720                                  DAG.getConstant(Diff, Cond.getValueType()));
17721
17722             // Add the base if non-zero.
17723             if (FalseC->getAPIntValue() != 0)
17724               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17725                                  SDValue(FalseC, 0));
17726             return Cond;
17727           }
17728         }
17729       }
17730   }
17731
17732   // Canonicalize max and min:
17733   // (x > y) ? x : y -> (x >= y) ? x : y
17734   // (x < y) ? x : y -> (x <= y) ? x : y
17735   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17736   // the need for an extra compare
17737   // against zero. e.g.
17738   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17739   // subl   %esi, %edi
17740   // testl  %edi, %edi
17741   // movl   $0, %eax
17742   // cmovgl %edi, %eax
17743   // =>
17744   // xorl   %eax, %eax
17745   // subl   %esi, $edi
17746   // cmovsl %eax, %edi
17747   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17748       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17749       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17750     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17751     switch (CC) {
17752     default: break;
17753     case ISD::SETLT:
17754     case ISD::SETGT: {
17755       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17756       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17757                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17758       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17759     }
17760     }
17761   }
17762
17763   // Early exit check
17764   if (!TLI.isTypeLegal(VT))
17765     return SDValue();
17766
17767   // Match VSELECTs into subs with unsigned saturation.
17768   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17769       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17770       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17771        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17772     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17773
17774     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17775     // left side invert the predicate to simplify logic below.
17776     SDValue Other;
17777     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17778       Other = RHS;
17779       CC = ISD::getSetCCInverse(CC, true);
17780     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17781       Other = LHS;
17782     }
17783
17784     if (Other.getNode() && Other->getNumOperands() == 2 &&
17785         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17786       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17787       SDValue CondRHS = Cond->getOperand(1);
17788
17789       // Look for a general sub with unsigned saturation first.
17790       // x >= y ? x-y : 0 --> subus x, y
17791       // x >  y ? x-y : 0 --> subus x, y
17792       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17793           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17794         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17795
17796       // If the RHS is a constant we have to reverse the const canonicalization.
17797       // x > C-1 ? x+-C : 0 --> subus x, C
17798       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17799           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17800         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17801         if (CondRHS.getConstantOperandVal(0) == -A-1)
17802           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17803                              DAG.getConstant(-A, VT));
17804       }
17805
17806       // Another special case: If C was a sign bit, the sub has been
17807       // canonicalized into a xor.
17808       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17809       //        it's safe to decanonicalize the xor?
17810       // x s< 0 ? x^C : 0 --> subus x, C
17811       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17812           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17813           isSplatVector(OpRHS.getNode())) {
17814         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17815         if (A.isSignBit())
17816           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17817       }
17818     }
17819   }
17820
17821   // Try to match a min/max vector operation.
17822   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17823     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17824     unsigned Opc = ret.first;
17825     bool NeedSplit = ret.second;
17826
17827     if (Opc && NeedSplit) {
17828       unsigned NumElems = VT.getVectorNumElements();
17829       // Extract the LHS vectors
17830       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17831       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17832
17833       // Extract the RHS vectors
17834       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17835       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17836
17837       // Create min/max for each subvector
17838       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17839       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17840
17841       // Merge the result
17842       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17843     } else if (Opc)
17844       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17845   }
17846
17847   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17848   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17849       // Check if SETCC has already been promoted
17850       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17851       // Check that condition value type matches vselect operand type
17852       CondVT == VT) { 
17853
17854     assert(Cond.getValueType().isVector() &&
17855            "vector select expects a vector selector!");
17856
17857     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17858     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17859
17860     if (!TValIsAllOnes && !FValIsAllZeros) {
17861       // Try invert the condition if true value is not all 1s and false value
17862       // is not all 0s.
17863       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17864       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17865
17866       if (TValIsAllZeros || FValIsAllOnes) {
17867         SDValue CC = Cond.getOperand(2);
17868         ISD::CondCode NewCC =
17869           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17870                                Cond.getOperand(0).getValueType().isInteger());
17871         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17872         std::swap(LHS, RHS);
17873         TValIsAllOnes = FValIsAllOnes;
17874         FValIsAllZeros = TValIsAllZeros;
17875       }
17876     }
17877
17878     if (TValIsAllOnes || FValIsAllZeros) {
17879       SDValue Ret;
17880
17881       if (TValIsAllOnes && FValIsAllZeros)
17882         Ret = Cond;
17883       else if (TValIsAllOnes)
17884         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17885                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17886       else if (FValIsAllZeros)
17887         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17888                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17889
17890       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17891     }
17892   }
17893
17894   // Try to fold this VSELECT into a MOVSS/MOVSD
17895   if (N->getOpcode() == ISD::VSELECT &&
17896       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17897     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17898         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17899       bool CanFold = false;
17900       unsigned NumElems = Cond.getNumOperands();
17901       SDValue A = LHS;
17902       SDValue B = RHS;
17903       
17904       if (isZero(Cond.getOperand(0))) {
17905         CanFold = true;
17906
17907         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17908         // fold (vselect <0,-1> -> (movsd A, B)
17909         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17910           CanFold = isAllOnes(Cond.getOperand(i));
17911       } else if (isAllOnes(Cond.getOperand(0))) {
17912         CanFold = true;
17913         std::swap(A, B);
17914
17915         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17916         // fold (vselect <-1,0> -> (movsd B, A)
17917         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17918           CanFold = isZero(Cond.getOperand(i));
17919       }
17920
17921       if (CanFold) {
17922         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17923           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17924         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17925       }
17926
17927       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17928         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17929         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17930         //                             (v2i64 (bitcast B)))))
17931         //
17932         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17933         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17934         //                             (v2f64 (bitcast B)))))
17935         //
17936         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17937         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17938         //                             (v2i64 (bitcast A)))))
17939         //
17940         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17941         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17942         //                             (v2f64 (bitcast A)))))
17943
17944         CanFold = (isZero(Cond.getOperand(0)) &&
17945                    isZero(Cond.getOperand(1)) &&
17946                    isAllOnes(Cond.getOperand(2)) &&
17947                    isAllOnes(Cond.getOperand(3)));
17948
17949         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17950             isAllOnes(Cond.getOperand(1)) &&
17951             isZero(Cond.getOperand(2)) &&
17952             isZero(Cond.getOperand(3))) {
17953           CanFold = true;
17954           std::swap(LHS, RHS);
17955         }
17956
17957         if (CanFold) {
17958           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17959           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17960           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17961           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17962                                                 NewB, DAG);
17963           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17964         }
17965       }
17966     }
17967   }
17968
17969   // If we know that this node is legal then we know that it is going to be
17970   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17971   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17972   // to simplify previous instructions.
17973   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17974       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17975     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17976
17977     // Don't optimize vector selects that map to mask-registers.
17978     if (BitWidth == 1)
17979       return SDValue();
17980
17981     // Check all uses of that condition operand to check whether it will be
17982     // consumed by non-BLEND instructions, which may depend on all bits are set
17983     // properly.
17984     for (SDNode::use_iterator I = Cond->use_begin(),
17985                               E = Cond->use_end(); I != E; ++I)
17986       if (I->getOpcode() != ISD::VSELECT)
17987         // TODO: Add other opcodes eventually lowered into BLEND.
17988         return SDValue();
17989
17990     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17991     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17992
17993     APInt KnownZero, KnownOne;
17994     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17995                                           DCI.isBeforeLegalizeOps());
17996     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17997         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17998       DCI.CommitTargetLoweringOpt(TLO);
17999   }
18000
18001   return SDValue();
18002 }
18003
18004 // Check whether a boolean test is testing a boolean value generated by
18005 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18006 // code.
18007 //
18008 // Simplify the following patterns:
18009 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18010 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18011 // to (Op EFLAGS Cond)
18012 //
18013 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18014 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18015 // to (Op EFLAGS !Cond)
18016 //
18017 // where Op could be BRCOND or CMOV.
18018 //
18019 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18020   // Quit if not CMP and SUB with its value result used.
18021   if (Cmp.getOpcode() != X86ISD::CMP &&
18022       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18023       return SDValue();
18024
18025   // Quit if not used as a boolean value.
18026   if (CC != X86::COND_E && CC != X86::COND_NE)
18027     return SDValue();
18028
18029   // Check CMP operands. One of them should be 0 or 1 and the other should be
18030   // an SetCC or extended from it.
18031   SDValue Op1 = Cmp.getOperand(0);
18032   SDValue Op2 = Cmp.getOperand(1);
18033
18034   SDValue SetCC;
18035   const ConstantSDNode* C = nullptr;
18036   bool needOppositeCond = (CC == X86::COND_E);
18037   bool checkAgainstTrue = false; // Is it a comparison against 1?
18038
18039   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18040     SetCC = Op2;
18041   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18042     SetCC = Op1;
18043   else // Quit if all operands are not constants.
18044     return SDValue();
18045
18046   if (C->getZExtValue() == 1) {
18047     needOppositeCond = !needOppositeCond;
18048     checkAgainstTrue = true;
18049   } else if (C->getZExtValue() != 0)
18050     // Quit if the constant is neither 0 or 1.
18051     return SDValue();
18052
18053   bool truncatedToBoolWithAnd = false;
18054   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18055   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18056          SetCC.getOpcode() == ISD::TRUNCATE ||
18057          SetCC.getOpcode() == ISD::AND) {
18058     if (SetCC.getOpcode() == ISD::AND) {
18059       int OpIdx = -1;
18060       ConstantSDNode *CS;
18061       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18062           CS->getZExtValue() == 1)
18063         OpIdx = 1;
18064       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18065           CS->getZExtValue() == 1)
18066         OpIdx = 0;
18067       if (OpIdx == -1)
18068         break;
18069       SetCC = SetCC.getOperand(OpIdx);
18070       truncatedToBoolWithAnd = true;
18071     } else
18072       SetCC = SetCC.getOperand(0);
18073   }
18074
18075   switch (SetCC.getOpcode()) {
18076   case X86ISD::SETCC_CARRY:
18077     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18078     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18079     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18080     // truncated to i1 using 'and'.
18081     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18082       break;
18083     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18084            "Invalid use of SETCC_CARRY!");
18085     // FALL THROUGH
18086   case X86ISD::SETCC:
18087     // Set the condition code or opposite one if necessary.
18088     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18089     if (needOppositeCond)
18090       CC = X86::GetOppositeBranchCondition(CC);
18091     return SetCC.getOperand(1);
18092   case X86ISD::CMOV: {
18093     // Check whether false/true value has canonical one, i.e. 0 or 1.
18094     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18095     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18096     // Quit if true value is not a constant.
18097     if (!TVal)
18098       return SDValue();
18099     // Quit if false value is not a constant.
18100     if (!FVal) {
18101       SDValue Op = SetCC.getOperand(0);
18102       // Skip 'zext' or 'trunc' node.
18103       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18104           Op.getOpcode() == ISD::TRUNCATE)
18105         Op = Op.getOperand(0);
18106       // A special case for rdrand/rdseed, where 0 is set if false cond is
18107       // found.
18108       if ((Op.getOpcode() != X86ISD::RDRAND &&
18109            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18110         return SDValue();
18111     }
18112     // Quit if false value is not the constant 0 or 1.
18113     bool FValIsFalse = true;
18114     if (FVal && FVal->getZExtValue() != 0) {
18115       if (FVal->getZExtValue() != 1)
18116         return SDValue();
18117       // If FVal is 1, opposite cond is needed.
18118       needOppositeCond = !needOppositeCond;
18119       FValIsFalse = false;
18120     }
18121     // Quit if TVal is not the constant opposite of FVal.
18122     if (FValIsFalse && TVal->getZExtValue() != 1)
18123       return SDValue();
18124     if (!FValIsFalse && TVal->getZExtValue() != 0)
18125       return SDValue();
18126     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18127     if (needOppositeCond)
18128       CC = X86::GetOppositeBranchCondition(CC);
18129     return SetCC.getOperand(3);
18130   }
18131   }
18132
18133   return SDValue();
18134 }
18135
18136 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18137 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18138                                   TargetLowering::DAGCombinerInfo &DCI,
18139                                   const X86Subtarget *Subtarget) {
18140   SDLoc DL(N);
18141
18142   // If the flag operand isn't dead, don't touch this CMOV.
18143   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18144     return SDValue();
18145
18146   SDValue FalseOp = N->getOperand(0);
18147   SDValue TrueOp = N->getOperand(1);
18148   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18149   SDValue Cond = N->getOperand(3);
18150
18151   if (CC == X86::COND_E || CC == X86::COND_NE) {
18152     switch (Cond.getOpcode()) {
18153     default: break;
18154     case X86ISD::BSR:
18155     case X86ISD::BSF:
18156       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18157       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18158         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18159     }
18160   }
18161
18162   SDValue Flags;
18163
18164   Flags = checkBoolTestSetCCCombine(Cond, CC);
18165   if (Flags.getNode() &&
18166       // Extra check as FCMOV only supports a subset of X86 cond.
18167       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18168     SDValue Ops[] = { FalseOp, TrueOp,
18169                       DAG.getConstant(CC, MVT::i8), Flags };
18170     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18171                        Ops, array_lengthof(Ops));
18172   }
18173
18174   // If this is a select between two integer constants, try to do some
18175   // optimizations.  Note that the operands are ordered the opposite of SELECT
18176   // operands.
18177   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18178     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18179       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18180       // larger than FalseC (the false value).
18181       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18182         CC = X86::GetOppositeBranchCondition(CC);
18183         std::swap(TrueC, FalseC);
18184         std::swap(TrueOp, FalseOp);
18185       }
18186
18187       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18188       // This is efficient for any integer data type (including i8/i16) and
18189       // shift amount.
18190       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18191         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18192                            DAG.getConstant(CC, MVT::i8), Cond);
18193
18194         // Zero extend the condition if needed.
18195         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18196
18197         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18198         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18199                            DAG.getConstant(ShAmt, MVT::i8));
18200         if (N->getNumValues() == 2)  // Dead flag value?
18201           return DCI.CombineTo(N, Cond, SDValue());
18202         return Cond;
18203       }
18204
18205       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18206       // for any integer data type, including i8/i16.
18207       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18208         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18209                            DAG.getConstant(CC, MVT::i8), Cond);
18210
18211         // Zero extend the condition if needed.
18212         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18213                            FalseC->getValueType(0), Cond);
18214         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18215                            SDValue(FalseC, 0));
18216
18217         if (N->getNumValues() == 2)  // Dead flag value?
18218           return DCI.CombineTo(N, Cond, SDValue());
18219         return Cond;
18220       }
18221
18222       // Optimize cases that will turn into an LEA instruction.  This requires
18223       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18224       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18225         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18226         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18227
18228         bool isFastMultiplier = false;
18229         if (Diff < 10) {
18230           switch ((unsigned char)Diff) {
18231           default: break;
18232           case 1:  // result = add base, cond
18233           case 2:  // result = lea base(    , cond*2)
18234           case 3:  // result = lea base(cond, cond*2)
18235           case 4:  // result = lea base(    , cond*4)
18236           case 5:  // result = lea base(cond, cond*4)
18237           case 8:  // result = lea base(    , cond*8)
18238           case 9:  // result = lea base(cond, cond*8)
18239             isFastMultiplier = true;
18240             break;
18241           }
18242         }
18243
18244         if (isFastMultiplier) {
18245           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18246           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18247                              DAG.getConstant(CC, MVT::i8), Cond);
18248           // Zero extend the condition if needed.
18249           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18250                              Cond);
18251           // Scale the condition by the difference.
18252           if (Diff != 1)
18253             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18254                                DAG.getConstant(Diff, Cond.getValueType()));
18255
18256           // Add the base if non-zero.
18257           if (FalseC->getAPIntValue() != 0)
18258             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18259                                SDValue(FalseC, 0));
18260           if (N->getNumValues() == 2)  // Dead flag value?
18261             return DCI.CombineTo(N, Cond, SDValue());
18262           return Cond;
18263         }
18264       }
18265     }
18266   }
18267
18268   // Handle these cases:
18269   //   (select (x != c), e, c) -> select (x != c), e, x),
18270   //   (select (x == c), c, e) -> select (x == c), x, e)
18271   // where the c is an integer constant, and the "select" is the combination
18272   // of CMOV and CMP.
18273   //
18274   // The rationale for this change is that the conditional-move from a constant
18275   // needs two instructions, however, conditional-move from a register needs
18276   // only one instruction.
18277   //
18278   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18279   //  some instruction-combining opportunities. This opt needs to be
18280   //  postponed as late as possible.
18281   //
18282   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18283     // the DCI.xxxx conditions are provided to postpone the optimization as
18284     // late as possible.
18285
18286     ConstantSDNode *CmpAgainst = nullptr;
18287     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18288         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18289         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18290
18291       if (CC == X86::COND_NE &&
18292           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18293         CC = X86::GetOppositeBranchCondition(CC);
18294         std::swap(TrueOp, FalseOp);
18295       }
18296
18297       if (CC == X86::COND_E &&
18298           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18299         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18300                           DAG.getConstant(CC, MVT::i8), Cond };
18301         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18302                            array_lengthof(Ops));
18303       }
18304     }
18305   }
18306
18307   return SDValue();
18308 }
18309
18310 /// PerformMulCombine - Optimize a single multiply with constant into two
18311 /// in order to implement it with two cheaper instructions, e.g.
18312 /// LEA + SHL, LEA + LEA.
18313 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18314                                  TargetLowering::DAGCombinerInfo &DCI) {
18315   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18316     return SDValue();
18317
18318   EVT VT = N->getValueType(0);
18319   if (VT != MVT::i64)
18320     return SDValue();
18321
18322   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18323   if (!C)
18324     return SDValue();
18325   uint64_t MulAmt = C->getZExtValue();
18326   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18327     return SDValue();
18328
18329   uint64_t MulAmt1 = 0;
18330   uint64_t MulAmt2 = 0;
18331   if ((MulAmt % 9) == 0) {
18332     MulAmt1 = 9;
18333     MulAmt2 = MulAmt / 9;
18334   } else if ((MulAmt % 5) == 0) {
18335     MulAmt1 = 5;
18336     MulAmt2 = MulAmt / 5;
18337   } else if ((MulAmt % 3) == 0) {
18338     MulAmt1 = 3;
18339     MulAmt2 = MulAmt / 3;
18340   }
18341   if (MulAmt2 &&
18342       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18343     SDLoc DL(N);
18344
18345     if (isPowerOf2_64(MulAmt2) &&
18346         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18347       // If second multiplifer is pow2, issue it first. We want the multiply by
18348       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18349       // is an add.
18350       std::swap(MulAmt1, MulAmt2);
18351
18352     SDValue NewMul;
18353     if (isPowerOf2_64(MulAmt1))
18354       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18355                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18356     else
18357       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18358                            DAG.getConstant(MulAmt1, VT));
18359
18360     if (isPowerOf2_64(MulAmt2))
18361       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18362                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18363     else
18364       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18365                            DAG.getConstant(MulAmt2, VT));
18366
18367     // Do not add new nodes to DAG combiner worklist.
18368     DCI.CombineTo(N, NewMul, false);
18369   }
18370   return SDValue();
18371 }
18372
18373 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18374   SDValue N0 = N->getOperand(0);
18375   SDValue N1 = N->getOperand(1);
18376   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18377   EVT VT = N0.getValueType();
18378
18379   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18380   // since the result of setcc_c is all zero's or all ones.
18381   if (VT.isInteger() && !VT.isVector() &&
18382       N1C && N0.getOpcode() == ISD::AND &&
18383       N0.getOperand(1).getOpcode() == ISD::Constant) {
18384     SDValue N00 = N0.getOperand(0);
18385     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18386         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18387           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18388          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18389       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18390       APInt ShAmt = N1C->getAPIntValue();
18391       Mask = Mask.shl(ShAmt);
18392       if (Mask != 0)
18393         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18394                            N00, DAG.getConstant(Mask, VT));
18395     }
18396   }
18397
18398   // Hardware support for vector shifts is sparse which makes us scalarize the
18399   // vector operations in many cases. Also, on sandybridge ADD is faster than
18400   // shl.
18401   // (shl V, 1) -> add V,V
18402   if (isSplatVector(N1.getNode())) {
18403     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18404     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18405     // We shift all of the values by one. In many cases we do not have
18406     // hardware support for this operation. This is better expressed as an ADD
18407     // of two values.
18408     if (N1C && (1 == N1C->getZExtValue())) {
18409       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18410     }
18411   }
18412
18413   return SDValue();
18414 }
18415
18416 /// \brief Returns a vector of 0s if the node in input is a vector logical
18417 /// shift by a constant amount which is known to be bigger than or equal
18418 /// to the vector element size in bits.
18419 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18420                                       const X86Subtarget *Subtarget) {
18421   EVT VT = N->getValueType(0);
18422
18423   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18424       (!Subtarget->hasInt256() ||
18425        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18426     return SDValue();
18427
18428   SDValue Amt = N->getOperand(1);
18429   SDLoc DL(N);
18430   if (isSplatVector(Amt.getNode())) {
18431     SDValue SclrAmt = Amt->getOperand(0);
18432     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18433       APInt ShiftAmt = C->getAPIntValue();
18434       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18435
18436       // SSE2/AVX2 logical shifts always return a vector of 0s
18437       // if the shift amount is bigger than or equal to
18438       // the element size. The constant shift amount will be
18439       // encoded as a 8-bit immediate.
18440       if (ShiftAmt.trunc(8).uge(MaxAmount))
18441         return getZeroVector(VT, Subtarget, DAG, DL);
18442     }
18443   }
18444
18445   return SDValue();
18446 }
18447
18448 /// PerformShiftCombine - Combine shifts.
18449 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18450                                    TargetLowering::DAGCombinerInfo &DCI,
18451                                    const X86Subtarget *Subtarget) {
18452   if (N->getOpcode() == ISD::SHL) {
18453     SDValue V = PerformSHLCombine(N, DAG);
18454     if (V.getNode()) return V;
18455   }
18456
18457   if (N->getOpcode() != ISD::SRA) {
18458     // Try to fold this logical shift into a zero vector.
18459     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18460     if (V.getNode()) return V;
18461   }
18462
18463   return SDValue();
18464 }
18465
18466 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18467 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18468 // and friends.  Likewise for OR -> CMPNEQSS.
18469 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18470                             TargetLowering::DAGCombinerInfo &DCI,
18471                             const X86Subtarget *Subtarget) {
18472   unsigned opcode;
18473
18474   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18475   // we're requiring SSE2 for both.
18476   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18477     SDValue N0 = N->getOperand(0);
18478     SDValue N1 = N->getOperand(1);
18479     SDValue CMP0 = N0->getOperand(1);
18480     SDValue CMP1 = N1->getOperand(1);
18481     SDLoc DL(N);
18482
18483     // The SETCCs should both refer to the same CMP.
18484     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18485       return SDValue();
18486
18487     SDValue CMP00 = CMP0->getOperand(0);
18488     SDValue CMP01 = CMP0->getOperand(1);
18489     EVT     VT    = CMP00.getValueType();
18490
18491     if (VT == MVT::f32 || VT == MVT::f64) {
18492       bool ExpectingFlags = false;
18493       // Check for any users that want flags:
18494       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18495            !ExpectingFlags && UI != UE; ++UI)
18496         switch (UI->getOpcode()) {
18497         default:
18498         case ISD::BR_CC:
18499         case ISD::BRCOND:
18500         case ISD::SELECT:
18501           ExpectingFlags = true;
18502           break;
18503         case ISD::CopyToReg:
18504         case ISD::SIGN_EXTEND:
18505         case ISD::ZERO_EXTEND:
18506         case ISD::ANY_EXTEND:
18507           break;
18508         }
18509
18510       if (!ExpectingFlags) {
18511         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18512         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18513
18514         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18515           X86::CondCode tmp = cc0;
18516           cc0 = cc1;
18517           cc1 = tmp;
18518         }
18519
18520         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18521             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18522           // FIXME: need symbolic constants for these magic numbers.
18523           // See X86ATTInstPrinter.cpp:printSSECC().
18524           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18525           if (Subtarget->hasAVX512()) {
18526             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18527                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18528             if (N->getValueType(0) != MVT::i1)
18529               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18530                                  FSetCC);
18531             return FSetCC;
18532           }
18533           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18534                                               CMP00.getValueType(), CMP00, CMP01,
18535                                               DAG.getConstant(x86cc, MVT::i8));
18536
18537           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18538           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18539
18540           if (is64BitFP && !Subtarget->is64Bit()) {
18541             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18542             // 64-bit integer, since that's not a legal type. Since
18543             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18544             // bits, but can do this little dance to extract the lowest 32 bits
18545             // and work with those going forward.
18546             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18547                                            OnesOrZeroesF);
18548             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18549                                            Vector64);
18550             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18551                                         Vector32, DAG.getIntPtrConstant(0));
18552             IntVT = MVT::i32;
18553           }
18554
18555           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18556           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18557                                       DAG.getConstant(1, IntVT));
18558           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18559           return OneBitOfTruth;
18560         }
18561       }
18562     }
18563   }
18564   return SDValue();
18565 }
18566
18567 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18568 /// so it can be folded inside ANDNP.
18569 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18570   EVT VT = N->getValueType(0);
18571
18572   // Match direct AllOnes for 128 and 256-bit vectors
18573   if (ISD::isBuildVectorAllOnes(N))
18574     return true;
18575
18576   // Look through a bit convert.
18577   if (N->getOpcode() == ISD::BITCAST)
18578     N = N->getOperand(0).getNode();
18579
18580   // Sometimes the operand may come from a insert_subvector building a 256-bit
18581   // allones vector
18582   if (VT.is256BitVector() &&
18583       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18584     SDValue V1 = N->getOperand(0);
18585     SDValue V2 = N->getOperand(1);
18586
18587     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18588         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18589         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18590         ISD::isBuildVectorAllOnes(V2.getNode()))
18591       return true;
18592   }
18593
18594   return false;
18595 }
18596
18597 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18598 // register. In most cases we actually compare or select YMM-sized registers
18599 // and mixing the two types creates horrible code. This method optimizes
18600 // some of the transition sequences.
18601 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18602                                  TargetLowering::DAGCombinerInfo &DCI,
18603                                  const X86Subtarget *Subtarget) {
18604   EVT VT = N->getValueType(0);
18605   if (!VT.is256BitVector())
18606     return SDValue();
18607
18608   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18609           N->getOpcode() == ISD::ZERO_EXTEND ||
18610           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18611
18612   SDValue Narrow = N->getOperand(0);
18613   EVT NarrowVT = Narrow->getValueType(0);
18614   if (!NarrowVT.is128BitVector())
18615     return SDValue();
18616
18617   if (Narrow->getOpcode() != ISD::XOR &&
18618       Narrow->getOpcode() != ISD::AND &&
18619       Narrow->getOpcode() != ISD::OR)
18620     return SDValue();
18621
18622   SDValue N0  = Narrow->getOperand(0);
18623   SDValue N1  = Narrow->getOperand(1);
18624   SDLoc DL(Narrow);
18625
18626   // The Left side has to be a trunc.
18627   if (N0.getOpcode() != ISD::TRUNCATE)
18628     return SDValue();
18629
18630   // The type of the truncated inputs.
18631   EVT WideVT = N0->getOperand(0)->getValueType(0);
18632   if (WideVT != VT)
18633     return SDValue();
18634
18635   // The right side has to be a 'trunc' or a constant vector.
18636   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18637   bool RHSConst = (isSplatVector(N1.getNode()) &&
18638                    isa<ConstantSDNode>(N1->getOperand(0)));
18639   if (!RHSTrunc && !RHSConst)
18640     return SDValue();
18641
18642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18643
18644   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18645     return SDValue();
18646
18647   // Set N0 and N1 to hold the inputs to the new wide operation.
18648   N0 = N0->getOperand(0);
18649   if (RHSConst) {
18650     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18651                      N1->getOperand(0));
18652     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18653     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18654   } else if (RHSTrunc) {
18655     N1 = N1->getOperand(0);
18656   }
18657
18658   // Generate the wide operation.
18659   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18660   unsigned Opcode = N->getOpcode();
18661   switch (Opcode) {
18662   case ISD::ANY_EXTEND:
18663     return Op;
18664   case ISD::ZERO_EXTEND: {
18665     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18666     APInt Mask = APInt::getAllOnesValue(InBits);
18667     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18668     return DAG.getNode(ISD::AND, DL, VT,
18669                        Op, DAG.getConstant(Mask, VT));
18670   }
18671   case ISD::SIGN_EXTEND:
18672     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18673                        Op, DAG.getValueType(NarrowVT));
18674   default:
18675     llvm_unreachable("Unexpected opcode");
18676   }
18677 }
18678
18679 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18680                                  TargetLowering::DAGCombinerInfo &DCI,
18681                                  const X86Subtarget *Subtarget) {
18682   EVT VT = N->getValueType(0);
18683   if (DCI.isBeforeLegalizeOps())
18684     return SDValue();
18685
18686   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18687   if (R.getNode())
18688     return R;
18689
18690   // Create BEXTR instructions
18691   // BEXTR is ((X >> imm) & (2**size-1))
18692   if (VT == MVT::i32 || VT == MVT::i64) {
18693     SDValue N0 = N->getOperand(0);
18694     SDValue N1 = N->getOperand(1);
18695     SDLoc DL(N);
18696
18697     // Check for BEXTR.
18698     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18699         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18700       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18701       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18702       if (MaskNode && ShiftNode) {
18703         uint64_t Mask = MaskNode->getZExtValue();
18704         uint64_t Shift = ShiftNode->getZExtValue();
18705         if (isMask_64(Mask)) {
18706           uint64_t MaskSize = CountPopulation_64(Mask);
18707           if (Shift + MaskSize <= VT.getSizeInBits())
18708             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18709                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18710         }
18711       }
18712     } // BEXTR
18713
18714     return SDValue();
18715   }
18716
18717   // Want to form ANDNP nodes:
18718   // 1) In the hopes of then easily combining them with OR and AND nodes
18719   //    to form PBLEND/PSIGN.
18720   // 2) To match ANDN packed intrinsics
18721   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18722     return SDValue();
18723
18724   SDValue N0 = N->getOperand(0);
18725   SDValue N1 = N->getOperand(1);
18726   SDLoc DL(N);
18727
18728   // Check LHS for vnot
18729   if (N0.getOpcode() == ISD::XOR &&
18730       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18731       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18732     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18733
18734   // Check RHS for vnot
18735   if (N1.getOpcode() == ISD::XOR &&
18736       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18737       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18738     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18739
18740   return SDValue();
18741 }
18742
18743 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18744                                 TargetLowering::DAGCombinerInfo &DCI,
18745                                 const X86Subtarget *Subtarget) {
18746   if (DCI.isBeforeLegalizeOps())
18747     return SDValue();
18748
18749   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18750   if (R.getNode())
18751     return R;
18752
18753   SDValue N0 = N->getOperand(0);
18754   SDValue N1 = N->getOperand(1);
18755   EVT VT = N->getValueType(0);
18756
18757   // look for psign/blend
18758   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18759     if (!Subtarget->hasSSSE3() ||
18760         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18761       return SDValue();
18762
18763     // Canonicalize pandn to RHS
18764     if (N0.getOpcode() == X86ISD::ANDNP)
18765       std::swap(N0, N1);
18766     // or (and (m, y), (pandn m, x))
18767     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18768       SDValue Mask = N1.getOperand(0);
18769       SDValue X    = N1.getOperand(1);
18770       SDValue Y;
18771       if (N0.getOperand(0) == Mask)
18772         Y = N0.getOperand(1);
18773       if (N0.getOperand(1) == Mask)
18774         Y = N0.getOperand(0);
18775
18776       // Check to see if the mask appeared in both the AND and ANDNP and
18777       if (!Y.getNode())
18778         return SDValue();
18779
18780       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18781       // Look through mask bitcast.
18782       if (Mask.getOpcode() == ISD::BITCAST)
18783         Mask = Mask.getOperand(0);
18784       if (X.getOpcode() == ISD::BITCAST)
18785         X = X.getOperand(0);
18786       if (Y.getOpcode() == ISD::BITCAST)
18787         Y = Y.getOperand(0);
18788
18789       EVT MaskVT = Mask.getValueType();
18790
18791       // Validate that the Mask operand is a vector sra node.
18792       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18793       // there is no psrai.b
18794       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18795       unsigned SraAmt = ~0;
18796       if (Mask.getOpcode() == ISD::SRA) {
18797         SDValue Amt = Mask.getOperand(1);
18798         if (isSplatVector(Amt.getNode())) {
18799           SDValue SclrAmt = Amt->getOperand(0);
18800           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18801             SraAmt = C->getZExtValue();
18802         }
18803       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18804         SDValue SraC = Mask.getOperand(1);
18805         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18806       }
18807       if ((SraAmt + 1) != EltBits)
18808         return SDValue();
18809
18810       SDLoc DL(N);
18811
18812       // Now we know we at least have a plendvb with the mask val.  See if
18813       // we can form a psignb/w/d.
18814       // psign = x.type == y.type == mask.type && y = sub(0, x);
18815       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18816           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18817           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18818         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18819                "Unsupported VT for PSIGN");
18820         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18821         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18822       }
18823       // PBLENDVB only available on SSE 4.1
18824       if (!Subtarget->hasSSE41())
18825         return SDValue();
18826
18827       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18828
18829       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18830       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18831       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18832       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18833       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18834     }
18835   }
18836
18837   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18838     return SDValue();
18839
18840   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18841   MachineFunction &MF = DAG.getMachineFunction();
18842   bool OptForSize = MF.getFunction()->getAttributes().
18843     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18844
18845   // SHLD/SHRD instructions have lower register pressure, but on some
18846   // platforms they have higher latency than the equivalent
18847   // series of shifts/or that would otherwise be generated.
18848   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18849   // have higher latencies and we are not optimizing for size.
18850   if (!OptForSize && Subtarget->isSHLDSlow())
18851     return SDValue();
18852
18853   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18854     std::swap(N0, N1);
18855   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18856     return SDValue();
18857   if (!N0.hasOneUse() || !N1.hasOneUse())
18858     return SDValue();
18859
18860   SDValue ShAmt0 = N0.getOperand(1);
18861   if (ShAmt0.getValueType() != MVT::i8)
18862     return SDValue();
18863   SDValue ShAmt1 = N1.getOperand(1);
18864   if (ShAmt1.getValueType() != MVT::i8)
18865     return SDValue();
18866   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18867     ShAmt0 = ShAmt0.getOperand(0);
18868   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18869     ShAmt1 = ShAmt1.getOperand(0);
18870
18871   SDLoc DL(N);
18872   unsigned Opc = X86ISD::SHLD;
18873   SDValue Op0 = N0.getOperand(0);
18874   SDValue Op1 = N1.getOperand(0);
18875   if (ShAmt0.getOpcode() == ISD::SUB) {
18876     Opc = X86ISD::SHRD;
18877     std::swap(Op0, Op1);
18878     std::swap(ShAmt0, ShAmt1);
18879   }
18880
18881   unsigned Bits = VT.getSizeInBits();
18882   if (ShAmt1.getOpcode() == ISD::SUB) {
18883     SDValue Sum = ShAmt1.getOperand(0);
18884     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18885       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18886       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18887         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18888       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18889         return DAG.getNode(Opc, DL, VT,
18890                            Op0, Op1,
18891                            DAG.getNode(ISD::TRUNCATE, DL,
18892                                        MVT::i8, ShAmt0));
18893     }
18894   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18895     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18896     if (ShAmt0C &&
18897         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18898       return DAG.getNode(Opc, DL, VT,
18899                          N0.getOperand(0), N1.getOperand(0),
18900                          DAG.getNode(ISD::TRUNCATE, DL,
18901                                        MVT::i8, ShAmt0));
18902   }
18903
18904   return SDValue();
18905 }
18906
18907 // Generate NEG and CMOV for integer abs.
18908 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18909   EVT VT = N->getValueType(0);
18910
18911   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18912   // 8-bit integer abs to NEG and CMOV.
18913   if (VT.isInteger() && VT.getSizeInBits() == 8)
18914     return SDValue();
18915
18916   SDValue N0 = N->getOperand(0);
18917   SDValue N1 = N->getOperand(1);
18918   SDLoc DL(N);
18919
18920   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18921   // and change it to SUB and CMOV.
18922   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18923       N0.getOpcode() == ISD::ADD &&
18924       N0.getOperand(1) == N1 &&
18925       N1.getOpcode() == ISD::SRA &&
18926       N1.getOperand(0) == N0.getOperand(0))
18927     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18928       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18929         // Generate SUB & CMOV.
18930         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18931                                   DAG.getConstant(0, VT), N0.getOperand(0));
18932
18933         SDValue Ops[] = { N0.getOperand(0), Neg,
18934                           DAG.getConstant(X86::COND_GE, MVT::i8),
18935                           SDValue(Neg.getNode(), 1) };
18936         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18937                            Ops, array_lengthof(Ops));
18938       }
18939   return SDValue();
18940 }
18941
18942 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18943 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18944                                  TargetLowering::DAGCombinerInfo &DCI,
18945                                  const X86Subtarget *Subtarget) {
18946   if (DCI.isBeforeLegalizeOps())
18947     return SDValue();
18948
18949   if (Subtarget->hasCMov()) {
18950     SDValue RV = performIntegerAbsCombine(N, DAG);
18951     if (RV.getNode())
18952       return RV;
18953   }
18954
18955   return SDValue();
18956 }
18957
18958 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18959 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18960                                   TargetLowering::DAGCombinerInfo &DCI,
18961                                   const X86Subtarget *Subtarget) {
18962   LoadSDNode *Ld = cast<LoadSDNode>(N);
18963   EVT RegVT = Ld->getValueType(0);
18964   EVT MemVT = Ld->getMemoryVT();
18965   SDLoc dl(Ld);
18966   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18967   unsigned RegSz = RegVT.getSizeInBits();
18968
18969   // On Sandybridge unaligned 256bit loads are inefficient.
18970   ISD::LoadExtType Ext = Ld->getExtensionType();
18971   unsigned Alignment = Ld->getAlignment();
18972   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18973   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18974       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18975     unsigned NumElems = RegVT.getVectorNumElements();
18976     if (NumElems < 2)
18977       return SDValue();
18978
18979     SDValue Ptr = Ld->getBasePtr();
18980     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18981
18982     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18983                                   NumElems/2);
18984     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18985                                 Ld->getPointerInfo(), Ld->isVolatile(),
18986                                 Ld->isNonTemporal(), Ld->isInvariant(),
18987                                 Alignment);
18988     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18989     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18990                                 Ld->getPointerInfo(), Ld->isVolatile(),
18991                                 Ld->isNonTemporal(), Ld->isInvariant(),
18992                                 std::min(16U, Alignment));
18993     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18994                              Load1.getValue(1),
18995                              Load2.getValue(1));
18996
18997     SDValue NewVec = DAG.getUNDEF(RegVT);
18998     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18999     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19000     return DCI.CombineTo(N, NewVec, TF, true);
19001   }
19002
19003   // If this is a vector EXT Load then attempt to optimize it using a
19004   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19005   // expansion is still better than scalar code.
19006   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19007   // emit a shuffle and a arithmetic shift.
19008   // TODO: It is possible to support ZExt by zeroing the undef values
19009   // during the shuffle phase or after the shuffle.
19010   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19011       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19012     assert(MemVT != RegVT && "Cannot extend to the same type");
19013     assert(MemVT.isVector() && "Must load a vector from memory");
19014
19015     unsigned NumElems = RegVT.getVectorNumElements();
19016     unsigned MemSz = MemVT.getSizeInBits();
19017     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19018
19019     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19020       return SDValue();
19021
19022     // All sizes must be a power of two.
19023     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19024       return SDValue();
19025
19026     // Attempt to load the original value using scalar loads.
19027     // Find the largest scalar type that divides the total loaded size.
19028     MVT SclrLoadTy = MVT::i8;
19029     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19030          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19031       MVT Tp = (MVT::SimpleValueType)tp;
19032       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19033         SclrLoadTy = Tp;
19034       }
19035     }
19036
19037     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19038     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19039         (64 <= MemSz))
19040       SclrLoadTy = MVT::f64;
19041
19042     // Calculate the number of scalar loads that we need to perform
19043     // in order to load our vector from memory.
19044     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19045     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19046       return SDValue();
19047
19048     unsigned loadRegZize = RegSz;
19049     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19050       loadRegZize /= 2;
19051
19052     // Represent our vector as a sequence of elements which are the
19053     // largest scalar that we can load.
19054     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19055       loadRegZize/SclrLoadTy.getSizeInBits());
19056
19057     // Represent the data using the same element type that is stored in
19058     // memory. In practice, we ''widen'' MemVT.
19059     EVT WideVecVT =
19060           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19061                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19062
19063     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19064       "Invalid vector type");
19065
19066     // We can't shuffle using an illegal type.
19067     if (!TLI.isTypeLegal(WideVecVT))
19068       return SDValue();
19069
19070     SmallVector<SDValue, 8> Chains;
19071     SDValue Ptr = Ld->getBasePtr();
19072     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19073                                         TLI.getPointerTy());
19074     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19075
19076     for (unsigned i = 0; i < NumLoads; ++i) {
19077       // Perform a single load.
19078       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19079                                        Ptr, Ld->getPointerInfo(),
19080                                        Ld->isVolatile(), Ld->isNonTemporal(),
19081                                        Ld->isInvariant(), Ld->getAlignment());
19082       Chains.push_back(ScalarLoad.getValue(1));
19083       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19084       // another round of DAGCombining.
19085       if (i == 0)
19086         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19087       else
19088         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19089                           ScalarLoad, DAG.getIntPtrConstant(i));
19090
19091       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19092     }
19093
19094     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19095                                Chains.size());
19096
19097     // Bitcast the loaded value to a vector of the original element type, in
19098     // the size of the target vector type.
19099     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19100     unsigned SizeRatio = RegSz/MemSz;
19101
19102     if (Ext == ISD::SEXTLOAD) {
19103       // If we have SSE4.1 we can directly emit a VSEXT node.
19104       if (Subtarget->hasSSE41()) {
19105         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19106         return DCI.CombineTo(N, Sext, TF, true);
19107       }
19108
19109       // Otherwise we'll shuffle the small elements in the high bits of the
19110       // larger type and perform an arithmetic shift. If the shift is not legal
19111       // it's better to scalarize.
19112       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19113         return SDValue();
19114
19115       // Redistribute the loaded elements into the different locations.
19116       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19117       for (unsigned i = 0; i != NumElems; ++i)
19118         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19119
19120       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19121                                            DAG.getUNDEF(WideVecVT),
19122                                            &ShuffleVec[0]);
19123
19124       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19125
19126       // Build the arithmetic shift.
19127       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19128                      MemVT.getVectorElementType().getSizeInBits();
19129       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19130                           DAG.getConstant(Amt, RegVT));
19131
19132       return DCI.CombineTo(N, Shuff, TF, true);
19133     }
19134
19135     // Redistribute the loaded elements into the different locations.
19136     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19137     for (unsigned i = 0; i != NumElems; ++i)
19138       ShuffleVec[i*SizeRatio] = i;
19139
19140     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19141                                          DAG.getUNDEF(WideVecVT),
19142                                          &ShuffleVec[0]);
19143
19144     // Bitcast to the requested type.
19145     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19146     // Replace the original load with the new sequence
19147     // and return the new chain.
19148     return DCI.CombineTo(N, Shuff, TF, true);
19149   }
19150
19151   return SDValue();
19152 }
19153
19154 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19155 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19156                                    const X86Subtarget *Subtarget) {
19157   StoreSDNode *St = cast<StoreSDNode>(N);
19158   EVT VT = St->getValue().getValueType();
19159   EVT StVT = St->getMemoryVT();
19160   SDLoc dl(St);
19161   SDValue StoredVal = St->getOperand(1);
19162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19163
19164   // If we are saving a concatenation of two XMM registers, perform two stores.
19165   // On Sandy Bridge, 256-bit memory operations are executed by two
19166   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19167   // memory  operation.
19168   unsigned Alignment = St->getAlignment();
19169   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19170   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19171       StVT == VT && !IsAligned) {
19172     unsigned NumElems = VT.getVectorNumElements();
19173     if (NumElems < 2)
19174       return SDValue();
19175
19176     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19177     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19178
19179     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19180     SDValue Ptr0 = St->getBasePtr();
19181     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19182
19183     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19184                                 St->getPointerInfo(), St->isVolatile(),
19185                                 St->isNonTemporal(), Alignment);
19186     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19187                                 St->getPointerInfo(), St->isVolatile(),
19188                                 St->isNonTemporal(),
19189                                 std::min(16U, Alignment));
19190     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19191   }
19192
19193   // Optimize trunc store (of multiple scalars) to shuffle and store.
19194   // First, pack all of the elements in one place. Next, store to memory
19195   // in fewer chunks.
19196   if (St->isTruncatingStore() && VT.isVector()) {
19197     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19198     unsigned NumElems = VT.getVectorNumElements();
19199     assert(StVT != VT && "Cannot truncate to the same type");
19200     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19201     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19202
19203     // From, To sizes and ElemCount must be pow of two
19204     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19205     // We are going to use the original vector elt for storing.
19206     // Accumulated smaller vector elements must be a multiple of the store size.
19207     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19208
19209     unsigned SizeRatio  = FromSz / ToSz;
19210
19211     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19212
19213     // Create a type on which we perform the shuffle
19214     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19215             StVT.getScalarType(), NumElems*SizeRatio);
19216
19217     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19218
19219     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19220     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19221     for (unsigned i = 0; i != NumElems; ++i)
19222       ShuffleVec[i] = i * SizeRatio;
19223
19224     // Can't shuffle using an illegal type.
19225     if (!TLI.isTypeLegal(WideVecVT))
19226       return SDValue();
19227
19228     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19229                                          DAG.getUNDEF(WideVecVT),
19230                                          &ShuffleVec[0]);
19231     // At this point all of the data is stored at the bottom of the
19232     // register. We now need to save it to mem.
19233
19234     // Find the largest store unit
19235     MVT StoreType = MVT::i8;
19236     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19237          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19238       MVT Tp = (MVT::SimpleValueType)tp;
19239       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19240         StoreType = Tp;
19241     }
19242
19243     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19244     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19245         (64 <= NumElems * ToSz))
19246       StoreType = MVT::f64;
19247
19248     // Bitcast the original vector into a vector of store-size units
19249     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19250             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19251     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19252     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19253     SmallVector<SDValue, 8> Chains;
19254     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19255                                         TLI.getPointerTy());
19256     SDValue Ptr = St->getBasePtr();
19257
19258     // Perform one or more big stores into memory.
19259     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19260       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19261                                    StoreType, ShuffWide,
19262                                    DAG.getIntPtrConstant(i));
19263       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19264                                 St->getPointerInfo(), St->isVolatile(),
19265                                 St->isNonTemporal(), St->getAlignment());
19266       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19267       Chains.push_back(Ch);
19268     }
19269
19270     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19271                                Chains.size());
19272   }
19273
19274   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19275   // the FP state in cases where an emms may be missing.
19276   // A preferable solution to the general problem is to figure out the right
19277   // places to insert EMMS.  This qualifies as a quick hack.
19278
19279   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19280   if (VT.getSizeInBits() != 64)
19281     return SDValue();
19282
19283   const Function *F = DAG.getMachineFunction().getFunction();
19284   bool NoImplicitFloatOps = F->getAttributes().
19285     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19286   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19287                      && Subtarget->hasSSE2();
19288   if ((VT.isVector() ||
19289        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19290       isa<LoadSDNode>(St->getValue()) &&
19291       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19292       St->getChain().hasOneUse() && !St->isVolatile()) {
19293     SDNode* LdVal = St->getValue().getNode();
19294     LoadSDNode *Ld = nullptr;
19295     int TokenFactorIndex = -1;
19296     SmallVector<SDValue, 8> Ops;
19297     SDNode* ChainVal = St->getChain().getNode();
19298     // Must be a store of a load.  We currently handle two cases:  the load
19299     // is a direct child, and it's under an intervening TokenFactor.  It is
19300     // possible to dig deeper under nested TokenFactors.
19301     if (ChainVal == LdVal)
19302       Ld = cast<LoadSDNode>(St->getChain());
19303     else if (St->getValue().hasOneUse() &&
19304              ChainVal->getOpcode() == ISD::TokenFactor) {
19305       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19306         if (ChainVal->getOperand(i).getNode() == LdVal) {
19307           TokenFactorIndex = i;
19308           Ld = cast<LoadSDNode>(St->getValue());
19309         } else
19310           Ops.push_back(ChainVal->getOperand(i));
19311       }
19312     }
19313
19314     if (!Ld || !ISD::isNormalLoad(Ld))
19315       return SDValue();
19316
19317     // If this is not the MMX case, i.e. we are just turning i64 load/store
19318     // into f64 load/store, avoid the transformation if there are multiple
19319     // uses of the loaded value.
19320     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19321       return SDValue();
19322
19323     SDLoc LdDL(Ld);
19324     SDLoc StDL(N);
19325     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19326     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19327     // pair instead.
19328     if (Subtarget->is64Bit() || F64IsLegal) {
19329       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19330       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19331                                   Ld->getPointerInfo(), Ld->isVolatile(),
19332                                   Ld->isNonTemporal(), Ld->isInvariant(),
19333                                   Ld->getAlignment());
19334       SDValue NewChain = NewLd.getValue(1);
19335       if (TokenFactorIndex != -1) {
19336         Ops.push_back(NewChain);
19337         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19338                                Ops.size());
19339       }
19340       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19341                           St->getPointerInfo(),
19342                           St->isVolatile(), St->isNonTemporal(),
19343                           St->getAlignment());
19344     }
19345
19346     // Otherwise, lower to two pairs of 32-bit loads / stores.
19347     SDValue LoAddr = Ld->getBasePtr();
19348     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19349                                  DAG.getConstant(4, MVT::i32));
19350
19351     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19352                                Ld->getPointerInfo(),
19353                                Ld->isVolatile(), Ld->isNonTemporal(),
19354                                Ld->isInvariant(), Ld->getAlignment());
19355     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19356                                Ld->getPointerInfo().getWithOffset(4),
19357                                Ld->isVolatile(), Ld->isNonTemporal(),
19358                                Ld->isInvariant(),
19359                                MinAlign(Ld->getAlignment(), 4));
19360
19361     SDValue NewChain = LoLd.getValue(1);
19362     if (TokenFactorIndex != -1) {
19363       Ops.push_back(LoLd);
19364       Ops.push_back(HiLd);
19365       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19366                              Ops.size());
19367     }
19368
19369     LoAddr = St->getBasePtr();
19370     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19371                          DAG.getConstant(4, MVT::i32));
19372
19373     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19374                                 St->getPointerInfo(),
19375                                 St->isVolatile(), St->isNonTemporal(),
19376                                 St->getAlignment());
19377     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19378                                 St->getPointerInfo().getWithOffset(4),
19379                                 St->isVolatile(),
19380                                 St->isNonTemporal(),
19381                                 MinAlign(St->getAlignment(), 4));
19382     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19383   }
19384   return SDValue();
19385 }
19386
19387 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19388 /// and return the operands for the horizontal operation in LHS and RHS.  A
19389 /// horizontal operation performs the binary operation on successive elements
19390 /// of its first operand, then on successive elements of its second operand,
19391 /// returning the resulting values in a vector.  For example, if
19392 ///   A = < float a0, float a1, float a2, float a3 >
19393 /// and
19394 ///   B = < float b0, float b1, float b2, float b3 >
19395 /// then the result of doing a horizontal operation on A and B is
19396 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19397 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19398 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19399 /// set to A, RHS to B, and the routine returns 'true'.
19400 /// Note that the binary operation should have the property that if one of the
19401 /// operands is UNDEF then the result is UNDEF.
19402 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19403   // Look for the following pattern: if
19404   //   A = < float a0, float a1, float a2, float a3 >
19405   //   B = < float b0, float b1, float b2, float b3 >
19406   // and
19407   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19408   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19409   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19410   // which is A horizontal-op B.
19411
19412   // At least one of the operands should be a vector shuffle.
19413   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19414       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19415     return false;
19416
19417   MVT VT = LHS.getSimpleValueType();
19418
19419   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19420          "Unsupported vector type for horizontal add/sub");
19421
19422   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19423   // operate independently on 128-bit lanes.
19424   unsigned NumElts = VT.getVectorNumElements();
19425   unsigned NumLanes = VT.getSizeInBits()/128;
19426   unsigned NumLaneElts = NumElts / NumLanes;
19427   assert((NumLaneElts % 2 == 0) &&
19428          "Vector type should have an even number of elements in each lane");
19429   unsigned HalfLaneElts = NumLaneElts/2;
19430
19431   // View LHS in the form
19432   //   LHS = VECTOR_SHUFFLE A, B, LMask
19433   // If LHS is not a shuffle then pretend it is the shuffle
19434   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19435   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19436   // type VT.
19437   SDValue A, B;
19438   SmallVector<int, 16> LMask(NumElts);
19439   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19440     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19441       A = LHS.getOperand(0);
19442     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19443       B = LHS.getOperand(1);
19444     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19445     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19446   } else {
19447     if (LHS.getOpcode() != ISD::UNDEF)
19448       A = LHS;
19449     for (unsigned i = 0; i != NumElts; ++i)
19450       LMask[i] = i;
19451   }
19452
19453   // Likewise, view RHS in the form
19454   //   RHS = VECTOR_SHUFFLE C, D, RMask
19455   SDValue C, D;
19456   SmallVector<int, 16> RMask(NumElts);
19457   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19458     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19459       C = RHS.getOperand(0);
19460     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19461       D = RHS.getOperand(1);
19462     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19463     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19464   } else {
19465     if (RHS.getOpcode() != ISD::UNDEF)
19466       C = RHS;
19467     for (unsigned i = 0; i != NumElts; ++i)
19468       RMask[i] = i;
19469   }
19470
19471   // Check that the shuffles are both shuffling the same vectors.
19472   if (!(A == C && B == D) && !(A == D && B == C))
19473     return false;
19474
19475   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19476   if (!A.getNode() && !B.getNode())
19477     return false;
19478
19479   // If A and B occur in reverse order in RHS, then "swap" them (which means
19480   // rewriting the mask).
19481   if (A != C)
19482     CommuteVectorShuffleMask(RMask, NumElts);
19483
19484   // At this point LHS and RHS are equivalent to
19485   //   LHS = VECTOR_SHUFFLE A, B, LMask
19486   //   RHS = VECTOR_SHUFFLE A, B, RMask
19487   // Check that the masks correspond to performing a horizontal operation.
19488   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19489     for (unsigned i = 0; i != NumLaneElts; ++i) {
19490       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19491
19492       // Ignore any UNDEF components.
19493       if (LIdx < 0 || RIdx < 0 ||
19494           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19495           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19496         continue;
19497
19498       // Check that successive elements are being operated on.  If not, this is
19499       // not a horizontal operation.
19500       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19501       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19502       if (!(LIdx == Index && RIdx == Index + 1) &&
19503           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19504         return false;
19505     }
19506   }
19507
19508   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19509   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19510   return true;
19511 }
19512
19513 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19514 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19515                                   const X86Subtarget *Subtarget) {
19516   EVT VT = N->getValueType(0);
19517   SDValue LHS = N->getOperand(0);
19518   SDValue RHS = N->getOperand(1);
19519
19520   // Try to synthesize horizontal adds from adds of shuffles.
19521   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19522        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19523       isHorizontalBinOp(LHS, RHS, true))
19524     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19525   return SDValue();
19526 }
19527
19528 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19529 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19530                                   const X86Subtarget *Subtarget) {
19531   EVT VT = N->getValueType(0);
19532   SDValue LHS = N->getOperand(0);
19533   SDValue RHS = N->getOperand(1);
19534
19535   // Try to synthesize horizontal subs from subs of shuffles.
19536   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19537        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19538       isHorizontalBinOp(LHS, RHS, false))
19539     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19540   return SDValue();
19541 }
19542
19543 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19544 /// X86ISD::FXOR nodes.
19545 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19546   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19547   // F[X]OR(0.0, x) -> x
19548   // F[X]OR(x, 0.0) -> x
19549   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19550     if (C->getValueAPF().isPosZero())
19551       return N->getOperand(1);
19552   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19553     if (C->getValueAPF().isPosZero())
19554       return N->getOperand(0);
19555   return SDValue();
19556 }
19557
19558 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19559 /// X86ISD::FMAX nodes.
19560 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19561   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19562
19563   // Only perform optimizations if UnsafeMath is used.
19564   if (!DAG.getTarget().Options.UnsafeFPMath)
19565     return SDValue();
19566
19567   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19568   // into FMINC and FMAXC, which are Commutative operations.
19569   unsigned NewOp = 0;
19570   switch (N->getOpcode()) {
19571     default: llvm_unreachable("unknown opcode");
19572     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19573     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19574   }
19575
19576   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19577                      N->getOperand(0), N->getOperand(1));
19578 }
19579
19580 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19581 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19582   // FAND(0.0, x) -> 0.0
19583   // FAND(x, 0.0) -> 0.0
19584   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19585     if (C->getValueAPF().isPosZero())
19586       return N->getOperand(0);
19587   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19588     if (C->getValueAPF().isPosZero())
19589       return N->getOperand(1);
19590   return SDValue();
19591 }
19592
19593 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19594 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19595   // FANDN(x, 0.0) -> 0.0
19596   // FANDN(0.0, x) -> x
19597   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19598     if (C->getValueAPF().isPosZero())
19599       return N->getOperand(1);
19600   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19601     if (C->getValueAPF().isPosZero())
19602       return N->getOperand(1);
19603   return SDValue();
19604 }
19605
19606 static SDValue PerformBTCombine(SDNode *N,
19607                                 SelectionDAG &DAG,
19608                                 TargetLowering::DAGCombinerInfo &DCI) {
19609   // BT ignores high bits in the bit index operand.
19610   SDValue Op1 = N->getOperand(1);
19611   if (Op1.hasOneUse()) {
19612     unsigned BitWidth = Op1.getValueSizeInBits();
19613     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19614     APInt KnownZero, KnownOne;
19615     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19616                                           !DCI.isBeforeLegalizeOps());
19617     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19618     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19619         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19620       DCI.CommitTargetLoweringOpt(TLO);
19621   }
19622   return SDValue();
19623 }
19624
19625 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19626   SDValue Op = N->getOperand(0);
19627   if (Op.getOpcode() == ISD::BITCAST)
19628     Op = Op.getOperand(0);
19629   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19630   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19631       VT.getVectorElementType().getSizeInBits() ==
19632       OpVT.getVectorElementType().getSizeInBits()) {
19633     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19634   }
19635   return SDValue();
19636 }
19637
19638 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19639                                                const X86Subtarget *Subtarget) {
19640   EVT VT = N->getValueType(0);
19641   if (!VT.isVector())
19642     return SDValue();
19643
19644   SDValue N0 = N->getOperand(0);
19645   SDValue N1 = N->getOperand(1);
19646   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19647   SDLoc dl(N);
19648
19649   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19650   // both SSE and AVX2 since there is no sign-extended shift right
19651   // operation on a vector with 64-bit elements.
19652   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19653   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19654   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19655       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19656     SDValue N00 = N0.getOperand(0);
19657
19658     // EXTLOAD has a better solution on AVX2,
19659     // it may be replaced with X86ISD::VSEXT node.
19660     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19661       if (!ISD::isNormalLoad(N00.getNode()))
19662         return SDValue();
19663
19664     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19665         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19666                                   N00, N1);
19667       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19668     }
19669   }
19670   return SDValue();
19671 }
19672
19673 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19674                                   TargetLowering::DAGCombinerInfo &DCI,
19675                                   const X86Subtarget *Subtarget) {
19676   if (!DCI.isBeforeLegalizeOps())
19677     return SDValue();
19678
19679   if (!Subtarget->hasFp256())
19680     return SDValue();
19681
19682   EVT VT = N->getValueType(0);
19683   if (VT.isVector() && VT.getSizeInBits() == 256) {
19684     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19685     if (R.getNode())
19686       return R;
19687   }
19688
19689   return SDValue();
19690 }
19691
19692 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19693                                  const X86Subtarget* Subtarget) {
19694   SDLoc dl(N);
19695   EVT VT = N->getValueType(0);
19696
19697   // Let legalize expand this if it isn't a legal type yet.
19698   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19699     return SDValue();
19700
19701   EVT ScalarVT = VT.getScalarType();
19702   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19703       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19704     return SDValue();
19705
19706   SDValue A = N->getOperand(0);
19707   SDValue B = N->getOperand(1);
19708   SDValue C = N->getOperand(2);
19709
19710   bool NegA = (A.getOpcode() == ISD::FNEG);
19711   bool NegB = (B.getOpcode() == ISD::FNEG);
19712   bool NegC = (C.getOpcode() == ISD::FNEG);
19713
19714   // Negative multiplication when NegA xor NegB
19715   bool NegMul = (NegA != NegB);
19716   if (NegA)
19717     A = A.getOperand(0);
19718   if (NegB)
19719     B = B.getOperand(0);
19720   if (NegC)
19721     C = C.getOperand(0);
19722
19723   unsigned Opcode;
19724   if (!NegMul)
19725     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19726   else
19727     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19728
19729   return DAG.getNode(Opcode, dl, VT, A, B, C);
19730 }
19731
19732 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19733                                   TargetLowering::DAGCombinerInfo &DCI,
19734                                   const X86Subtarget *Subtarget) {
19735   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19736   //           (and (i32 x86isd::setcc_carry), 1)
19737   // This eliminates the zext. This transformation is necessary because
19738   // ISD::SETCC is always legalized to i8.
19739   SDLoc dl(N);
19740   SDValue N0 = N->getOperand(0);
19741   EVT VT = N->getValueType(0);
19742
19743   if (N0.getOpcode() == ISD::AND &&
19744       N0.hasOneUse() &&
19745       N0.getOperand(0).hasOneUse()) {
19746     SDValue N00 = N0.getOperand(0);
19747     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19748       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19749       if (!C || C->getZExtValue() != 1)
19750         return SDValue();
19751       return DAG.getNode(ISD::AND, dl, VT,
19752                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19753                                      N00.getOperand(0), N00.getOperand(1)),
19754                          DAG.getConstant(1, VT));
19755     }
19756   }
19757
19758   if (N0.getOpcode() == ISD::TRUNCATE &&
19759       N0.hasOneUse() &&
19760       N0.getOperand(0).hasOneUse()) {
19761     SDValue N00 = N0.getOperand(0);
19762     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19763       return DAG.getNode(ISD::AND, dl, VT,
19764                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19765                                      N00.getOperand(0), N00.getOperand(1)),
19766                          DAG.getConstant(1, VT));
19767     }
19768   }
19769   if (VT.is256BitVector()) {
19770     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19771     if (R.getNode())
19772       return R;
19773   }
19774
19775   return SDValue();
19776 }
19777
19778 // Optimize x == -y --> x+y == 0
19779 //          x != -y --> x+y != 0
19780 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19781                                       const X86Subtarget* Subtarget) {
19782   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19783   SDValue LHS = N->getOperand(0);
19784   SDValue RHS = N->getOperand(1);
19785   EVT VT = N->getValueType(0);
19786   SDLoc DL(N);
19787
19788   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19789     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19790       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19791         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19792                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19793         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19794                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19795       }
19796   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19797     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19798       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19799         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19800                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19801         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19802                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19803       }
19804
19805   if (VT.getScalarType() == MVT::i1) {
19806     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19807       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19808     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19809     if (!IsSEXT0 && !IsVZero0)
19810       return SDValue();
19811     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19812       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19813     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19814
19815     if (!IsSEXT1 && !IsVZero1)
19816       return SDValue();
19817
19818     if (IsSEXT0 && IsVZero1) {
19819       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19820       if (CC == ISD::SETEQ)
19821         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19822       return LHS.getOperand(0);
19823     }
19824     if (IsSEXT1 && IsVZero0) {
19825       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19826       if (CC == ISD::SETEQ)
19827         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19828       return RHS.getOperand(0);
19829     }
19830   }
19831
19832   return SDValue();
19833 }
19834
19835 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19836 // as "sbb reg,reg", since it can be extended without zext and produces
19837 // an all-ones bit which is more useful than 0/1 in some cases.
19838 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19839                                MVT VT) {
19840   if (VT == MVT::i8)
19841     return DAG.getNode(ISD::AND, DL, VT,
19842                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19843                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19844                        DAG.getConstant(1, VT));
19845   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19846   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19847                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19848                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19849 }
19850
19851 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19852 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19853                                    TargetLowering::DAGCombinerInfo &DCI,
19854                                    const X86Subtarget *Subtarget) {
19855   SDLoc DL(N);
19856   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19857   SDValue EFLAGS = N->getOperand(1);
19858
19859   if (CC == X86::COND_A) {
19860     // Try to convert COND_A into COND_B in an attempt to facilitate
19861     // materializing "setb reg".
19862     //
19863     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19864     // cannot take an immediate as its first operand.
19865     //
19866     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19867         EFLAGS.getValueType().isInteger() &&
19868         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19869       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19870                                    EFLAGS.getNode()->getVTList(),
19871                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19872       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19873       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19874     }
19875   }
19876
19877   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19878   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19879   // cases.
19880   if (CC == X86::COND_B)
19881     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19882
19883   SDValue Flags;
19884
19885   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19886   if (Flags.getNode()) {
19887     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19888     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19889   }
19890
19891   return SDValue();
19892 }
19893
19894 // Optimize branch condition evaluation.
19895 //
19896 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19897                                     TargetLowering::DAGCombinerInfo &DCI,
19898                                     const X86Subtarget *Subtarget) {
19899   SDLoc DL(N);
19900   SDValue Chain = N->getOperand(0);
19901   SDValue Dest = N->getOperand(1);
19902   SDValue EFLAGS = N->getOperand(3);
19903   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19904
19905   SDValue Flags;
19906
19907   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19908   if (Flags.getNode()) {
19909     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19910     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19911                        Flags);
19912   }
19913
19914   return SDValue();
19915 }
19916
19917 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19918                                         const X86TargetLowering *XTLI) {
19919   SDValue Op0 = N->getOperand(0);
19920   EVT InVT = Op0->getValueType(0);
19921
19922   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19923   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19924     SDLoc dl(N);
19925     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19926     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19927     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19928   }
19929
19930   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19931   // a 32-bit target where SSE doesn't support i64->FP operations.
19932   if (Op0.getOpcode() == ISD::LOAD) {
19933     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19934     EVT VT = Ld->getValueType(0);
19935     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19936         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19937         !XTLI->getSubtarget()->is64Bit() &&
19938         VT == MVT::i64) {
19939       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19940                                           Ld->getChain(), Op0, DAG);
19941       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19942       return FILDChain;
19943     }
19944   }
19945   return SDValue();
19946 }
19947
19948 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19949 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19950                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19951   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19952   // the result is either zero or one (depending on the input carry bit).
19953   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19954   if (X86::isZeroNode(N->getOperand(0)) &&
19955       X86::isZeroNode(N->getOperand(1)) &&
19956       // We don't have a good way to replace an EFLAGS use, so only do this when
19957       // dead right now.
19958       SDValue(N, 1).use_empty()) {
19959     SDLoc DL(N);
19960     EVT VT = N->getValueType(0);
19961     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19962     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19963                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19964                                            DAG.getConstant(X86::COND_B,MVT::i8),
19965                                            N->getOperand(2)),
19966                                DAG.getConstant(1, VT));
19967     return DCI.CombineTo(N, Res1, CarryOut);
19968   }
19969
19970   return SDValue();
19971 }
19972
19973 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19974 //      (add Y, (setne X, 0)) -> sbb -1, Y
19975 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19976 //      (sub (setne X, 0), Y) -> adc -1, Y
19977 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19978   SDLoc DL(N);
19979
19980   // Look through ZExts.
19981   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19982   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19983     return SDValue();
19984
19985   SDValue SetCC = Ext.getOperand(0);
19986   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19987     return SDValue();
19988
19989   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19990   if (CC != X86::COND_E && CC != X86::COND_NE)
19991     return SDValue();
19992
19993   SDValue Cmp = SetCC.getOperand(1);
19994   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19995       !X86::isZeroNode(Cmp.getOperand(1)) ||
19996       !Cmp.getOperand(0).getValueType().isInteger())
19997     return SDValue();
19998
19999   SDValue CmpOp0 = Cmp.getOperand(0);
20000   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20001                                DAG.getConstant(1, CmpOp0.getValueType()));
20002
20003   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20004   if (CC == X86::COND_NE)
20005     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20006                        DL, OtherVal.getValueType(), OtherVal,
20007                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20008   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20009                      DL, OtherVal.getValueType(), OtherVal,
20010                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20011 }
20012
20013 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20014 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20015                                  const X86Subtarget *Subtarget) {
20016   EVT VT = N->getValueType(0);
20017   SDValue Op0 = N->getOperand(0);
20018   SDValue Op1 = N->getOperand(1);
20019
20020   // Try to synthesize horizontal adds from adds of shuffles.
20021   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20022        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20023       isHorizontalBinOp(Op0, Op1, true))
20024     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20025
20026   return OptimizeConditionalInDecrement(N, DAG);
20027 }
20028
20029 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20030                                  const X86Subtarget *Subtarget) {
20031   SDValue Op0 = N->getOperand(0);
20032   SDValue Op1 = N->getOperand(1);
20033
20034   // X86 can't encode an immediate LHS of a sub. See if we can push the
20035   // negation into a preceding instruction.
20036   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20037     // If the RHS of the sub is a XOR with one use and a constant, invert the
20038     // immediate. Then add one to the LHS of the sub so we can turn
20039     // X-Y -> X+~Y+1, saving one register.
20040     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20041         isa<ConstantSDNode>(Op1.getOperand(1))) {
20042       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20043       EVT VT = Op0.getValueType();
20044       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20045                                    Op1.getOperand(0),
20046                                    DAG.getConstant(~XorC, VT));
20047       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20048                          DAG.getConstant(C->getAPIntValue()+1, VT));
20049     }
20050   }
20051
20052   // Try to synthesize horizontal adds from adds of shuffles.
20053   EVT VT = N->getValueType(0);
20054   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20055        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20056       isHorizontalBinOp(Op0, Op1, true))
20057     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20058
20059   return OptimizeConditionalInDecrement(N, DAG);
20060 }
20061
20062 /// performVZEXTCombine - Performs build vector combines
20063 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20064                                         TargetLowering::DAGCombinerInfo &DCI,
20065                                         const X86Subtarget *Subtarget) {
20066   // (vzext (bitcast (vzext (x)) -> (vzext x)
20067   SDValue In = N->getOperand(0);
20068   while (In.getOpcode() == ISD::BITCAST)
20069     In = In.getOperand(0);
20070
20071   if (In.getOpcode() != X86ISD::VZEXT)
20072     return SDValue();
20073
20074   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20075                      In.getOperand(0));
20076 }
20077
20078 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20079                                              DAGCombinerInfo &DCI) const {
20080   SelectionDAG &DAG = DCI.DAG;
20081   switch (N->getOpcode()) {
20082   default: break;
20083   case ISD::EXTRACT_VECTOR_ELT:
20084     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20085   case ISD::VSELECT:
20086   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20087   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20088   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20089   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20090   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20091   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20092   case ISD::SHL:
20093   case ISD::SRA:
20094   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20095   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20096   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20097   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20098   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20099   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20100   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20101   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20102   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20103   case X86ISD::FXOR:
20104   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20105   case X86ISD::FMIN:
20106   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20107   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20108   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20109   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20110   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20111   case ISD::ANY_EXTEND:
20112   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20113   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20114   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20115   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20116   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20117   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20118   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20119   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20120   case X86ISD::SHUFP:       // Handle all target specific shuffles
20121   case X86ISD::PALIGNR:
20122   case X86ISD::UNPCKH:
20123   case X86ISD::UNPCKL:
20124   case X86ISD::MOVHLPS:
20125   case X86ISD::MOVLHPS:
20126   case X86ISD::PSHUFD:
20127   case X86ISD::PSHUFHW:
20128   case X86ISD::PSHUFLW:
20129   case X86ISD::MOVSS:
20130   case X86ISD::MOVSD:
20131   case X86ISD::VPERMILP:
20132   case X86ISD::VPERM2X128:
20133   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20134   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20135   }
20136
20137   return SDValue();
20138 }
20139
20140 /// isTypeDesirableForOp - Return true if the target has native support for
20141 /// the specified value type and it is 'desirable' to use the type for the
20142 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20143 /// instruction encodings are longer and some i16 instructions are slow.
20144 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20145   if (!isTypeLegal(VT))
20146     return false;
20147   if (VT != MVT::i16)
20148     return true;
20149
20150   switch (Opc) {
20151   default:
20152     return true;
20153   case ISD::LOAD:
20154   case ISD::SIGN_EXTEND:
20155   case ISD::ZERO_EXTEND:
20156   case ISD::ANY_EXTEND:
20157   case ISD::SHL:
20158   case ISD::SRL:
20159   case ISD::SUB:
20160   case ISD::ADD:
20161   case ISD::MUL:
20162   case ISD::AND:
20163   case ISD::OR:
20164   case ISD::XOR:
20165     return false;
20166   }
20167 }
20168
20169 /// IsDesirableToPromoteOp - This method query the target whether it is
20170 /// beneficial for dag combiner to promote the specified node. If true, it
20171 /// should return the desired promotion type by reference.
20172 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20173   EVT VT = Op.getValueType();
20174   if (VT != MVT::i16)
20175     return false;
20176
20177   bool Promote = false;
20178   bool Commute = false;
20179   switch (Op.getOpcode()) {
20180   default: break;
20181   case ISD::LOAD: {
20182     LoadSDNode *LD = cast<LoadSDNode>(Op);
20183     // If the non-extending load has a single use and it's not live out, then it
20184     // might be folded.
20185     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20186                                                      Op.hasOneUse()*/) {
20187       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20188              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20189         // The only case where we'd want to promote LOAD (rather then it being
20190         // promoted as an operand is when it's only use is liveout.
20191         if (UI->getOpcode() != ISD::CopyToReg)
20192           return false;
20193       }
20194     }
20195     Promote = true;
20196     break;
20197   }
20198   case ISD::SIGN_EXTEND:
20199   case ISD::ZERO_EXTEND:
20200   case ISD::ANY_EXTEND:
20201     Promote = true;
20202     break;
20203   case ISD::SHL:
20204   case ISD::SRL: {
20205     SDValue N0 = Op.getOperand(0);
20206     // Look out for (store (shl (load), x)).
20207     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20208       return false;
20209     Promote = true;
20210     break;
20211   }
20212   case ISD::ADD:
20213   case ISD::MUL:
20214   case ISD::AND:
20215   case ISD::OR:
20216   case ISD::XOR:
20217     Commute = true;
20218     // fallthrough
20219   case ISD::SUB: {
20220     SDValue N0 = Op.getOperand(0);
20221     SDValue N1 = Op.getOperand(1);
20222     if (!Commute && MayFoldLoad(N1))
20223       return false;
20224     // Avoid disabling potential load folding opportunities.
20225     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20226       return false;
20227     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20228       return false;
20229     Promote = true;
20230   }
20231   }
20232
20233   PVT = MVT::i32;
20234   return Promote;
20235 }
20236
20237 //===----------------------------------------------------------------------===//
20238 //                           X86 Inline Assembly Support
20239 //===----------------------------------------------------------------------===//
20240
20241 namespace {
20242   // Helper to match a string separated by whitespace.
20243   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20244     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20245
20246     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20247       StringRef piece(*args[i]);
20248       if (!s.startswith(piece)) // Check if the piece matches.
20249         return false;
20250
20251       s = s.substr(piece.size());
20252       StringRef::size_type pos = s.find_first_not_of(" \t");
20253       if (pos == 0) // We matched a prefix.
20254         return false;
20255
20256       s = s.substr(pos);
20257     }
20258
20259     return s.empty();
20260   }
20261   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20262 }
20263
20264 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20265
20266   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20267     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20268         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20269         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20270
20271       if (AsmPieces.size() == 3)
20272         return true;
20273       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20274         return true;
20275     }
20276   }
20277   return false;
20278 }
20279
20280 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20281   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20282
20283   std::string AsmStr = IA->getAsmString();
20284
20285   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20286   if (!Ty || Ty->getBitWidth() % 16 != 0)
20287     return false;
20288
20289   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20290   SmallVector<StringRef, 4> AsmPieces;
20291   SplitString(AsmStr, AsmPieces, ";\n");
20292
20293   switch (AsmPieces.size()) {
20294   default: return false;
20295   case 1:
20296     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20297     // we will turn this bswap into something that will be lowered to logical
20298     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20299     // lower so don't worry about this.
20300     // bswap $0
20301     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20302         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20303         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20304         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20305         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20306         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20307       // No need to check constraints, nothing other than the equivalent of
20308       // "=r,0" would be valid here.
20309       return IntrinsicLowering::LowerToByteSwap(CI);
20310     }
20311
20312     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20313     if (CI->getType()->isIntegerTy(16) &&
20314         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20315         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20316          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20317       AsmPieces.clear();
20318       const std::string &ConstraintsStr = IA->getConstraintString();
20319       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20320       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20321       if (clobbersFlagRegisters(AsmPieces))
20322         return IntrinsicLowering::LowerToByteSwap(CI);
20323     }
20324     break;
20325   case 3:
20326     if (CI->getType()->isIntegerTy(32) &&
20327         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20328         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20329         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20330         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20331       AsmPieces.clear();
20332       const std::string &ConstraintsStr = IA->getConstraintString();
20333       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20334       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20335       if (clobbersFlagRegisters(AsmPieces))
20336         return IntrinsicLowering::LowerToByteSwap(CI);
20337     }
20338
20339     if (CI->getType()->isIntegerTy(64)) {
20340       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20341       if (Constraints.size() >= 2 &&
20342           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20343           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20344         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20345         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20346             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20347             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20348           return IntrinsicLowering::LowerToByteSwap(CI);
20349       }
20350     }
20351     break;
20352   }
20353   return false;
20354 }
20355
20356 /// getConstraintType - Given a constraint letter, return the type of
20357 /// constraint it is for this target.
20358 X86TargetLowering::ConstraintType
20359 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20360   if (Constraint.size() == 1) {
20361     switch (Constraint[0]) {
20362     case 'R':
20363     case 'q':
20364     case 'Q':
20365     case 'f':
20366     case 't':
20367     case 'u':
20368     case 'y':
20369     case 'x':
20370     case 'Y':
20371     case 'l':
20372       return C_RegisterClass;
20373     case 'a':
20374     case 'b':
20375     case 'c':
20376     case 'd':
20377     case 'S':
20378     case 'D':
20379     case 'A':
20380       return C_Register;
20381     case 'I':
20382     case 'J':
20383     case 'K':
20384     case 'L':
20385     case 'M':
20386     case 'N':
20387     case 'G':
20388     case 'C':
20389     case 'e':
20390     case 'Z':
20391       return C_Other;
20392     default:
20393       break;
20394     }
20395   }
20396   return TargetLowering::getConstraintType(Constraint);
20397 }
20398
20399 /// Examine constraint type and operand type and determine a weight value.
20400 /// This object must already have been set up with the operand type
20401 /// and the current alternative constraint selected.
20402 TargetLowering::ConstraintWeight
20403   X86TargetLowering::getSingleConstraintMatchWeight(
20404     AsmOperandInfo &info, const char *constraint) const {
20405   ConstraintWeight weight = CW_Invalid;
20406   Value *CallOperandVal = info.CallOperandVal;
20407     // If we don't have a value, we can't do a match,
20408     // but allow it at the lowest weight.
20409   if (!CallOperandVal)
20410     return CW_Default;
20411   Type *type = CallOperandVal->getType();
20412   // Look at the constraint type.
20413   switch (*constraint) {
20414   default:
20415     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20416   case 'R':
20417   case 'q':
20418   case 'Q':
20419   case 'a':
20420   case 'b':
20421   case 'c':
20422   case 'd':
20423   case 'S':
20424   case 'D':
20425   case 'A':
20426     if (CallOperandVal->getType()->isIntegerTy())
20427       weight = CW_SpecificReg;
20428     break;
20429   case 'f':
20430   case 't':
20431   case 'u':
20432     if (type->isFloatingPointTy())
20433       weight = CW_SpecificReg;
20434     break;
20435   case 'y':
20436     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20437       weight = CW_SpecificReg;
20438     break;
20439   case 'x':
20440   case 'Y':
20441     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20442         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20443       weight = CW_Register;
20444     break;
20445   case 'I':
20446     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20447       if (C->getZExtValue() <= 31)
20448         weight = CW_Constant;
20449     }
20450     break;
20451   case 'J':
20452     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20453       if (C->getZExtValue() <= 63)
20454         weight = CW_Constant;
20455     }
20456     break;
20457   case 'K':
20458     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20459       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20460         weight = CW_Constant;
20461     }
20462     break;
20463   case 'L':
20464     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20465       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20466         weight = CW_Constant;
20467     }
20468     break;
20469   case 'M':
20470     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20471       if (C->getZExtValue() <= 3)
20472         weight = CW_Constant;
20473     }
20474     break;
20475   case 'N':
20476     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20477       if (C->getZExtValue() <= 0xff)
20478         weight = CW_Constant;
20479     }
20480     break;
20481   case 'G':
20482   case 'C':
20483     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20484       weight = CW_Constant;
20485     }
20486     break;
20487   case 'e':
20488     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20489       if ((C->getSExtValue() >= -0x80000000LL) &&
20490           (C->getSExtValue() <= 0x7fffffffLL))
20491         weight = CW_Constant;
20492     }
20493     break;
20494   case 'Z':
20495     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20496       if (C->getZExtValue() <= 0xffffffff)
20497         weight = CW_Constant;
20498     }
20499     break;
20500   }
20501   return weight;
20502 }
20503
20504 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20505 /// with another that has more specific requirements based on the type of the
20506 /// corresponding operand.
20507 const char *X86TargetLowering::
20508 LowerXConstraint(EVT ConstraintVT) const {
20509   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20510   // 'f' like normal targets.
20511   if (ConstraintVT.isFloatingPoint()) {
20512     if (Subtarget->hasSSE2())
20513       return "Y";
20514     if (Subtarget->hasSSE1())
20515       return "x";
20516   }
20517
20518   return TargetLowering::LowerXConstraint(ConstraintVT);
20519 }
20520
20521 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20522 /// vector.  If it is invalid, don't add anything to Ops.
20523 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20524                                                      std::string &Constraint,
20525                                                      std::vector<SDValue>&Ops,
20526                                                      SelectionDAG &DAG) const {
20527   SDValue Result;
20528
20529   // Only support length 1 constraints for now.
20530   if (Constraint.length() > 1) return;
20531
20532   char ConstraintLetter = Constraint[0];
20533   switch (ConstraintLetter) {
20534   default: break;
20535   case 'I':
20536     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20537       if (C->getZExtValue() <= 31) {
20538         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20539         break;
20540       }
20541     }
20542     return;
20543   case 'J':
20544     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20545       if (C->getZExtValue() <= 63) {
20546         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20547         break;
20548       }
20549     }
20550     return;
20551   case 'K':
20552     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20553       if (isInt<8>(C->getSExtValue())) {
20554         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20555         break;
20556       }
20557     }
20558     return;
20559   case 'N':
20560     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20561       if (C->getZExtValue() <= 255) {
20562         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20563         break;
20564       }
20565     }
20566     return;
20567   case 'e': {
20568     // 32-bit signed value
20569     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20570       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20571                                            C->getSExtValue())) {
20572         // Widen to 64 bits here to get it sign extended.
20573         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20574         break;
20575       }
20576     // FIXME gcc accepts some relocatable values here too, but only in certain
20577     // memory models; it's complicated.
20578     }
20579     return;
20580   }
20581   case 'Z': {
20582     // 32-bit unsigned value
20583     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20584       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20585                                            C->getZExtValue())) {
20586         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20587         break;
20588       }
20589     }
20590     // FIXME gcc accepts some relocatable values here too, but only in certain
20591     // memory models; it's complicated.
20592     return;
20593   }
20594   case 'i': {
20595     // Literal immediates are always ok.
20596     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20597       // Widen to 64 bits here to get it sign extended.
20598       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20599       break;
20600     }
20601
20602     // In any sort of PIC mode addresses need to be computed at runtime by
20603     // adding in a register or some sort of table lookup.  These can't
20604     // be used as immediates.
20605     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20606       return;
20607
20608     // If we are in non-pic codegen mode, we allow the address of a global (with
20609     // an optional displacement) to be used with 'i'.
20610     GlobalAddressSDNode *GA = nullptr;
20611     int64_t Offset = 0;
20612
20613     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20614     while (1) {
20615       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20616         Offset += GA->getOffset();
20617         break;
20618       } else if (Op.getOpcode() == ISD::ADD) {
20619         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20620           Offset += C->getZExtValue();
20621           Op = Op.getOperand(0);
20622           continue;
20623         }
20624       } else if (Op.getOpcode() == ISD::SUB) {
20625         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20626           Offset += -C->getZExtValue();
20627           Op = Op.getOperand(0);
20628           continue;
20629         }
20630       }
20631
20632       // Otherwise, this isn't something we can handle, reject it.
20633       return;
20634     }
20635
20636     const GlobalValue *GV = GA->getGlobal();
20637     // If we require an extra load to get this address, as in PIC mode, we
20638     // can't accept it.
20639     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20640                                                         getTargetMachine())))
20641       return;
20642
20643     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20644                                         GA->getValueType(0), Offset);
20645     break;
20646   }
20647   }
20648
20649   if (Result.getNode()) {
20650     Ops.push_back(Result);
20651     return;
20652   }
20653   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20654 }
20655
20656 std::pair<unsigned, const TargetRegisterClass*>
20657 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20658                                                 MVT VT) const {
20659   // First, see if this is a constraint that directly corresponds to an LLVM
20660   // register class.
20661   if (Constraint.size() == 1) {
20662     // GCC Constraint Letters
20663     switch (Constraint[0]) {
20664     default: break;
20665       // TODO: Slight differences here in allocation order and leaving
20666       // RIP in the class. Do they matter any more here than they do
20667       // in the normal allocation?
20668     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20669       if (Subtarget->is64Bit()) {
20670         if (VT == MVT::i32 || VT == MVT::f32)
20671           return std::make_pair(0U, &X86::GR32RegClass);
20672         if (VT == MVT::i16)
20673           return std::make_pair(0U, &X86::GR16RegClass);
20674         if (VT == MVT::i8 || VT == MVT::i1)
20675           return std::make_pair(0U, &X86::GR8RegClass);
20676         if (VT == MVT::i64 || VT == MVT::f64)
20677           return std::make_pair(0U, &X86::GR64RegClass);
20678         break;
20679       }
20680       // 32-bit fallthrough
20681     case 'Q':   // Q_REGS
20682       if (VT == MVT::i32 || VT == MVT::f32)
20683         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20684       if (VT == MVT::i16)
20685         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20686       if (VT == MVT::i8 || VT == MVT::i1)
20687         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20688       if (VT == MVT::i64)
20689         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20690       break;
20691     case 'r':   // GENERAL_REGS
20692     case 'l':   // INDEX_REGS
20693       if (VT == MVT::i8 || VT == MVT::i1)
20694         return std::make_pair(0U, &X86::GR8RegClass);
20695       if (VT == MVT::i16)
20696         return std::make_pair(0U, &X86::GR16RegClass);
20697       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20698         return std::make_pair(0U, &X86::GR32RegClass);
20699       return std::make_pair(0U, &X86::GR64RegClass);
20700     case 'R':   // LEGACY_REGS
20701       if (VT == MVT::i8 || VT == MVT::i1)
20702         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20703       if (VT == MVT::i16)
20704         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20705       if (VT == MVT::i32 || !Subtarget->is64Bit())
20706         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20707       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20708     case 'f':  // FP Stack registers.
20709       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20710       // value to the correct fpstack register class.
20711       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20712         return std::make_pair(0U, &X86::RFP32RegClass);
20713       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20714         return std::make_pair(0U, &X86::RFP64RegClass);
20715       return std::make_pair(0U, &X86::RFP80RegClass);
20716     case 'y':   // MMX_REGS if MMX allowed.
20717       if (!Subtarget->hasMMX()) break;
20718       return std::make_pair(0U, &X86::VR64RegClass);
20719     case 'Y':   // SSE_REGS if SSE2 allowed
20720       if (!Subtarget->hasSSE2()) break;
20721       // FALL THROUGH.
20722     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20723       if (!Subtarget->hasSSE1()) break;
20724
20725       switch (VT.SimpleTy) {
20726       default: break;
20727       // Scalar SSE types.
20728       case MVT::f32:
20729       case MVT::i32:
20730         return std::make_pair(0U, &X86::FR32RegClass);
20731       case MVT::f64:
20732       case MVT::i64:
20733         return std::make_pair(0U, &X86::FR64RegClass);
20734       // Vector types.
20735       case MVT::v16i8:
20736       case MVT::v8i16:
20737       case MVT::v4i32:
20738       case MVT::v2i64:
20739       case MVT::v4f32:
20740       case MVT::v2f64:
20741         return std::make_pair(0U, &X86::VR128RegClass);
20742       // AVX types.
20743       case MVT::v32i8:
20744       case MVT::v16i16:
20745       case MVT::v8i32:
20746       case MVT::v4i64:
20747       case MVT::v8f32:
20748       case MVT::v4f64:
20749         return std::make_pair(0U, &X86::VR256RegClass);
20750       case MVT::v8f64:
20751       case MVT::v16f32:
20752       case MVT::v16i32:
20753       case MVT::v8i64:
20754         return std::make_pair(0U, &X86::VR512RegClass);
20755       }
20756       break;
20757     }
20758   }
20759
20760   // Use the default implementation in TargetLowering to convert the register
20761   // constraint into a member of a register class.
20762   std::pair<unsigned, const TargetRegisterClass*> Res;
20763   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20764
20765   // Not found as a standard register?
20766   if (!Res.second) {
20767     // Map st(0) -> st(7) -> ST0
20768     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20769         tolower(Constraint[1]) == 's' &&
20770         tolower(Constraint[2]) == 't' &&
20771         Constraint[3] == '(' &&
20772         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20773         Constraint[5] == ')' &&
20774         Constraint[6] == '}') {
20775
20776       Res.first = X86::ST0+Constraint[4]-'0';
20777       Res.second = &X86::RFP80RegClass;
20778       return Res;
20779     }
20780
20781     // GCC allows "st(0)" to be called just plain "st".
20782     if (StringRef("{st}").equals_lower(Constraint)) {
20783       Res.first = X86::ST0;
20784       Res.second = &X86::RFP80RegClass;
20785       return Res;
20786     }
20787
20788     // flags -> EFLAGS
20789     if (StringRef("{flags}").equals_lower(Constraint)) {
20790       Res.first = X86::EFLAGS;
20791       Res.second = &X86::CCRRegClass;
20792       return Res;
20793     }
20794
20795     // 'A' means EAX + EDX.
20796     if (Constraint == "A") {
20797       Res.first = X86::EAX;
20798       Res.second = &X86::GR32_ADRegClass;
20799       return Res;
20800     }
20801     return Res;
20802   }
20803
20804   // Otherwise, check to see if this is a register class of the wrong value
20805   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20806   // turn into {ax},{dx}.
20807   if (Res.second->hasType(VT))
20808     return Res;   // Correct type already, nothing to do.
20809
20810   // All of the single-register GCC register classes map their values onto
20811   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20812   // really want an 8-bit or 32-bit register, map to the appropriate register
20813   // class and return the appropriate register.
20814   if (Res.second == &X86::GR16RegClass) {
20815     if (VT == MVT::i8 || VT == MVT::i1) {
20816       unsigned DestReg = 0;
20817       switch (Res.first) {
20818       default: break;
20819       case X86::AX: DestReg = X86::AL; break;
20820       case X86::DX: DestReg = X86::DL; break;
20821       case X86::CX: DestReg = X86::CL; break;
20822       case X86::BX: DestReg = X86::BL; break;
20823       }
20824       if (DestReg) {
20825         Res.first = DestReg;
20826         Res.second = &X86::GR8RegClass;
20827       }
20828     } else if (VT == MVT::i32 || VT == MVT::f32) {
20829       unsigned DestReg = 0;
20830       switch (Res.first) {
20831       default: break;
20832       case X86::AX: DestReg = X86::EAX; break;
20833       case X86::DX: DestReg = X86::EDX; break;
20834       case X86::CX: DestReg = X86::ECX; break;
20835       case X86::BX: DestReg = X86::EBX; break;
20836       case X86::SI: DestReg = X86::ESI; break;
20837       case X86::DI: DestReg = X86::EDI; break;
20838       case X86::BP: DestReg = X86::EBP; break;
20839       case X86::SP: DestReg = X86::ESP; break;
20840       }
20841       if (DestReg) {
20842         Res.first = DestReg;
20843         Res.second = &X86::GR32RegClass;
20844       }
20845     } else if (VT == MVT::i64 || VT == MVT::f64) {
20846       unsigned DestReg = 0;
20847       switch (Res.first) {
20848       default: break;
20849       case X86::AX: DestReg = X86::RAX; break;
20850       case X86::DX: DestReg = X86::RDX; break;
20851       case X86::CX: DestReg = X86::RCX; break;
20852       case X86::BX: DestReg = X86::RBX; break;
20853       case X86::SI: DestReg = X86::RSI; break;
20854       case X86::DI: DestReg = X86::RDI; break;
20855       case X86::BP: DestReg = X86::RBP; break;
20856       case X86::SP: DestReg = X86::RSP; break;
20857       }
20858       if (DestReg) {
20859         Res.first = DestReg;
20860         Res.second = &X86::GR64RegClass;
20861       }
20862     }
20863   } else if (Res.second == &X86::FR32RegClass ||
20864              Res.second == &X86::FR64RegClass ||
20865              Res.second == &X86::VR128RegClass ||
20866              Res.second == &X86::VR256RegClass ||
20867              Res.second == &X86::FR32XRegClass ||
20868              Res.second == &X86::FR64XRegClass ||
20869              Res.second == &X86::VR128XRegClass ||
20870              Res.second == &X86::VR256XRegClass ||
20871              Res.second == &X86::VR512RegClass) {
20872     // Handle references to XMM physical registers that got mapped into the
20873     // wrong class.  This can happen with constraints like {xmm0} where the
20874     // target independent register mapper will just pick the first match it can
20875     // find, ignoring the required type.
20876
20877     if (VT == MVT::f32 || VT == MVT::i32)
20878       Res.second = &X86::FR32RegClass;
20879     else if (VT == MVT::f64 || VT == MVT::i64)
20880       Res.second = &X86::FR64RegClass;
20881     else if (X86::VR128RegClass.hasType(VT))
20882       Res.second = &X86::VR128RegClass;
20883     else if (X86::VR256RegClass.hasType(VT))
20884       Res.second = &X86::VR256RegClass;
20885     else if (X86::VR512RegClass.hasType(VT))
20886       Res.second = &X86::VR512RegClass;
20887   }
20888
20889   return Res;
20890 }
20891
20892 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20893                                             Type *Ty) const {
20894   // Scaling factors are not free at all.
20895   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20896   // will take 2 allocations instead of 1 for plain addressing mode,
20897   // i.e. inst (reg1).
20898   if (isLegalAddressingMode(AM, Ty))
20899     // Scale represents reg2 * scale, thus account for 1
20900     // as soon as we use a second register.
20901     return AM.Scale != 0;
20902   return -1;
20903 }