Add 'musttail' marker to call instructions
[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, 0);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
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::UMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::SDIVREM, VT, Expand);
831     setOperationAction(ISD::UDIVREM, VT, Expand);
832     setOperationAction(ISD::FPOW, VT, Expand);
833     setOperationAction(ISD::CTPOP, VT, Expand);
834     setOperationAction(ISD::CTTZ, VT, Expand);
835     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836     setOperationAction(ISD::CTLZ, VT, Expand);
837     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::SHL, VT, Expand);
839     setOperationAction(ISD::SRA, VT, Expand);
840     setOperationAction(ISD::SRL, VT, Expand);
841     setOperationAction(ISD::ROTL, VT, Expand);
842     setOperationAction(ISD::ROTR, VT, Expand);
843     setOperationAction(ISD::BSWAP, VT, Expand);
844     setOperationAction(ISD::SETCC, VT, Expand);
845     setOperationAction(ISD::FLOG, VT, Expand);
846     setOperationAction(ISD::FLOG2, VT, Expand);
847     setOperationAction(ISD::FLOG10, VT, Expand);
848     setOperationAction(ISD::FEXP, VT, Expand);
849     setOperationAction(ISD::FEXP2, VT, Expand);
850     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855     setOperationAction(ISD::TRUNCATE, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859     setOperationAction(ISD::VSELECT, VT, Expand);
860     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
861              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
862       setTruncStoreAction(VT,
863                           (MVT::SimpleValueType)InnerVT, Expand);
864     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
865     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
866     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
867   }
868
869   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
870   // with -msoft-float, disable use of MMX as well.
871   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
872     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
873     // No operations on x86mmx supported, everything uses intrinsics.
874   }
875
876   // MMX-sized vectors (other than x86mmx) are expected to be expanded
877   // into smaller operations.
878   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
879   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
880   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
881   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
882   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
883   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
884   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
885   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
886   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
887   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
888   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
889   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
890   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
891   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
892   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
893   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
894   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
898   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
899   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
900   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
903   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
907
908   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
909     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
910
911     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
912     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
916     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
917     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
918     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
919     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
920     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
921     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
923   }
924
925   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
926     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
927
928     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
929     // registers cannot be used even for integer operations.
930     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
931     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
932     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
933     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
934
935     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
936     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
937     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
938     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
939     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
940     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
941     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
942     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
943     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
944     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
945     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
946     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
947     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
948     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
951     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
952     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
953
954     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
955     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
956     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
958
959     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
960     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
964
965     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
966     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967       MVT VT = (MVT::SimpleValueType)i;
968       // Do not attempt to custom lower non-power-of-2 vectors
969       if (!isPowerOf2_32(VT.getVectorNumElements()))
970         continue;
971       // Do not attempt to custom lower non-128-bit vectors
972       if (!VT.is128BitVector())
973         continue;
974       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
975       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
976       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
977     }
978
979     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
980     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
981     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
982     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
985
986     if (Subtarget->is64Bit()) {
987       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
988       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
989     }
990
991     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
992     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
993       MVT VT = (MVT::SimpleValueType)i;
994
995       // Do not attempt to promote non-128-bit vectors
996       if (!VT.is128BitVector())
997         continue;
998
999       setOperationAction(ISD::AND,    VT, Promote);
1000       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1001       setOperationAction(ISD::OR,     VT, Promote);
1002       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1003       setOperationAction(ISD::XOR,    VT, Promote);
1004       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1005       setOperationAction(ISD::LOAD,   VT, Promote);
1006       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1007       setOperationAction(ISD::SELECT, VT, Promote);
1008       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1009     }
1010
1011     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1012
1013     // Custom lower v2i64 and v2f64 selects.
1014     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1015     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1016     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1017     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1018
1019     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1020     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1021
1022     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1023     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1024     // As there is no 64-bit GPR available, we need build a special custom
1025     // sequence to convert from v2i32 to v2f32.
1026     if (!Subtarget->is64Bit())
1027       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1028
1029     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1030     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1031
1032     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1033   }
1034
1035   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1036     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1037     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1038     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1041     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1042     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1043     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1046
1047     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1048     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1049     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1057
1058     // FIXME: Do we need to handle scalar-to-vector here?
1059     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1060
1061     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1062     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1063     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1066
1067     // i8 and i16 vectors are custom , because the source register and source
1068     // source memory operand types are not the same width.  f32 vectors are
1069     // custom since the immediate controlling the insert encodes additional
1070     // information.
1071     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1072     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1075
1076     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1077     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1080
1081     // FIXME: these should be Legal but thats only for the case where
1082     // the index is constant.  For now custom expand to deal with that.
1083     if (Subtarget->is64Bit()) {
1084       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1085       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1086     }
1087   }
1088
1089   if (Subtarget->hasSSE2()) {
1090     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1091     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1092
1093     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1094     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1095
1096     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1098
1099     // In the customized shift lowering, the legal cases in AVX2 will be
1100     // recognized.
1101     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1102     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1103
1104     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1105     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1106
1107     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1110     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1111   }
1112
1113   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1114     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1115     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1116     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1120
1121     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1122     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1123     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1124
1125     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1126     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1127     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1130     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1131     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1135     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1136     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1137
1138     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1139     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1140     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1143     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1144     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1148     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1149     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1150
1151     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1152     // even though v8i16 is a legal type.
1153     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1154     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1155     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1156
1157     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1160
1161     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1162     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1163
1164     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1165
1166     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1167     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1168
1169     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1176
1177     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1181
1182     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1183     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1185
1186     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1190
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1203
1204     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1209       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1211     }
1212
1213     if (Subtarget->hasInt256()) {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1227       // Don't lower v32i8 because there is no 128-bit byte mul
1228
1229       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1232     } else {
1233       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1236       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1237
1238       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1241       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1242
1243       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1244       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1245       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1246       // Don't lower v32i8 because there is no 128-bit byte mul
1247     }
1248
1249     // In the customized shift lowering, the legal cases in AVX2 will be
1250     // recognized.
1251     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1255     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1256
1257     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1258
1259     // Custom lower several nodes for 256-bit types.
1260     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262       MVT VT = (MVT::SimpleValueType)i;
1263
1264       // Extract subvector is special because the value type
1265       // (result) is 128-bit but the source is 256-bit wide.
1266       if (VT.is128BitVector())
1267         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1268
1269       // Do not attempt to custom lower other non-256-bit vectors
1270       if (!VT.is256BitVector())
1271         continue;
1272
1273       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1274       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1275       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1276       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1278       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1279       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1280     }
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1310     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1311     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1312
1313     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1314     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1315     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1316     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1317     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1318     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1324
1325     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1330     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1331
1332     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1337     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1338     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1339     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1340     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1341
1342     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1343     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1344     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1346     if (Subtarget->is64Bit()) {
1347       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1348       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1349       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1350       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1351     }
1352     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1355     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1360     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1361     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1362
1363     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1369     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1370     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1373     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1376
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1383
1384     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1385     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1386
1387     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1388
1389     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1390     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1391     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1392     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1393     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1394     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1395     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1396     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1397     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1398
1399     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1400     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1403     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1404
1405     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1406
1407     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1408     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1409
1410     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1414     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1415
1416     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1417     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1418     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1419     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1420     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1421     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1422
1423     // Custom lower several nodes.
1424     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1425              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1426       MVT VT = (MVT::SimpleValueType)i;
1427
1428       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1429       // Extract subvector is special because the value type
1430       // (result) is 256/128-bit but the source is 512-bit wide.
1431       if (VT.is128BitVector() || VT.is256BitVector())
1432         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1433
1434       if (VT.getVectorElementType() == MVT::i1)
1435         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1436
1437       // Do not attempt to custom lower other non-512-bit vectors
1438       if (!VT.is512BitVector())
1439         continue;
1440
1441       if ( EltSize >= 32) {
1442         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1443         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1444         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1445         setOperationAction(ISD::VSELECT,             VT, Legal);
1446         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1447         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1448         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1449       }
1450     }
1451     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1452       MVT VT = (MVT::SimpleValueType)i;
1453
1454       // Do not attempt to promote non-256-bit vectors
1455       if (!VT.is512BitVector())
1456         continue;
1457
1458       setOperationAction(ISD::SELECT, VT, Promote);
1459       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1460     }
1461   }// has  AVX-512
1462
1463   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1464   // of this type with custom code.
1465   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1466            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1467     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1468                        Custom);
1469   }
1470
1471   // We want to custom lower some of our intrinsics.
1472   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1475   if (!Subtarget->is64Bit())
1476     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1477
1478   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1479   // handle type legalization for these operations here.
1480   //
1481   // FIXME: We really should do custom legalization for addition and
1482   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1483   // than generic legalization for 64-bit multiplication-with-overflow, though.
1484   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1485     // Add/Sub/Mul with overflow operations are custom lowered.
1486     MVT VT = IntVTs[i];
1487     setOperationAction(ISD::SADDO, VT, Custom);
1488     setOperationAction(ISD::UADDO, VT, Custom);
1489     setOperationAction(ISD::SSUBO, VT, Custom);
1490     setOperationAction(ISD::USUBO, VT, Custom);
1491     setOperationAction(ISD::SMULO, VT, Custom);
1492     setOperationAction(ISD::UMULO, VT, Custom);
1493   }
1494
1495   // There are no 8-bit 3-address imul/mul instructions
1496   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1497   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1498
1499   if (!Subtarget->is64Bit()) {
1500     // These libcalls are not available in 32-bit.
1501     setLibcallName(RTLIB::SHL_I128, 0);
1502     setLibcallName(RTLIB::SRL_I128, 0);
1503     setLibcallName(RTLIB::SRA_I128, 0);
1504   }
1505
1506   // Combine sin / cos into one node or libcall if possible.
1507   if (Subtarget->hasSinCos()) {
1508     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1509     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1510     if (Subtarget->isTargetDarwin()) {
1511       // For MacOSX, we don't want to the normal expansion of a libcall to
1512       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1513       // traffic.
1514       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1515       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1516     }
1517   }
1518
1519   // We have target-specific dag combine patterns for the following nodes:
1520   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1521   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1522   setTargetDAGCombine(ISD::VSELECT);
1523   setTargetDAGCombine(ISD::SELECT);
1524   setTargetDAGCombine(ISD::SHL);
1525   setTargetDAGCombine(ISD::SRA);
1526   setTargetDAGCombine(ISD::SRL);
1527   setTargetDAGCombine(ISD::OR);
1528   setTargetDAGCombine(ISD::AND);
1529   setTargetDAGCombine(ISD::ADD);
1530   setTargetDAGCombine(ISD::FADD);
1531   setTargetDAGCombine(ISD::FSUB);
1532   setTargetDAGCombine(ISD::FMA);
1533   setTargetDAGCombine(ISD::SUB);
1534   setTargetDAGCombine(ISD::LOAD);
1535   setTargetDAGCombine(ISD::STORE);
1536   setTargetDAGCombine(ISD::ZERO_EXTEND);
1537   setTargetDAGCombine(ISD::ANY_EXTEND);
1538   setTargetDAGCombine(ISD::SIGN_EXTEND);
1539   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1540   setTargetDAGCombine(ISD::TRUNCATE);
1541   setTargetDAGCombine(ISD::SINT_TO_FP);
1542   setTargetDAGCombine(ISD::SETCC);
1543   if (Subtarget->is64Bit())
1544     setTargetDAGCombine(ISD::MUL);
1545   setTargetDAGCombine(ISD::XOR);
1546
1547   computeRegisterProperties();
1548
1549   // On Darwin, -Os means optimize for size without hurting performance,
1550   // do not reduce the limit.
1551   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1552   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1553   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1554   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1556   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1557   setPrefLoopAlignment(4); // 2^4 bytes.
1558
1559   // Predictable cmov don't hurt on atom because it's in-order.
1560   PredictableSelectIsExpensive = !Subtarget->isAtom();
1561
1562   setPrefFunctionAlignment(4); // 2^4 bytes.
1563 }
1564
1565 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1566   if (!VT.isVector())
1567     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1568
1569   if (Subtarget->hasAVX512())
1570     switch(VT.getVectorNumElements()) {
1571     case  8: return MVT::v8i1;
1572     case 16: return MVT::v16i1;
1573   }
1574
1575   return VT.changeVectorElementTypeToInteger();
1576 }
1577
1578 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1579 /// the desired ByVal argument alignment.
1580 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1581   if (MaxAlign == 16)
1582     return;
1583   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1584     if (VTy->getBitWidth() == 128)
1585       MaxAlign = 16;
1586   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1587     unsigned EltAlign = 0;
1588     getMaxByValAlign(ATy->getElementType(), EltAlign);
1589     if (EltAlign > MaxAlign)
1590       MaxAlign = EltAlign;
1591   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1592     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1593       unsigned EltAlign = 0;
1594       getMaxByValAlign(STy->getElementType(i), EltAlign);
1595       if (EltAlign > MaxAlign)
1596         MaxAlign = EltAlign;
1597       if (MaxAlign == 16)
1598         break;
1599     }
1600   }
1601 }
1602
1603 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1604 /// function arguments in the caller parameter area. For X86, aggregates
1605 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1606 /// are at 4-byte boundaries.
1607 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1608   if (Subtarget->is64Bit()) {
1609     // Max of 8 and alignment of type.
1610     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1611     if (TyAlign > 8)
1612       return TyAlign;
1613     return 8;
1614   }
1615
1616   unsigned Align = 4;
1617   if (Subtarget->hasSSE1())
1618     getMaxByValAlign(Ty, Align);
1619   return Align;
1620 }
1621
1622 /// getOptimalMemOpType - Returns the target specific optimal type for load
1623 /// and store operations as a result of memset, memcpy, and memmove
1624 /// lowering. If DstAlign is zero that means it's safe to destination
1625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1626 /// means there isn't a need to check it against alignment requirement,
1627 /// probably because the source does not need to be loaded. If 'IsMemset' is
1628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1630 /// source is constant so it does not need to be loaded.
1631 /// It returns EVT::Other if the type should be determined using generic
1632 /// target-independent logic.
1633 EVT
1634 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1635                                        unsigned DstAlign, unsigned SrcAlign,
1636                                        bool IsMemset, bool ZeroMemset,
1637                                        bool MemcpyStrSrc,
1638                                        MachineFunction &MF) const {
1639   const Function *F = MF.getFunction();
1640   if ((!IsMemset || ZeroMemset) &&
1641       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1642                                        Attribute::NoImplicitFloat)) {
1643     if (Size >= 16 &&
1644         (Subtarget->isUnalignedMemAccessFast() ||
1645          ((DstAlign == 0 || DstAlign >= 16) &&
1646           (SrcAlign == 0 || SrcAlign >= 16)))) {
1647       if (Size >= 32) {
1648         if (Subtarget->hasInt256())
1649           return MVT::v8i32;
1650         if (Subtarget->hasFp256())
1651           return MVT::v8f32;
1652       }
1653       if (Subtarget->hasSSE2())
1654         return MVT::v4i32;
1655       if (Subtarget->hasSSE1())
1656         return MVT::v4f32;
1657     } else if (!MemcpyStrSrc && Size >= 8 &&
1658                !Subtarget->is64Bit() &&
1659                Subtarget->hasSSE2()) {
1660       // Do not use f64 to lower memcpy if source is string constant. It's
1661       // better to use i32 to avoid the loads.
1662       return MVT::f64;
1663     }
1664   }
1665   if (Subtarget->is64Bit() && Size >= 8)
1666     return MVT::i64;
1667   return MVT::i32;
1668 }
1669
1670 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1671   if (VT == MVT::f32)
1672     return X86ScalarSSEf32;
1673   else if (VT == MVT::f64)
1674     return X86ScalarSSEf64;
1675   return true;
1676 }
1677
1678 bool
1679 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1680                                                  unsigned,
1681                                                  bool *Fast) const {
1682   if (Fast)
1683     *Fast = Subtarget->isUnalignedMemAccessFast();
1684   return true;
1685 }
1686
1687 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1688 /// current function.  The returned value is a member of the
1689 /// MachineJumpTableInfo::JTEntryKind enum.
1690 unsigned X86TargetLowering::getJumpTableEncoding() const {
1691   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1692   // symbol.
1693   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1694       Subtarget->isPICStyleGOT())
1695     return MachineJumpTableInfo::EK_Custom32;
1696
1697   // Otherwise, use the normal jump table encoding heuristics.
1698   return TargetLowering::getJumpTableEncoding();
1699 }
1700
1701 const MCExpr *
1702 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1703                                              const MachineBasicBlock *MBB,
1704                                              unsigned uid,MCContext &Ctx) const{
1705   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1706          Subtarget->isPICStyleGOT());
1707   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1708   // entries.
1709   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1710                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1711 }
1712
1713 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1714 /// jumptable.
1715 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1716                                                     SelectionDAG &DAG) const {
1717   if (!Subtarget->is64Bit())
1718     // This doesn't have SDLoc associated with it, but is not really the
1719     // same as a Register.
1720     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1721   return Table;
1722 }
1723
1724 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1725 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1726 /// MCExpr.
1727 const MCExpr *X86TargetLowering::
1728 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1729                              MCContext &Ctx) const {
1730   // X86-64 uses RIP relative addressing based on the jump table label.
1731   if (Subtarget->isPICStyleRIPRel())
1732     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1733
1734   // Otherwise, the reference is relative to the PIC base.
1735   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1736 }
1737
1738 // FIXME: Why this routine is here? Move to RegInfo!
1739 std::pair<const TargetRegisterClass*, uint8_t>
1740 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1741   const TargetRegisterClass *RRC = 0;
1742   uint8_t Cost = 1;
1743   switch (VT.SimpleTy) {
1744   default:
1745     return TargetLowering::findRepresentativeClass(VT);
1746   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1747     RRC = Subtarget->is64Bit() ?
1748       (const TargetRegisterClass*)&X86::GR64RegClass :
1749       (const TargetRegisterClass*)&X86::GR32RegClass;
1750     break;
1751   case MVT::x86mmx:
1752     RRC = &X86::VR64RegClass;
1753     break;
1754   case MVT::f32: case MVT::f64:
1755   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1756   case MVT::v4f32: case MVT::v2f64:
1757   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1758   case MVT::v4f64:
1759     RRC = &X86::VR128RegClass;
1760     break;
1761   }
1762   return std::make_pair(RRC, Cost);
1763 }
1764
1765 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1766                                                unsigned &Offset) const {
1767   if (!Subtarget->isTargetLinux())
1768     return false;
1769
1770   if (Subtarget->is64Bit()) {
1771     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1772     Offset = 0x28;
1773     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1774       AddressSpace = 256;
1775     else
1776       AddressSpace = 257;
1777   } else {
1778     // %gs:0x14 on i386
1779     Offset = 0x14;
1780     AddressSpace = 256;
1781   }
1782   return true;
1783 }
1784
1785 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1786                                             unsigned DestAS) const {
1787   assert(SrcAS != DestAS && "Expected different address spaces!");
1788
1789   return SrcAS < 256 && DestAS < 256;
1790 }
1791
1792 //===----------------------------------------------------------------------===//
1793 //               Return Value Calling Convention Implementation
1794 //===----------------------------------------------------------------------===//
1795
1796 #include "X86GenCallingConv.inc"
1797
1798 bool
1799 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1800                                   MachineFunction &MF, bool isVarArg,
1801                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1802                         LLVMContext &Context) const {
1803   SmallVector<CCValAssign, 16> RVLocs;
1804   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1805                  RVLocs, Context);
1806   return CCInfo.CheckReturn(Outs, RetCC_X86);
1807 }
1808
1809 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1810   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1811   return ScratchRegs;
1812 }
1813
1814 SDValue
1815 X86TargetLowering::LowerReturn(SDValue Chain,
1816                                CallingConv::ID CallConv, bool isVarArg,
1817                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1818                                const SmallVectorImpl<SDValue> &OutVals,
1819                                SDLoc dl, SelectionDAG &DAG) const {
1820   MachineFunction &MF = DAG.getMachineFunction();
1821   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1822
1823   SmallVector<CCValAssign, 16> RVLocs;
1824   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825                  RVLocs, *DAG.getContext());
1826   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1827
1828   SDValue Flag;
1829   SmallVector<SDValue, 6> RetOps;
1830   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1831   // Operand #1 = Bytes To Pop
1832   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1833                    MVT::i16));
1834
1835   // Copy the result values into the output registers.
1836   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1837     CCValAssign &VA = RVLocs[i];
1838     assert(VA.isRegLoc() && "Can only return in registers!");
1839     SDValue ValToCopy = OutVals[i];
1840     EVT ValVT = ValToCopy.getValueType();
1841
1842     // Promote values to the appropriate types
1843     if (VA.getLocInfo() == CCValAssign::SExt)
1844       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845     else if (VA.getLocInfo() == CCValAssign::ZExt)
1846       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847     else if (VA.getLocInfo() == CCValAssign::AExt)
1848       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849     else if (VA.getLocInfo() == CCValAssign::BCvt)
1850       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1851
1852     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1853            "Unexpected FP-extend for return value.");  
1854
1855     // If this is x86-64, and we disabled SSE, we can't return FP values,
1856     // or SSE or MMX vectors.
1857     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1858          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1859           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1860       report_fatal_error("SSE register return with SSE disabled");
1861     }
1862     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1863     // llvm-gcc has never done it right and no one has noticed, so this
1864     // should be OK for now.
1865     if (ValVT == MVT::f64 &&
1866         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1867       report_fatal_error("SSE2 register return with SSE2 disabled");
1868
1869     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1870     // the RET instruction and handled by the FP Stackifier.
1871     if (VA.getLocReg() == X86::ST0 ||
1872         VA.getLocReg() == X86::ST1) {
1873       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1874       // change the value to the FP stack register class.
1875       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1876         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1877       RetOps.push_back(ValToCopy);
1878       // Don't emit a copytoreg.
1879       continue;
1880     }
1881
1882     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1883     // which is returned in RAX / RDX.
1884     if (Subtarget->is64Bit()) {
1885       if (ValVT == MVT::x86mmx) {
1886         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1887           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1888           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1889                                   ValToCopy);
1890           // If we don't have SSE2 available, convert to v4f32 so the generated
1891           // register is legal.
1892           if (!Subtarget->hasSSE2())
1893             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1894         }
1895       }
1896     }
1897
1898     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1899     Flag = Chain.getValue(1);
1900     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1901   }
1902
1903   // The x86-64 ABIs require that for returning structs by value we copy
1904   // the sret argument into %rax/%eax (depending on ABI) for the return.
1905   // Win32 requires us to put the sret argument to %eax as well.
1906   // We saved the argument into a virtual register in the entry block,
1907   // so now we copy the value out and into %rax/%eax.
1908   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1909       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1910     MachineFunction &MF = DAG.getMachineFunction();
1911     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1912     unsigned Reg = FuncInfo->getSRetReturnReg();
1913     assert(Reg &&
1914            "SRetReturnReg should have been set in LowerFormalArguments().");
1915     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1916
1917     unsigned RetValReg
1918         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1919           X86::RAX : X86::EAX;
1920     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1921     Flag = Chain.getValue(1);
1922
1923     // RAX/EAX now acts like a return value.
1924     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1925   }
1926
1927   RetOps[0] = Chain;  // Update chain.
1928
1929   // Add the flag if we have it.
1930   if (Flag.getNode())
1931     RetOps.push_back(Flag);
1932
1933   return DAG.getNode(X86ISD::RET_FLAG, dl,
1934                      MVT::Other, &RetOps[0], RetOps.size());
1935 }
1936
1937 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1938   if (N->getNumValues() != 1)
1939     return false;
1940   if (!N->hasNUsesOfValue(1, 0))
1941     return false;
1942
1943   SDValue TCChain = Chain;
1944   SDNode *Copy = *N->use_begin();
1945   if (Copy->getOpcode() == ISD::CopyToReg) {
1946     // If the copy has a glue operand, we conservatively assume it isn't safe to
1947     // perform a tail call.
1948     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1949       return false;
1950     TCChain = Copy->getOperand(0);
1951   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1952     return false;
1953
1954   bool HasRet = false;
1955   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1956        UI != UE; ++UI) {
1957     if (UI->getOpcode() != X86ISD::RET_FLAG)
1958       return false;
1959     HasRet = true;
1960   }
1961
1962   if (!HasRet)
1963     return false;
1964
1965   Chain = TCChain;
1966   return true;
1967 }
1968
1969 MVT
1970 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1971                                             ISD::NodeType ExtendKind) const {
1972   MVT ReturnMVT;
1973   // TODO: Is this also valid on 32-bit?
1974   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1975     ReturnMVT = MVT::i8;
1976   else
1977     ReturnMVT = MVT::i32;
1978
1979   MVT MinVT = getRegisterType(ReturnMVT);
1980   return VT.bitsLT(MinVT) ? MinVT : VT;
1981 }
1982
1983 /// LowerCallResult - Lower the result values of a call into the
1984 /// appropriate copies out of appropriate physical registers.
1985 ///
1986 SDValue
1987 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1988                                    CallingConv::ID CallConv, bool isVarArg,
1989                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1990                                    SDLoc dl, SelectionDAG &DAG,
1991                                    SmallVectorImpl<SDValue> &InVals) const {
1992
1993   // Assign locations to each value returned by this call.
1994   SmallVector<CCValAssign, 16> RVLocs;
1995   bool Is64Bit = Subtarget->is64Bit();
1996   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1997                  getTargetMachine(), RVLocs, *DAG.getContext());
1998   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1999
2000   // Copy all of the result registers out of their specified physreg.
2001   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2002     CCValAssign &VA = RVLocs[i];
2003     EVT CopyVT = VA.getValVT();
2004
2005     // If this is x86-64, and we disabled SSE, we can't return FP values
2006     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2007         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2008       report_fatal_error("SSE register return with SSE disabled");
2009     }
2010
2011     SDValue Val;
2012
2013     // If this is a call to a function that returns an fp value on the floating
2014     // point stack, we must guarantee the value is popped from the stack, so
2015     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2016     // if the return value is not used. We use the FpPOP_RETVAL instruction
2017     // instead.
2018     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2019       // If we prefer to use the value in xmm registers, copy it out as f80 and
2020       // use a truncate to move it from fp stack reg to xmm reg.
2021       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2022       SDValue Ops[] = { Chain, InFlag };
2023       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2024                                          MVT::Other, MVT::Glue, Ops), 1);
2025       Val = Chain.getValue(0);
2026
2027       // Round the f80 to the right size, which also moves it to the appropriate
2028       // xmm register.
2029       if (CopyVT != VA.getValVT())
2030         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2031                           // This truncation won't change the value.
2032                           DAG.getIntPtrConstant(1));
2033     } else {
2034       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2035                                  CopyVT, InFlag).getValue(1);
2036       Val = Chain.getValue(0);
2037     }
2038     InFlag = Chain.getValue(2);
2039     InVals.push_back(Val);
2040   }
2041
2042   return Chain;
2043 }
2044
2045 //===----------------------------------------------------------------------===//
2046 //                C & StdCall & Fast Calling Convention implementation
2047 //===----------------------------------------------------------------------===//
2048 //  StdCall calling convention seems to be standard for many Windows' API
2049 //  routines and around. It differs from C calling convention just a little:
2050 //  callee should clean up the stack, not caller. Symbols should be also
2051 //  decorated in some fancy way :) It doesn't support any vector arguments.
2052 //  For info on fast calling convention see Fast Calling Convention (tail call)
2053 //  implementation LowerX86_32FastCCCallTo.
2054
2055 /// CallIsStructReturn - Determines whether a call uses struct return
2056 /// semantics.
2057 enum StructReturnType {
2058   NotStructReturn,
2059   RegStructReturn,
2060   StackStructReturn
2061 };
2062 static StructReturnType
2063 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2064   if (Outs.empty())
2065     return NotStructReturn;
2066
2067   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2068   if (!Flags.isSRet())
2069     return NotStructReturn;
2070   if (Flags.isInReg())
2071     return RegStructReturn;
2072   return StackStructReturn;
2073 }
2074
2075 /// ArgsAreStructReturn - Determines whether a function uses struct
2076 /// return semantics.
2077 static StructReturnType
2078 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2079   if (Ins.empty())
2080     return NotStructReturn;
2081
2082   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2083   if (!Flags.isSRet())
2084     return NotStructReturn;
2085   if (Flags.isInReg())
2086     return RegStructReturn;
2087   return StackStructReturn;
2088 }
2089
2090 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2091 /// by "Src" to address "Dst" with size and alignment information specified by
2092 /// the specific parameter attribute. The copy will be passed as a byval
2093 /// function parameter.
2094 static SDValue
2095 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2096                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2097                           SDLoc dl) {
2098   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2099
2100   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2101                        /*isVolatile*/false, /*AlwaysInline=*/true,
2102                        MachinePointerInfo(), MachinePointerInfo());
2103 }
2104
2105 /// IsTailCallConvention - Return true if the calling convention is one that
2106 /// supports tail call optimization.
2107 static bool IsTailCallConvention(CallingConv::ID CC) {
2108   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2109           CC == CallingConv::HiPE);
2110 }
2111
2112 /// \brief Return true if the calling convention is a C calling convention.
2113 static bool IsCCallConvention(CallingConv::ID CC) {
2114   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2115           CC == CallingConv::X86_64_SysV);
2116 }
2117
2118 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2119   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2120     return false;
2121
2122   CallSite CS(CI);
2123   CallingConv::ID CalleeCC = CS.getCallingConv();
2124   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2125     return false;
2126
2127   return true;
2128 }
2129
2130 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2131 /// a tailcall target by changing its ABI.
2132 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2133                                    bool GuaranteedTailCallOpt) {
2134   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2135 }
2136
2137 SDValue
2138 X86TargetLowering::LowerMemArgument(SDValue Chain,
2139                                     CallingConv::ID CallConv,
2140                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2141                                     SDLoc dl, SelectionDAG &DAG,
2142                                     const CCValAssign &VA,
2143                                     MachineFrameInfo *MFI,
2144                                     unsigned i) const {
2145   // Create the nodes corresponding to a load from this parameter slot.
2146   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2147   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2148                               getTargetMachine().Options.GuaranteedTailCallOpt);
2149   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2150   EVT ValVT;
2151
2152   // If value is passed by pointer we have address passed instead of the value
2153   // itself.
2154   if (VA.getLocInfo() == CCValAssign::Indirect)
2155     ValVT = VA.getLocVT();
2156   else
2157     ValVT = VA.getValVT();
2158
2159   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2160   // changed with more analysis.
2161   // In case of tail call optimization mark all arguments mutable. Since they
2162   // could be overwritten by lowering of arguments in case of a tail call.
2163   if (Flags.isByVal()) {
2164     unsigned Bytes = Flags.getByValSize();
2165     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2166     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2167     return DAG.getFrameIndex(FI, getPointerTy());
2168   } else {
2169     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2170                                     VA.getLocMemOffset(), isImmutable);
2171     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2172     return DAG.getLoad(ValVT, dl, Chain, FIN,
2173                        MachinePointerInfo::getFixedStack(FI),
2174                        false, false, false, 0);
2175   }
2176 }
2177
2178 SDValue
2179 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2180                                         CallingConv::ID CallConv,
2181                                         bool isVarArg,
2182                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2183                                         SDLoc dl,
2184                                         SelectionDAG &DAG,
2185                                         SmallVectorImpl<SDValue> &InVals)
2186                                           const {
2187   MachineFunction &MF = DAG.getMachineFunction();
2188   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2189
2190   const Function* Fn = MF.getFunction();
2191   if (Fn->hasExternalLinkage() &&
2192       Subtarget->isTargetCygMing() &&
2193       Fn->getName() == "main")
2194     FuncInfo->setForceFramePointer(true);
2195
2196   MachineFrameInfo *MFI = MF.getFrameInfo();
2197   bool Is64Bit = Subtarget->is64Bit();
2198   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2199
2200   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2201          "Var args not supported with calling convention fastcc, ghc or hipe");
2202
2203   // Assign locations to all of the incoming arguments.
2204   SmallVector<CCValAssign, 16> ArgLocs;
2205   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2206                  ArgLocs, *DAG.getContext());
2207
2208   // Allocate shadow area for Win64
2209   if (IsWin64)
2210     CCInfo.AllocateStack(32, 8);
2211
2212   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2213
2214   unsigned LastVal = ~0U;
2215   SDValue ArgValue;
2216   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217     CCValAssign &VA = ArgLocs[i];
2218     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2219     // places.
2220     assert(VA.getValNo() != LastVal &&
2221            "Don't support value assigned to multiple locs yet");
2222     (void)LastVal;
2223     LastVal = VA.getValNo();
2224
2225     if (VA.isRegLoc()) {
2226       EVT RegVT = VA.getLocVT();
2227       const TargetRegisterClass *RC;
2228       if (RegVT == MVT::i32)
2229         RC = &X86::GR32RegClass;
2230       else if (Is64Bit && RegVT == MVT::i64)
2231         RC = &X86::GR64RegClass;
2232       else if (RegVT == MVT::f32)
2233         RC = &X86::FR32RegClass;
2234       else if (RegVT == MVT::f64)
2235         RC = &X86::FR64RegClass;
2236       else if (RegVT.is512BitVector())
2237         RC = &X86::VR512RegClass;
2238       else if (RegVT.is256BitVector())
2239         RC = &X86::VR256RegClass;
2240       else if (RegVT.is128BitVector())
2241         RC = &X86::VR128RegClass;
2242       else if (RegVT == MVT::x86mmx)
2243         RC = &X86::VR64RegClass;
2244       else if (RegVT == MVT::i1)
2245         RC = &X86::VK1RegClass;
2246       else if (RegVT == MVT::v8i1)
2247         RC = &X86::VK8RegClass;
2248       else if (RegVT == MVT::v16i1)
2249         RC = &X86::VK16RegClass;
2250       else
2251         llvm_unreachable("Unknown argument type!");
2252
2253       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2254       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2255
2256       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2257       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2258       // right size.
2259       if (VA.getLocInfo() == CCValAssign::SExt)
2260         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2261                                DAG.getValueType(VA.getValVT()));
2262       else if (VA.getLocInfo() == CCValAssign::ZExt)
2263         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2264                                DAG.getValueType(VA.getValVT()));
2265       else if (VA.getLocInfo() == CCValAssign::BCvt)
2266         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2267
2268       if (VA.isExtInLoc()) {
2269         // Handle MMX values passed in XMM regs.
2270         if (RegVT.isVector())
2271           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2272         else
2273           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2274       }
2275     } else {
2276       assert(VA.isMemLoc());
2277       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2278     }
2279
2280     // If value is passed via pointer - do a load.
2281     if (VA.getLocInfo() == CCValAssign::Indirect)
2282       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2283                              MachinePointerInfo(), false, false, false, 0);
2284
2285     InVals.push_back(ArgValue);
2286   }
2287
2288   // The x86-64 ABIs require that for returning structs by value we copy
2289   // the sret argument into %rax/%eax (depending on ABI) for the return.
2290   // Win32 requires us to put the sret argument to %eax as well.
2291   // Save the argument into a virtual register so that we can access it
2292   // from the return points.
2293   if (MF.getFunction()->hasStructRetAttr() &&
2294       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2295     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2296     unsigned Reg = FuncInfo->getSRetReturnReg();
2297     if (!Reg) {
2298       MVT PtrTy = getPointerTy();
2299       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2300       FuncInfo->setSRetReturnReg(Reg);
2301     }
2302     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2303     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2304   }
2305
2306   unsigned StackSize = CCInfo.getNextStackOffset();
2307   // Align stack specially for tail calls.
2308   if (FuncIsMadeTailCallSafe(CallConv,
2309                              MF.getTarget().Options.GuaranteedTailCallOpt))
2310     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2311
2312   // If the function takes variable number of arguments, make a frame index for
2313   // the start of the first vararg value... for expansion of llvm.va_start.
2314   if (isVarArg) {
2315     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2316                     CallConv != CallingConv::X86_ThisCall)) {
2317       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2318     }
2319     if (Is64Bit) {
2320       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2321
2322       // FIXME: We should really autogenerate these arrays
2323       static const MCPhysReg GPR64ArgRegsWin64[] = {
2324         X86::RCX, X86::RDX, X86::R8,  X86::R9
2325       };
2326       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2327         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2328       };
2329       static const MCPhysReg XMMArgRegs64Bit[] = {
2330         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2331         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2332       };
2333       const MCPhysReg *GPR64ArgRegs;
2334       unsigned NumXMMRegs = 0;
2335
2336       if (IsWin64) {
2337         // The XMM registers which might contain var arg parameters are shadowed
2338         // in their paired GPR.  So we only need to save the GPR to their home
2339         // slots.
2340         TotalNumIntRegs = 4;
2341         GPR64ArgRegs = GPR64ArgRegsWin64;
2342       } else {
2343         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2344         GPR64ArgRegs = GPR64ArgRegs64Bit;
2345
2346         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2347                                                 TotalNumXMMRegs);
2348       }
2349       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2350                                                        TotalNumIntRegs);
2351
2352       bool NoImplicitFloatOps = Fn->getAttributes().
2353         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2354       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2355              "SSE register cannot be used when SSE is disabled!");
2356       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2357                NoImplicitFloatOps) &&
2358              "SSE register cannot be used when SSE is disabled!");
2359       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360           !Subtarget->hasSSE1())
2361         // Kernel mode asks for SSE to be disabled, so don't push them
2362         // on the stack.
2363         TotalNumXMMRegs = 0;
2364
2365       if (IsWin64) {
2366         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2367         // Get to the caller-allocated home save location.  Add 8 to account
2368         // for the return address.
2369         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2370         FuncInfo->setRegSaveFrameIndex(
2371           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2372         // Fixup to set vararg frame on shadow area (4 x i64).
2373         if (NumIntRegs < 4)
2374           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2375       } else {
2376         // For X86-64, if there are vararg parameters that are passed via
2377         // registers, then we must store them to their spots on the stack so
2378         // they may be loaded by deferencing the result of va_next.
2379         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2380         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2381         FuncInfo->setRegSaveFrameIndex(
2382           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2383                                false));
2384       }
2385
2386       // Store the integer parameter registers.
2387       SmallVector<SDValue, 8> MemOps;
2388       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2389                                         getPointerTy());
2390       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2391       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2392         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2393                                   DAG.getIntPtrConstant(Offset));
2394         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2395                                      &X86::GR64RegClass);
2396         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2397         SDValue Store =
2398           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2399                        MachinePointerInfo::getFixedStack(
2400                          FuncInfo->getRegSaveFrameIndex(), Offset),
2401                        false, false, 0);
2402         MemOps.push_back(Store);
2403         Offset += 8;
2404       }
2405
2406       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2407         // Now store the XMM (fp + vector) parameter registers.
2408         SmallVector<SDValue, 11> SaveXMMOps;
2409         SaveXMMOps.push_back(Chain);
2410
2411         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2412         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2413         SaveXMMOps.push_back(ALVal);
2414
2415         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416                                FuncInfo->getRegSaveFrameIndex()));
2417         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418                                FuncInfo->getVarArgsFPOffset()));
2419
2420         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2421           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2422                                        &X86::VR128RegClass);
2423           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2424           SaveXMMOps.push_back(Val);
2425         }
2426         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2427                                      MVT::Other,
2428                                      &SaveXMMOps[0], SaveXMMOps.size()));
2429       }
2430
2431       if (!MemOps.empty())
2432         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2433                             &MemOps[0], MemOps.size());
2434     }
2435   }
2436
2437   // Some CCs need callee pop.
2438   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2441   } else {
2442     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443     // If this is an sret function, the return should pop the hidden pointer.
2444     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446         argsAreStructReturn(Ins) == StackStructReturn)
2447       FuncInfo->setBytesToPopOnReturn(4);
2448   }
2449
2450   if (!Is64Bit) {
2451     // RegSaveFrameIndex is X86-64 only.
2452     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453     if (CallConv == CallingConv::X86_FastCall ||
2454         CallConv == CallingConv::X86_ThisCall)
2455       // fastcc functions can't have varargs.
2456       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2457   }
2458
2459   FuncInfo->setArgumentStackSize(StackSize);
2460
2461   return Chain;
2462 }
2463
2464 SDValue
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466                                     SDValue StackPtr, SDValue Arg,
2467                                     SDLoc dl, SelectionDAG &DAG,
2468                                     const CCValAssign &VA,
2469                                     ISD::ArgFlagsTy Flags) const {
2470   unsigned LocMemOffset = VA.getLocMemOffset();
2471   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473   if (Flags.isByVal())
2474     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2475
2476   return DAG.getStore(Chain, dl, Arg, PtrOff,
2477                       MachinePointerInfo::getStack(LocMemOffset),
2478                       false, false, 0);
2479 }
2480
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2483 SDValue
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485                                            SDValue &OutRetAddr, SDValue Chain,
2486                                            bool IsTailCall, bool Is64Bit,
2487                                            int FPDiff, SDLoc dl) const {
2488   // Adjust the Return address stack slot.
2489   EVT VT = getPointerTy();
2490   OutRetAddr = getReturnAddressFrameIndex(DAG);
2491
2492   // Load the "old" Return address.
2493   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494                            false, false, false, 0);
2495   return SDValue(OutRetAddr.getNode(), 1);
2496 }
2497
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2500 static SDValue
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2504   // Store the return address to the appropriate stack slot.
2505   if (!FPDiff) return Chain;
2506   // Calculate the new stack slot for the return address.
2507   int NewReturnAddrFI =
2508     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2509                                          false);
2510   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2513                        false, false, 0);
2514   return Chain;
2515 }
2516
2517 SDValue
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519                              SmallVectorImpl<SDValue> &InVals) const {
2520   SelectionDAG &DAG                     = CLI.DAG;
2521   SDLoc &dl                             = CLI.DL;
2522   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2524   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2525   SDValue Chain                         = CLI.Chain;
2526   SDValue Callee                        = CLI.Callee;
2527   CallingConv::ID CallConv              = CLI.CallConv;
2528   bool &isTailCall                      = CLI.IsTailCall;
2529   bool isVarArg                         = CLI.IsVarArg;
2530
2531   MachineFunction &MF = DAG.getMachineFunction();
2532   bool Is64Bit        = Subtarget->is64Bit();
2533   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2534   StructReturnType SR = callIsStructReturn(Outs);
2535   bool IsSibcall      = false;
2536
2537   if (MF.getTarget().Options.DisableTailCalls)
2538     isTailCall = false;
2539
2540   if (isTailCall) {
2541     // Check if it's really possible to do a tail call.
2542     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543                     isVarArg, SR != NotStructReturn,
2544                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545                     Outs, OutVals, Ins, DAG);
2546
2547     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2548       report_fatal_error("failed to perform tail call elimination on a call "
2549                          "site marked musttail");
2550
2551     // Sibcalls are automatically detected tailcalls which do not require
2552     // ABI changes.
2553     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2554       IsSibcall = true;
2555
2556     if (isTailCall)
2557       ++NumTailCalls;
2558   }
2559
2560   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561          "Var args not supported with calling convention fastcc, ghc or hipe");
2562
2563   // Analyze operands of the call, assigning locations to each operand.
2564   SmallVector<CCValAssign, 16> ArgLocs;
2565   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2566                  ArgLocs, *DAG.getContext());
2567
2568   // Allocate shadow area for Win64
2569   if (IsWin64)
2570     CCInfo.AllocateStack(32, 8);
2571
2572   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573
2574   // Get a count of how many bytes are to be pushed on the stack.
2575   unsigned NumBytes = CCInfo.getNextStackOffset();
2576   if (IsSibcall)
2577     // This is a sibcall. The memory operands are available in caller's
2578     // own caller's stack.
2579     NumBytes = 0;
2580   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2581            IsTailCallConvention(CallConv))
2582     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2583
2584   int FPDiff = 0;
2585   if (isTailCall && !IsSibcall) {
2586     // Lower arguments at fp - stackoffset + fpdiff.
2587     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2588     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2589
2590     FPDiff = NumBytesCallerPushed - NumBytes;
2591
2592     // Set the delta of movement of the returnaddr stackslot.
2593     // But only set if delta is greater than previous delta.
2594     if (FPDiff < X86Info->getTCReturnAddrDelta())
2595       X86Info->setTCReturnAddrDelta(FPDiff);
2596   }
2597
2598   unsigned NumBytesToPush = NumBytes;
2599   unsigned NumBytesToPop = NumBytes;
2600
2601   // If we have an inalloca argument, all stack space has already been allocated
2602   // for us and be right at the top of the stack.  We don't support multiple
2603   // arguments passed in memory when using inalloca.
2604   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2605     NumBytesToPush = 0;
2606     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2607            "an inalloca argument must be the only memory argument");
2608   }
2609
2610   if (!IsSibcall)
2611     Chain = DAG.getCALLSEQ_START(
2612         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2613
2614   SDValue RetAddrFrIdx;
2615   // Load return address for tail calls.
2616   if (isTailCall && FPDiff)
2617     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2618                                     Is64Bit, FPDiff, dl);
2619
2620   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2621   SmallVector<SDValue, 8> MemOpChains;
2622   SDValue StackPtr;
2623
2624   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2625   // of tail call optimization arguments are handle later.
2626   const X86RegisterInfo *RegInfo =
2627     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2628   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629     // Skip inalloca arguments, they have already been written.
2630     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2631     if (Flags.isInAlloca())
2632       continue;
2633
2634     CCValAssign &VA = ArgLocs[i];
2635     EVT RegVT = VA.getLocVT();
2636     SDValue Arg = OutVals[i];
2637     bool isByVal = Flags.isByVal();
2638
2639     // Promote the value if needed.
2640     switch (VA.getLocInfo()) {
2641     default: llvm_unreachable("Unknown loc info!");
2642     case CCValAssign::Full: break;
2643     case CCValAssign::SExt:
2644       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2645       break;
2646     case CCValAssign::ZExt:
2647       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2648       break;
2649     case CCValAssign::AExt:
2650       if (RegVT.is128BitVector()) {
2651         // Special case: passing MMX values in XMM registers.
2652         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2653         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2654         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2655       } else
2656         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2657       break;
2658     case CCValAssign::BCvt:
2659       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2660       break;
2661     case CCValAssign::Indirect: {
2662       // Store the argument.
2663       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2664       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2665       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2666                            MachinePointerInfo::getFixedStack(FI),
2667                            false, false, 0);
2668       Arg = SpillSlot;
2669       break;
2670     }
2671     }
2672
2673     if (VA.isRegLoc()) {
2674       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2675       if (isVarArg && IsWin64) {
2676         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2677         // shadow reg if callee is a varargs function.
2678         unsigned ShadowReg = 0;
2679         switch (VA.getLocReg()) {
2680         case X86::XMM0: ShadowReg = X86::RCX; break;
2681         case X86::XMM1: ShadowReg = X86::RDX; break;
2682         case X86::XMM2: ShadowReg = X86::R8; break;
2683         case X86::XMM3: ShadowReg = X86::R9; break;
2684         }
2685         if (ShadowReg)
2686           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2687       }
2688     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2689       assert(VA.isMemLoc());
2690       if (StackPtr.getNode() == 0)
2691         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2692                                       getPointerTy());
2693       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2694                                              dl, DAG, VA, Flags));
2695     }
2696   }
2697
2698   if (!MemOpChains.empty())
2699     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2700                         &MemOpChains[0], MemOpChains.size());
2701
2702   if (Subtarget->isPICStyleGOT()) {
2703     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2704     // GOT pointer.
2705     if (!isTailCall) {
2706       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2707                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2708     } else {
2709       // If we are tail calling and generating PIC/GOT style code load the
2710       // address of the callee into ECX. The value in ecx is used as target of
2711       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2712       // for tail calls on PIC/GOT architectures. Normally we would just put the
2713       // address of GOT into ebx and then call target@PLT. But for tail calls
2714       // ebx would be restored (since ebx is callee saved) before jumping to the
2715       // target@PLT.
2716
2717       // Note: The actual moving to ECX is done further down.
2718       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2719       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2720           !G->getGlobal()->hasProtectedVisibility())
2721         Callee = LowerGlobalAddress(Callee, DAG);
2722       else if (isa<ExternalSymbolSDNode>(Callee))
2723         Callee = LowerExternalSymbol(Callee, DAG);
2724     }
2725   }
2726
2727   if (Is64Bit && isVarArg && !IsWin64) {
2728     // From AMD64 ABI document:
2729     // For calls that may call functions that use varargs or stdargs
2730     // (prototype-less calls or calls to functions containing ellipsis (...) in
2731     // the declaration) %al is used as hidden argument to specify the number
2732     // of SSE registers used. The contents of %al do not need to match exactly
2733     // the number of registers, but must be an ubound on the number of SSE
2734     // registers used and is in the range 0 - 8 inclusive.
2735
2736     // Count the number of XMM registers allocated.
2737     static const MCPhysReg XMMArgRegs[] = {
2738       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2739       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2740     };
2741     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2742     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2743            && "SSE registers cannot be used when SSE is disabled");
2744
2745     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2746                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2747   }
2748
2749   // For tail calls lower the arguments to the 'real' stack slot.
2750   if (isTailCall) {
2751     // Force all the incoming stack arguments to be loaded from the stack
2752     // before any new outgoing arguments are stored to the stack, because the
2753     // outgoing stack slots may alias the incoming argument stack slots, and
2754     // the alias isn't otherwise explicit. This is slightly more conservative
2755     // than necessary, because it means that each store effectively depends
2756     // on every argument instead of just those arguments it would clobber.
2757     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2758
2759     SmallVector<SDValue, 8> MemOpChains2;
2760     SDValue FIN;
2761     int FI = 0;
2762     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2763       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2764         CCValAssign &VA = ArgLocs[i];
2765         if (VA.isRegLoc())
2766           continue;
2767         assert(VA.isMemLoc());
2768         SDValue Arg = OutVals[i];
2769         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2770         // Create frame index.
2771         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2772         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2773         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2774         FIN = DAG.getFrameIndex(FI, getPointerTy());
2775
2776         if (Flags.isByVal()) {
2777           // Copy relative to framepointer.
2778           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2779           if (StackPtr.getNode() == 0)
2780             StackPtr = DAG.getCopyFromReg(Chain, dl,
2781                                           RegInfo->getStackRegister(),
2782                                           getPointerTy());
2783           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2784
2785           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2786                                                            ArgChain,
2787                                                            Flags, DAG, dl));
2788         } else {
2789           // Store relative to framepointer.
2790           MemOpChains2.push_back(
2791             DAG.getStore(ArgChain, dl, Arg, FIN,
2792                          MachinePointerInfo::getFixedStack(FI),
2793                          false, false, 0));
2794         }
2795       }
2796     }
2797
2798     if (!MemOpChains2.empty())
2799       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2800                           &MemOpChains2[0], MemOpChains2.size());
2801
2802     // Store the return address to the appropriate stack slot.
2803     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2804                                      getPointerTy(), RegInfo->getSlotSize(),
2805                                      FPDiff, dl);
2806   }
2807
2808   // Build a sequence of copy-to-reg nodes chained together with token chain
2809   // and flag operands which copy the outgoing args into registers.
2810   SDValue InFlag;
2811   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2812     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2813                              RegsToPass[i].second, InFlag);
2814     InFlag = Chain.getValue(1);
2815   }
2816
2817   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2818     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2819     // In the 64-bit large code model, we have to make all calls
2820     // through a register, since the call instruction's 32-bit
2821     // pc-relative offset may not be large enough to hold the whole
2822     // address.
2823   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2824     // If the callee is a GlobalAddress node (quite common, every direct call
2825     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2826     // it.
2827
2828     // We should use extra load for direct calls to dllimported functions in
2829     // non-JIT mode.
2830     const GlobalValue *GV = G->getGlobal();
2831     if (!GV->hasDLLImportStorageClass()) {
2832       unsigned char OpFlags = 0;
2833       bool ExtraLoad = false;
2834       unsigned WrapperKind = ISD::DELETED_NODE;
2835
2836       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2837       // external symbols most go through the PLT in PIC mode.  If the symbol
2838       // has hidden or protected visibility, or if it is static or local, then
2839       // we don't need to use the PLT - we can directly call it.
2840       if (Subtarget->isTargetELF() &&
2841           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2842           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2843         OpFlags = X86II::MO_PLT;
2844       } else if (Subtarget->isPICStyleStubAny() &&
2845                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2846                  (!Subtarget->getTargetTriple().isMacOSX() ||
2847                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2848         // PC-relative references to external symbols should go through $stub,
2849         // unless we're building with the leopard linker or later, which
2850         // automatically synthesizes these stubs.
2851         OpFlags = X86II::MO_DARWIN_STUB;
2852       } else if (Subtarget->isPICStyleRIPRel() &&
2853                  isa<Function>(GV) &&
2854                  cast<Function>(GV)->getAttributes().
2855                    hasAttribute(AttributeSet::FunctionIndex,
2856                                 Attribute::NonLazyBind)) {
2857         // If the function is marked as non-lazy, generate an indirect call
2858         // which loads from the GOT directly. This avoids runtime overhead
2859         // at the cost of eager binding (and one extra byte of encoding).
2860         OpFlags = X86II::MO_GOTPCREL;
2861         WrapperKind = X86ISD::WrapperRIP;
2862         ExtraLoad = true;
2863       }
2864
2865       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2866                                           G->getOffset(), OpFlags);
2867
2868       // Add a wrapper if needed.
2869       if (WrapperKind != ISD::DELETED_NODE)
2870         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2871       // Add extra indirection if needed.
2872       if (ExtraLoad)
2873         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2874                              MachinePointerInfo::getGOT(),
2875                              false, false, false, 0);
2876     }
2877   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2878     unsigned char OpFlags = 0;
2879
2880     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2881     // external symbols should go through the PLT.
2882     if (Subtarget->isTargetELF() &&
2883         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2884       OpFlags = X86II::MO_PLT;
2885     } else if (Subtarget->isPICStyleStubAny() &&
2886                (!Subtarget->getTargetTriple().isMacOSX() ||
2887                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2888       // PC-relative references to external symbols should go through $stub,
2889       // unless we're building with the leopard linker or later, which
2890       // automatically synthesizes these stubs.
2891       OpFlags = X86II::MO_DARWIN_STUB;
2892     }
2893
2894     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2895                                          OpFlags);
2896   }
2897
2898   // Returns a chain & a flag for retval copy to use.
2899   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2900   SmallVector<SDValue, 8> Ops;
2901
2902   if (!IsSibcall && isTailCall) {
2903     Chain = DAG.getCALLSEQ_END(Chain,
2904                                DAG.getIntPtrConstant(NumBytesToPop, true),
2905                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2906     InFlag = Chain.getValue(1);
2907   }
2908
2909   Ops.push_back(Chain);
2910   Ops.push_back(Callee);
2911
2912   if (isTailCall)
2913     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2914
2915   // Add argument registers to the end of the list so that they are known live
2916   // into the call.
2917   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2918     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2919                                   RegsToPass[i].second.getValueType()));
2920
2921   // Add a register mask operand representing the call-preserved registers.
2922   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2923   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2924   assert(Mask && "Missing call preserved mask for calling convention");
2925   Ops.push_back(DAG.getRegisterMask(Mask));
2926
2927   if (InFlag.getNode())
2928     Ops.push_back(InFlag);
2929
2930   if (isTailCall) {
2931     // We used to do:
2932     //// If this is the first return lowered for this function, add the regs
2933     //// to the liveout set for the function.
2934     // This isn't right, although it's probably harmless on x86; liveouts
2935     // should be computed from returns not tail calls.  Consider a void
2936     // function making a tail call to a function returning int.
2937     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2938   }
2939
2940   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2941   InFlag = Chain.getValue(1);
2942
2943   // Create the CALLSEQ_END node.
2944   unsigned NumBytesForCalleeToPop;
2945   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2946                        getTargetMachine().Options.GuaranteedTailCallOpt))
2947     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2948   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2949            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950            SR == StackStructReturn)
2951     // If this is a call to a struct-return function, the callee
2952     // pops the hidden struct pointer, so we have to push it back.
2953     // This is common for Darwin/X86, Linux & Mingw32 targets.
2954     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2955     NumBytesForCalleeToPop = 4;
2956   else
2957     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2958
2959   // Returns a flag for retval copy to use.
2960   if (!IsSibcall) {
2961     Chain = DAG.getCALLSEQ_END(Chain,
2962                                DAG.getIntPtrConstant(NumBytesToPop, true),
2963                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2964                                                      true),
2965                                InFlag, dl);
2966     InFlag = Chain.getValue(1);
2967   }
2968
2969   // Handle result values, copying them out of physregs into vregs that we
2970   // return.
2971   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2972                          Ins, dl, DAG, InVals);
2973 }
2974
2975 //===----------------------------------------------------------------------===//
2976 //                Fast Calling Convention (tail call) implementation
2977 //===----------------------------------------------------------------------===//
2978
2979 //  Like std call, callee cleans arguments, convention except that ECX is
2980 //  reserved for storing the tail called function address. Only 2 registers are
2981 //  free for argument passing (inreg). Tail call optimization is performed
2982 //  provided:
2983 //                * tailcallopt is enabled
2984 //                * caller/callee are fastcc
2985 //  On X86_64 architecture with GOT-style position independent code only local
2986 //  (within module) calls are supported at the moment.
2987 //  To keep the stack aligned according to platform abi the function
2988 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2989 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2990 //  If a tail called function callee has more arguments than the caller the
2991 //  caller needs to make sure that there is room to move the RETADDR to. This is
2992 //  achieved by reserving an area the size of the argument delta right after the
2993 //  original REtADDR, but before the saved framepointer or the spilled registers
2994 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2995 //  stack layout:
2996 //    arg1
2997 //    arg2
2998 //    RETADDR
2999 //    [ new RETADDR
3000 //      move area ]
3001 //    (possible EBP)
3002 //    ESI
3003 //    EDI
3004 //    local1 ..
3005
3006 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3007 /// for a 16 byte align requirement.
3008 unsigned
3009 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3010                                                SelectionDAG& DAG) const {
3011   MachineFunction &MF = DAG.getMachineFunction();
3012   const TargetMachine &TM = MF.getTarget();
3013   const X86RegisterInfo *RegInfo =
3014     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3015   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3016   unsigned StackAlignment = TFI.getStackAlignment();
3017   uint64_t AlignMask = StackAlignment - 1;
3018   int64_t Offset = StackSize;
3019   unsigned SlotSize = RegInfo->getSlotSize();
3020   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3021     // Number smaller than 12 so just add the difference.
3022     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3023   } else {
3024     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3025     Offset = ((~AlignMask) & Offset) + StackAlignment +
3026       (StackAlignment-SlotSize);
3027   }
3028   return Offset;
3029 }
3030
3031 /// MatchingStackOffset - Return true if the given stack call argument is
3032 /// already available in the same position (relatively) of the caller's
3033 /// incoming argument stack.
3034 static
3035 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3036                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3037                          const X86InstrInfo *TII) {
3038   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3039   int FI = INT_MAX;
3040   if (Arg.getOpcode() == ISD::CopyFromReg) {
3041     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3042     if (!TargetRegisterInfo::isVirtualRegister(VR))
3043       return false;
3044     MachineInstr *Def = MRI->getVRegDef(VR);
3045     if (!Def)
3046       return false;
3047     if (!Flags.isByVal()) {
3048       if (!TII->isLoadFromStackSlot(Def, FI))
3049         return false;
3050     } else {
3051       unsigned Opcode = Def->getOpcode();
3052       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3053           Def->getOperand(1).isFI()) {
3054         FI = Def->getOperand(1).getIndex();
3055         Bytes = Flags.getByValSize();
3056       } else
3057         return false;
3058     }
3059   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3060     if (Flags.isByVal())
3061       // ByVal argument is passed in as a pointer but it's now being
3062       // dereferenced. e.g.
3063       // define @foo(%struct.X* %A) {
3064       //   tail call @bar(%struct.X* byval %A)
3065       // }
3066       return false;
3067     SDValue Ptr = Ld->getBasePtr();
3068     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3069     if (!FINode)
3070       return false;
3071     FI = FINode->getIndex();
3072   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3073     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3074     FI = FINode->getIndex();
3075     Bytes = Flags.getByValSize();
3076   } else
3077     return false;
3078
3079   assert(FI != INT_MAX);
3080   if (!MFI->isFixedObjectIndex(FI))
3081     return false;
3082   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3083 }
3084
3085 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3086 /// for tail call optimization. Targets which want to do tail call
3087 /// optimization should implement this function.
3088 bool
3089 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3090                                                      CallingConv::ID CalleeCC,
3091                                                      bool isVarArg,
3092                                                      bool isCalleeStructRet,
3093                                                      bool isCallerStructRet,
3094                                                      Type *RetTy,
3095                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3096                                     const SmallVectorImpl<SDValue> &OutVals,
3097                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3098                                                      SelectionDAG &DAG) const {
3099   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3100     return false;
3101
3102   // If -tailcallopt is specified, make fastcc functions tail-callable.
3103   const MachineFunction &MF = DAG.getMachineFunction();
3104   const Function *CallerF = MF.getFunction();
3105
3106   // If the function return type is x86_fp80 and the callee return type is not,
3107   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3108   // perform a tailcall optimization here.
3109   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3110     return false;
3111
3112   CallingConv::ID CallerCC = CallerF->getCallingConv();
3113   bool CCMatch = CallerCC == CalleeCC;
3114   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3115   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3116
3117   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3118     if (IsTailCallConvention(CalleeCC) && CCMatch)
3119       return true;
3120     return false;
3121   }
3122
3123   // Look for obvious safe cases to perform tail call optimization that do not
3124   // require ABI changes. This is what gcc calls sibcall.
3125
3126   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3127   // emit a special epilogue.
3128   const X86RegisterInfo *RegInfo =
3129     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3130   if (RegInfo->needsStackRealignment(MF))
3131     return false;
3132
3133   // Also avoid sibcall optimization if either caller or callee uses struct
3134   // return semantics.
3135   if (isCalleeStructRet || isCallerStructRet)
3136     return false;
3137
3138   // An stdcall/thiscall caller is expected to clean up its arguments; the
3139   // callee isn't going to do that.
3140   // FIXME: this is more restrictive than needed. We could produce a tailcall
3141   // when the stack adjustment matches. For example, with a thiscall that takes
3142   // only one argument.
3143   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3144                    CallerCC == CallingConv::X86_ThisCall))
3145     return false;
3146
3147   // Do not sibcall optimize vararg calls unless all arguments are passed via
3148   // registers.
3149   if (isVarArg && !Outs.empty()) {
3150
3151     // Optimizing for varargs on Win64 is unlikely to be safe without
3152     // additional testing.
3153     if (IsCalleeWin64 || IsCallerWin64)
3154       return false;
3155
3156     SmallVector<CCValAssign, 16> ArgLocs;
3157     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3158                    getTargetMachine(), ArgLocs, *DAG.getContext());
3159
3160     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3161     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3162       if (!ArgLocs[i].isRegLoc())
3163         return false;
3164   }
3165
3166   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3167   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3168   // this into a sibcall.
3169   bool Unused = false;
3170   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3171     if (!Ins[i].Used) {
3172       Unused = true;
3173       break;
3174     }
3175   }
3176   if (Unused) {
3177     SmallVector<CCValAssign, 16> RVLocs;
3178     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3179                    getTargetMachine(), RVLocs, *DAG.getContext());
3180     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3181     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3182       CCValAssign &VA = RVLocs[i];
3183       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3184         return false;
3185     }
3186   }
3187
3188   // If the calling conventions do not match, then we'd better make sure the
3189   // results are returned in the same way as what the caller expects.
3190   if (!CCMatch) {
3191     SmallVector<CCValAssign, 16> RVLocs1;
3192     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3193                     getTargetMachine(), RVLocs1, *DAG.getContext());
3194     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3195
3196     SmallVector<CCValAssign, 16> RVLocs2;
3197     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3198                     getTargetMachine(), RVLocs2, *DAG.getContext());
3199     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3200
3201     if (RVLocs1.size() != RVLocs2.size())
3202       return false;
3203     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3204       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3205         return false;
3206       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3207         return false;
3208       if (RVLocs1[i].isRegLoc()) {
3209         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3210           return false;
3211       } else {
3212         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3213           return false;
3214       }
3215     }
3216   }
3217
3218   // If the callee takes no arguments then go on to check the results of the
3219   // call.
3220   if (!Outs.empty()) {
3221     // Check if stack adjustment is needed. For now, do not do this if any
3222     // argument is passed on the stack.
3223     SmallVector<CCValAssign, 16> ArgLocs;
3224     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3225                    getTargetMachine(), ArgLocs, *DAG.getContext());
3226
3227     // Allocate shadow area for Win64
3228     if (IsCalleeWin64)
3229       CCInfo.AllocateStack(32, 8);
3230
3231     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3232     if (CCInfo.getNextStackOffset()) {
3233       MachineFunction &MF = DAG.getMachineFunction();
3234       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3235         return false;
3236
3237       // Check if the arguments are already laid out in the right way as
3238       // the caller's fixed stack objects.
3239       MachineFrameInfo *MFI = MF.getFrameInfo();
3240       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3241       const X86InstrInfo *TII =
3242         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3243       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3244         CCValAssign &VA = ArgLocs[i];
3245         SDValue Arg = OutVals[i];
3246         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3247         if (VA.getLocInfo() == CCValAssign::Indirect)
3248           return false;
3249         if (!VA.isRegLoc()) {
3250           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3251                                    MFI, MRI, TII))
3252             return false;
3253         }
3254       }
3255     }
3256
3257     // If the tailcall address may be in a register, then make sure it's
3258     // possible to register allocate for it. In 32-bit, the call address can
3259     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3260     // callee-saved registers are restored. These happen to be the same
3261     // registers used to pass 'inreg' arguments so watch out for those.
3262     if (!Subtarget->is64Bit() &&
3263         ((!isa<GlobalAddressSDNode>(Callee) &&
3264           !isa<ExternalSymbolSDNode>(Callee)) ||
3265          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3266       unsigned NumInRegs = 0;
3267       // In PIC we need an extra register to formulate the address computation
3268       // for the callee.
3269       unsigned MaxInRegs =
3270           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3271
3272       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3273         CCValAssign &VA = ArgLocs[i];
3274         if (!VA.isRegLoc())
3275           continue;
3276         unsigned Reg = VA.getLocReg();
3277         switch (Reg) {
3278         default: break;
3279         case X86::EAX: case X86::EDX: case X86::ECX:
3280           if (++NumInRegs == MaxInRegs)
3281             return false;
3282           break;
3283         }
3284       }
3285     }
3286   }
3287
3288   return true;
3289 }
3290
3291 FastISel *
3292 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3293                                   const TargetLibraryInfo *libInfo) const {
3294   return X86::createFastISel(funcInfo, libInfo);
3295 }
3296
3297 //===----------------------------------------------------------------------===//
3298 //                           Other Lowering Hooks
3299 //===----------------------------------------------------------------------===//
3300
3301 static bool MayFoldLoad(SDValue Op) {
3302   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3303 }
3304
3305 static bool MayFoldIntoStore(SDValue Op) {
3306   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3307 }
3308
3309 static bool isTargetShuffle(unsigned Opcode) {
3310   switch(Opcode) {
3311   default: return false;
3312   case X86ISD::PSHUFD:
3313   case X86ISD::PSHUFHW:
3314   case X86ISD::PSHUFLW:
3315   case X86ISD::SHUFP:
3316   case X86ISD::PALIGNR:
3317   case X86ISD::MOVLHPS:
3318   case X86ISD::MOVLHPD:
3319   case X86ISD::MOVHLPS:
3320   case X86ISD::MOVLPS:
3321   case X86ISD::MOVLPD:
3322   case X86ISD::MOVSHDUP:
3323   case X86ISD::MOVSLDUP:
3324   case X86ISD::MOVDDUP:
3325   case X86ISD::MOVSS:
3326   case X86ISD::MOVSD:
3327   case X86ISD::UNPCKL:
3328   case X86ISD::UNPCKH:
3329   case X86ISD::VPERMILP:
3330   case X86ISD::VPERM2X128:
3331   case X86ISD::VPERMI:
3332     return true;
3333   }
3334 }
3335
3336 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3337                                     SDValue V1, SelectionDAG &DAG) {
3338   switch(Opc) {
3339   default: llvm_unreachable("Unknown x86 shuffle node");
3340   case X86ISD::MOVSHDUP:
3341   case X86ISD::MOVSLDUP:
3342   case X86ISD::MOVDDUP:
3343     return DAG.getNode(Opc, dl, VT, V1);
3344   }
3345 }
3346
3347 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3348                                     SDValue V1, unsigned TargetMask,
3349                                     SelectionDAG &DAG) {
3350   switch(Opc) {
3351   default: llvm_unreachable("Unknown x86 shuffle node");
3352   case X86ISD::PSHUFD:
3353   case X86ISD::PSHUFHW:
3354   case X86ISD::PSHUFLW:
3355   case X86ISD::VPERMILP:
3356   case X86ISD::VPERMI:
3357     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3358   }
3359 }
3360
3361 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3362                                     SDValue V1, SDValue V2, unsigned TargetMask,
3363                                     SelectionDAG &DAG) {
3364   switch(Opc) {
3365   default: llvm_unreachable("Unknown x86 shuffle node");
3366   case X86ISD::PALIGNR:
3367   case X86ISD::SHUFP:
3368   case X86ISD::VPERM2X128:
3369     return DAG.getNode(Opc, dl, VT, V1, V2,
3370                        DAG.getConstant(TargetMask, MVT::i8));
3371   }
3372 }
3373
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3376   switch(Opc) {
3377   default: llvm_unreachable("Unknown x86 shuffle node");
3378   case X86ISD::MOVLHPS:
3379   case X86ISD::MOVLHPD:
3380   case X86ISD::MOVHLPS:
3381   case X86ISD::MOVLPS:
3382   case X86ISD::MOVLPD:
3383   case X86ISD::MOVSS:
3384   case X86ISD::MOVSD:
3385   case X86ISD::UNPCKL:
3386   case X86ISD::UNPCKH:
3387     return DAG.getNode(Opc, dl, VT, V1, V2);
3388   }
3389 }
3390
3391 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3392   MachineFunction &MF = DAG.getMachineFunction();
3393   const X86RegisterInfo *RegInfo =
3394     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3395   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3396   int ReturnAddrIndex = FuncInfo->getRAIndex();
3397
3398   if (ReturnAddrIndex == 0) {
3399     // Set up a frame object for the return address.
3400     unsigned SlotSize = RegInfo->getSlotSize();
3401     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3402                                                            -(int64_t)SlotSize,
3403                                                            false);
3404     FuncInfo->setRAIndex(ReturnAddrIndex);
3405   }
3406
3407   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3408 }
3409
3410 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3411                                        bool hasSymbolicDisplacement) {
3412   // Offset should fit into 32 bit immediate field.
3413   if (!isInt<32>(Offset))
3414     return false;
3415
3416   // If we don't have a symbolic displacement - we don't have any extra
3417   // restrictions.
3418   if (!hasSymbolicDisplacement)
3419     return true;
3420
3421   // FIXME: Some tweaks might be needed for medium code model.
3422   if (M != CodeModel::Small && M != CodeModel::Kernel)
3423     return false;
3424
3425   // For small code model we assume that latest object is 16MB before end of 31
3426   // bits boundary. We may also accept pretty large negative constants knowing
3427   // that all objects are in the positive half of address space.
3428   if (M == CodeModel::Small && Offset < 16*1024*1024)
3429     return true;
3430
3431   // For kernel code model we know that all object resist in the negative half
3432   // of 32bits address space. We may not accept negative offsets, since they may
3433   // be just off and we may accept pretty large positive ones.
3434   if (M == CodeModel::Kernel && Offset > 0)
3435     return true;
3436
3437   return false;
3438 }
3439
3440 /// isCalleePop - Determines whether the callee is required to pop its
3441 /// own arguments. Callee pop is necessary to support tail calls.
3442 bool X86::isCalleePop(CallingConv::ID CallingConv,
3443                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3444   if (IsVarArg)
3445     return false;
3446
3447   switch (CallingConv) {
3448   default:
3449     return false;
3450   case CallingConv::X86_StdCall:
3451     return !is64Bit;
3452   case CallingConv::X86_FastCall:
3453     return !is64Bit;
3454   case CallingConv::X86_ThisCall:
3455     return !is64Bit;
3456   case CallingConv::Fast:
3457     return TailCallOpt;
3458   case CallingConv::GHC:
3459     return TailCallOpt;
3460   case CallingConv::HiPE:
3461     return TailCallOpt;
3462   }
3463 }
3464
3465 /// \brief Return true if the condition is an unsigned comparison operation.
3466 static bool isX86CCUnsigned(unsigned X86CC) {
3467   switch (X86CC) {
3468   default: llvm_unreachable("Invalid integer condition!");
3469   case X86::COND_E:     return true;
3470   case X86::COND_G:     return false;
3471   case X86::COND_GE:    return false;
3472   case X86::COND_L:     return false;
3473   case X86::COND_LE:    return false;
3474   case X86::COND_NE:    return true;
3475   case X86::COND_B:     return true;
3476   case X86::COND_A:     return true;
3477   case X86::COND_BE:    return true;
3478   case X86::COND_AE:    return true;
3479   }
3480   llvm_unreachable("covered switch fell through?!");
3481 }
3482
3483 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3484 /// specific condition code, returning the condition code and the LHS/RHS of the
3485 /// comparison to make.
3486 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3487                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3488   if (!isFP) {
3489     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3490       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3491         // X > -1   -> X == 0, jump !sign.
3492         RHS = DAG.getConstant(0, RHS.getValueType());
3493         return X86::COND_NS;
3494       }
3495       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3496         // X < 0   -> X == 0, jump on sign.
3497         return X86::COND_S;
3498       }
3499       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3500         // X < 1   -> X <= 0
3501         RHS = DAG.getConstant(0, RHS.getValueType());
3502         return X86::COND_LE;
3503       }
3504     }
3505
3506     switch (SetCCOpcode) {
3507     default: llvm_unreachable("Invalid integer condition!");
3508     case ISD::SETEQ:  return X86::COND_E;
3509     case ISD::SETGT:  return X86::COND_G;
3510     case ISD::SETGE:  return X86::COND_GE;
3511     case ISD::SETLT:  return X86::COND_L;
3512     case ISD::SETLE:  return X86::COND_LE;
3513     case ISD::SETNE:  return X86::COND_NE;
3514     case ISD::SETULT: return X86::COND_B;
3515     case ISD::SETUGT: return X86::COND_A;
3516     case ISD::SETULE: return X86::COND_BE;
3517     case ISD::SETUGE: return X86::COND_AE;
3518     }
3519   }
3520
3521   // First determine if it is required or is profitable to flip the operands.
3522
3523   // If LHS is a foldable load, but RHS is not, flip the condition.
3524   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3525       !ISD::isNON_EXTLoad(RHS.getNode())) {
3526     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3527     std::swap(LHS, RHS);
3528   }
3529
3530   switch (SetCCOpcode) {
3531   default: break;
3532   case ISD::SETOLT:
3533   case ISD::SETOLE:
3534   case ISD::SETUGT:
3535   case ISD::SETUGE:
3536     std::swap(LHS, RHS);
3537     break;
3538   }
3539
3540   // On a floating point condition, the flags are set as follows:
3541   // ZF  PF  CF   op
3542   //  0 | 0 | 0 | X > Y
3543   //  0 | 0 | 1 | X < Y
3544   //  1 | 0 | 0 | X == Y
3545   //  1 | 1 | 1 | unordered
3546   switch (SetCCOpcode) {
3547   default: llvm_unreachable("Condcode should be pre-legalized away");
3548   case ISD::SETUEQ:
3549   case ISD::SETEQ:   return X86::COND_E;
3550   case ISD::SETOLT:              // flipped
3551   case ISD::SETOGT:
3552   case ISD::SETGT:   return X86::COND_A;
3553   case ISD::SETOLE:              // flipped
3554   case ISD::SETOGE:
3555   case ISD::SETGE:   return X86::COND_AE;
3556   case ISD::SETUGT:              // flipped
3557   case ISD::SETULT:
3558   case ISD::SETLT:   return X86::COND_B;
3559   case ISD::SETUGE:              // flipped
3560   case ISD::SETULE:
3561   case ISD::SETLE:   return X86::COND_BE;
3562   case ISD::SETONE:
3563   case ISD::SETNE:   return X86::COND_NE;
3564   case ISD::SETUO:   return X86::COND_P;
3565   case ISD::SETO:    return X86::COND_NP;
3566   case ISD::SETOEQ:
3567   case ISD::SETUNE:  return X86::COND_INVALID;
3568   }
3569 }
3570
3571 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3572 /// code. Current x86 isa includes the following FP cmov instructions:
3573 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3574 static bool hasFPCMov(unsigned X86CC) {
3575   switch (X86CC) {
3576   default:
3577     return false;
3578   case X86::COND_B:
3579   case X86::COND_BE:
3580   case X86::COND_E:
3581   case X86::COND_P:
3582   case X86::COND_A:
3583   case X86::COND_AE:
3584   case X86::COND_NE:
3585   case X86::COND_NP:
3586     return true;
3587   }
3588 }
3589
3590 /// isFPImmLegal - Returns true if the target can instruction select the
3591 /// specified FP immediate natively. If false, the legalizer will
3592 /// materialize the FP immediate as a load from a constant pool.
3593 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3594   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3595     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3596       return true;
3597   }
3598   return false;
3599 }
3600
3601 /// \brief Returns true if it is beneficial to convert a load of a constant
3602 /// to just the constant itself.
3603 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3604                                                           Type *Ty) const {
3605   assert(Ty->isIntegerTy());
3606
3607   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3608   if (BitSize == 0 || BitSize > 64)
3609     return false;
3610   return true;
3611 }
3612
3613 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3614 /// the specified range (L, H].
3615 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3616   return (Val < 0) || (Val >= Low && Val < Hi);
3617 }
3618
3619 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3620 /// specified value.
3621 static bool isUndefOrEqual(int Val, int CmpVal) {
3622   return (Val < 0 || Val == CmpVal);
3623 }
3624
3625 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3626 /// from position Pos and ending in Pos+Size, falls within the specified
3627 /// sequential range (L, L+Pos]. or is undef.
3628 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3629                                        unsigned Pos, unsigned Size, int Low) {
3630   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3631     if (!isUndefOrEqual(Mask[i], Low))
3632       return false;
3633   return true;
3634 }
3635
3636 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3637 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3638 /// the second operand.
3639 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3640   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3641     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3642   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3643     return (Mask[0] < 2 && Mask[1] < 2);
3644   return false;
3645 }
3646
3647 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3648 /// is suitable for input to PSHUFHW.
3649 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3650   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3651     return false;
3652
3653   // Lower quadword copied in order or undef.
3654   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3655     return false;
3656
3657   // Upper quadword shuffled.
3658   for (unsigned i = 4; i != 8; ++i)
3659     if (!isUndefOrInRange(Mask[i], 4, 8))
3660       return false;
3661
3662   if (VT == MVT::v16i16) {
3663     // Lower quadword copied in order or undef.
3664     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3665       return false;
3666
3667     // Upper quadword shuffled.
3668     for (unsigned i = 12; i != 16; ++i)
3669       if (!isUndefOrInRange(Mask[i], 12, 16))
3670         return false;
3671   }
3672
3673   return true;
3674 }
3675
3676 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3677 /// is suitable for input to PSHUFLW.
3678 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3679   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3680     return false;
3681
3682   // Upper quadword copied in order.
3683   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3684     return false;
3685
3686   // Lower quadword shuffled.
3687   for (unsigned i = 0; i != 4; ++i)
3688     if (!isUndefOrInRange(Mask[i], 0, 4))
3689       return false;
3690
3691   if (VT == MVT::v16i16) {
3692     // Upper quadword copied in order.
3693     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3694       return false;
3695
3696     // Lower quadword shuffled.
3697     for (unsigned i = 8; i != 12; ++i)
3698       if (!isUndefOrInRange(Mask[i], 8, 12))
3699         return false;
3700   }
3701
3702   return true;
3703 }
3704
3705 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PALIGNR.
3707 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3708                           const X86Subtarget *Subtarget) {
3709   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3710       (VT.is256BitVector() && !Subtarget->hasInt256()))
3711     return false;
3712
3713   unsigned NumElts = VT.getVectorNumElements();
3714   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3715   unsigned NumLaneElts = NumElts/NumLanes;
3716
3717   // Do not handle 64-bit element shuffles with palignr.
3718   if (NumLaneElts == 2)
3719     return false;
3720
3721   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3722     unsigned i;
3723     for (i = 0; i != NumLaneElts; ++i) {
3724       if (Mask[i+l] >= 0)
3725         break;
3726     }
3727
3728     // Lane is all undef, go to next lane
3729     if (i == NumLaneElts)
3730       continue;
3731
3732     int Start = Mask[i+l];
3733
3734     // Make sure its in this lane in one of the sources
3735     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3736         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3737       return false;
3738
3739     // If not lane 0, then we must match lane 0
3740     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3741       return false;
3742
3743     // Correct second source to be contiguous with first source
3744     if (Start >= (int)NumElts)
3745       Start -= NumElts - NumLaneElts;
3746
3747     // Make sure we're shifting in the right direction.
3748     if (Start <= (int)(i+l))
3749       return false;
3750
3751     Start -= i;
3752
3753     // Check the rest of the elements to see if they are consecutive.
3754     for (++i; i != NumLaneElts; ++i) {
3755       int Idx = Mask[i+l];
3756
3757       // Make sure its in this lane
3758       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3759           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3760         return false;
3761
3762       // If not lane 0, then we must match lane 0
3763       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3764         return false;
3765
3766       if (Idx >= (int)NumElts)
3767         Idx -= NumElts - NumLaneElts;
3768
3769       if (!isUndefOrEqual(Idx, Start+i))
3770         return false;
3771
3772     }
3773   }
3774
3775   return true;
3776 }
3777
3778 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3779 /// the two vector operands have swapped position.
3780 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3781                                      unsigned NumElems) {
3782   for (unsigned i = 0; i != NumElems; ++i) {
3783     int idx = Mask[i];
3784     if (idx < 0)
3785       continue;
3786     else if (idx < (int)NumElems)
3787       Mask[i] = idx + NumElems;
3788     else
3789       Mask[i] = idx - NumElems;
3790   }
3791 }
3792
3793 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3794 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3795 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3796 /// reverse of what x86 shuffles want.
3797 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3798
3799   unsigned NumElems = VT.getVectorNumElements();
3800   unsigned NumLanes = VT.getSizeInBits()/128;
3801   unsigned NumLaneElems = NumElems/NumLanes;
3802
3803   if (NumLaneElems != 2 && NumLaneElems != 4)
3804     return false;
3805
3806   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3807   bool symetricMaskRequired =
3808     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3809
3810   // VSHUFPSY divides the resulting vector into 4 chunks.
3811   // The sources are also splitted into 4 chunks, and each destination
3812   // chunk must come from a different source chunk.
3813   //
3814   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3815   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3816   //
3817   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3818   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3819   //
3820   // VSHUFPDY divides the resulting vector into 4 chunks.
3821   // The sources are also splitted into 4 chunks, and each destination
3822   // chunk must come from a different source chunk.
3823   //
3824   //  SRC1 =>      X3       X2       X1       X0
3825   //  SRC2 =>      Y3       Y2       Y1       Y0
3826   //
3827   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3828   //
3829   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3830   unsigned HalfLaneElems = NumLaneElems/2;
3831   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3832     for (unsigned i = 0; i != NumLaneElems; ++i) {
3833       int Idx = Mask[i+l];
3834       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3835       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3836         return false;
3837       // For VSHUFPSY, the mask of the second half must be the same as the
3838       // first but with the appropriate offsets. This works in the same way as
3839       // VPERMILPS works with masks.
3840       if (!symetricMaskRequired || Idx < 0)
3841         continue;
3842       if (MaskVal[i] < 0) {
3843         MaskVal[i] = Idx - l;
3844         continue;
3845       }
3846       if ((signed)(Idx - l) != MaskVal[i])
3847         return false;
3848     }
3849   }
3850
3851   return true;
3852 }
3853
3854 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3856 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3857   if (!VT.is128BitVector())
3858     return false;
3859
3860   unsigned NumElems = VT.getVectorNumElements();
3861
3862   if (NumElems != 4)
3863     return false;
3864
3865   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3866   return isUndefOrEqual(Mask[0], 6) &&
3867          isUndefOrEqual(Mask[1], 7) &&
3868          isUndefOrEqual(Mask[2], 2) &&
3869          isUndefOrEqual(Mask[3], 3);
3870 }
3871
3872 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3873 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3874 /// <2, 3, 2, 3>
3875 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3876   if (!VT.is128BitVector())
3877     return false;
3878
3879   unsigned NumElems = VT.getVectorNumElements();
3880
3881   if (NumElems != 4)
3882     return false;
3883
3884   return isUndefOrEqual(Mask[0], 2) &&
3885          isUndefOrEqual(Mask[1], 3) &&
3886          isUndefOrEqual(Mask[2], 2) &&
3887          isUndefOrEqual(Mask[3], 3);
3888 }
3889
3890 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3891 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3892 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3893   if (!VT.is128BitVector())
3894     return false;
3895
3896   unsigned NumElems = VT.getVectorNumElements();
3897
3898   if (NumElems != 2 && NumElems != 4)
3899     return false;
3900
3901   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3902     if (!isUndefOrEqual(Mask[i], i + NumElems))
3903       return false;
3904
3905   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3906     if (!isUndefOrEqual(Mask[i], i))
3907       return false;
3908
3909   return true;
3910 }
3911
3912 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3914 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3915   if (!VT.is128BitVector())
3916     return false;
3917
3918   unsigned NumElems = VT.getVectorNumElements();
3919
3920   if (NumElems != 2 && NumElems != 4)
3921     return false;
3922
3923   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3924     if (!isUndefOrEqual(Mask[i], i))
3925       return false;
3926
3927   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3929       return false;
3930
3931   return true;
3932 }
3933
3934 //
3935 // Some special combinations that can be optimized.
3936 //
3937 static
3938 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3939                                SelectionDAG &DAG) {
3940   MVT VT = SVOp->getSimpleValueType(0);
3941   SDLoc dl(SVOp);
3942
3943   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3944     return SDValue();
3945
3946   ArrayRef<int> Mask = SVOp->getMask();
3947
3948   // These are the special masks that may be optimized.
3949   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3950   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3951   bool MatchEvenMask = true;
3952   bool MatchOddMask  = true;
3953   for (int i=0; i<8; ++i) {
3954     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3955       MatchEvenMask = false;
3956     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3957       MatchOddMask = false;
3958   }
3959
3960   if (!MatchEvenMask && !MatchOddMask)
3961     return SDValue();
3962
3963   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3964
3965   SDValue Op0 = SVOp->getOperand(0);
3966   SDValue Op1 = SVOp->getOperand(1);
3967
3968   if (MatchEvenMask) {
3969     // Shift the second operand right to 32 bits.
3970     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3971     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3972   } else {
3973     // Shift the first operand left to 32 bits.
3974     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3975     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3976   }
3977   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3978   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3979 }
3980
3981 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3982 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3983 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3984                          bool HasInt256, bool V2IsSplat = false) {
3985
3986   assert(VT.getSizeInBits() >= 128 &&
3987          "Unsupported vector type for unpckl");
3988
3989   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3990   unsigned NumLanes;
3991   unsigned NumOf256BitLanes;
3992   unsigned NumElts = VT.getVectorNumElements();
3993   if (VT.is256BitVector()) {
3994     if (NumElts != 4 && NumElts != 8 &&
3995         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3996     return false;
3997     NumLanes = 2;
3998     NumOf256BitLanes = 1;
3999   } else if (VT.is512BitVector()) {
4000     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4001            "Unsupported vector type for unpckh");
4002     NumLanes = 2;
4003     NumOf256BitLanes = 2;
4004   } else {
4005     NumLanes = 1;
4006     NumOf256BitLanes = 1;
4007   }
4008
4009   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4010   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4011
4012   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4013     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4014       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4015         int BitI  = Mask[l256*NumEltsInStride+l+i];
4016         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4017         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4018           return false;
4019         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4020           return false;
4021         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4022           return false;
4023       }
4024     }
4025   }
4026   return true;
4027 }
4028
4029 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4030 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4031 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4032                          bool HasInt256, bool V2IsSplat = false) {
4033   assert(VT.getSizeInBits() >= 128 &&
4034          "Unsupported vector type for unpckh");
4035
4036   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4037   unsigned NumLanes;
4038   unsigned NumOf256BitLanes;
4039   unsigned NumElts = VT.getVectorNumElements();
4040   if (VT.is256BitVector()) {
4041     if (NumElts != 4 && NumElts != 8 &&
4042         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4043     return false;
4044     NumLanes = 2;
4045     NumOf256BitLanes = 1;
4046   } else if (VT.is512BitVector()) {
4047     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4048            "Unsupported vector type for unpckh");
4049     NumLanes = 2;
4050     NumOf256BitLanes = 2;
4051   } else {
4052     NumLanes = 1;
4053     NumOf256BitLanes = 1;
4054   }
4055
4056   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4057   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4058
4059   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4060     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4061       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4062         int BitI  = Mask[l256*NumEltsInStride+l+i];
4063         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4064         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4065           return false;
4066         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4067           return false;
4068         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4069           return false;
4070       }
4071     }
4072   }
4073   return true;
4074 }
4075
4076 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4077 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4078 /// <0, 0, 1, 1>
4079 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4080   unsigned NumElts = VT.getVectorNumElements();
4081   bool Is256BitVec = VT.is256BitVector();
4082
4083   if (VT.is512BitVector())
4084     return false;
4085   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4086          "Unsupported vector type for unpckh");
4087
4088   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4089       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4090     return false;
4091
4092   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4093   // FIXME: Need a better way to get rid of this, there's no latency difference
4094   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4095   // the former later. We should also remove the "_undef" special mask.
4096   if (NumElts == 4 && Is256BitVec)
4097     return false;
4098
4099   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4100   // independently on 128-bit lanes.
4101   unsigned NumLanes = VT.getSizeInBits()/128;
4102   unsigned NumLaneElts = NumElts/NumLanes;
4103
4104   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4105     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4106       int BitI  = Mask[l+i];
4107       int BitI1 = Mask[l+i+1];
4108
4109       if (!isUndefOrEqual(BitI, j))
4110         return false;
4111       if (!isUndefOrEqual(BitI1, j))
4112         return false;
4113     }
4114   }
4115
4116   return true;
4117 }
4118
4119 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4120 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4121 /// <2, 2, 3, 3>
4122 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4123   unsigned NumElts = VT.getVectorNumElements();
4124
4125   if (VT.is512BitVector())
4126     return false;
4127
4128   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4129          "Unsupported vector type for unpckh");
4130
4131   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4132       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4133     return false;
4134
4135   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4136   // independently on 128-bit lanes.
4137   unsigned NumLanes = VT.getSizeInBits()/128;
4138   unsigned NumLaneElts = NumElts/NumLanes;
4139
4140   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4141     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4142       int BitI  = Mask[l+i];
4143       int BitI1 = Mask[l+i+1];
4144       if (!isUndefOrEqual(BitI, j))
4145         return false;
4146       if (!isUndefOrEqual(BitI1, j))
4147         return false;
4148     }
4149   }
4150   return true;
4151 }
4152
4153 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4154 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4155 /// MOVSD, and MOVD, i.e. setting the lowest element.
4156 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4157   if (VT.getVectorElementType().getSizeInBits() < 32)
4158     return false;
4159   if (!VT.is128BitVector())
4160     return false;
4161
4162   unsigned NumElts = VT.getVectorNumElements();
4163
4164   if (!isUndefOrEqual(Mask[0], NumElts))
4165     return false;
4166
4167   for (unsigned i = 1; i != NumElts; ++i)
4168     if (!isUndefOrEqual(Mask[i], i))
4169       return false;
4170
4171   return true;
4172 }
4173
4174 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4175 /// as permutations between 128-bit chunks or halves. As an example: this
4176 /// shuffle bellow:
4177 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4178 /// The first half comes from the second half of V1 and the second half from the
4179 /// the second half of V2.
4180 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4181   if (!HasFp256 || !VT.is256BitVector())
4182     return false;
4183
4184   // The shuffle result is divided into half A and half B. In total the two
4185   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4186   // B must come from C, D, E or F.
4187   unsigned HalfSize = VT.getVectorNumElements()/2;
4188   bool MatchA = false, MatchB = false;
4189
4190   // Check if A comes from one of C, D, E, F.
4191   for (unsigned Half = 0; Half != 4; ++Half) {
4192     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4193       MatchA = true;
4194       break;
4195     }
4196   }
4197
4198   // Check if B comes from one of C, D, E, F.
4199   for (unsigned Half = 0; Half != 4; ++Half) {
4200     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4201       MatchB = true;
4202       break;
4203     }
4204   }
4205
4206   return MatchA && MatchB;
4207 }
4208
4209 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4210 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4211 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4212   MVT VT = SVOp->getSimpleValueType(0);
4213
4214   unsigned HalfSize = VT.getVectorNumElements()/2;
4215
4216   unsigned FstHalf = 0, SndHalf = 0;
4217   for (unsigned i = 0; i < HalfSize; ++i) {
4218     if (SVOp->getMaskElt(i) > 0) {
4219       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4220       break;
4221     }
4222   }
4223   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4224     if (SVOp->getMaskElt(i) > 0) {
4225       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4226       break;
4227     }
4228   }
4229
4230   return (FstHalf | (SndHalf << 4));
4231 }
4232
4233 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4234 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4235   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4236   if (EltSize < 32)
4237     return false;
4238
4239   unsigned NumElts = VT.getVectorNumElements();
4240   Imm8 = 0;
4241   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4242     for (unsigned i = 0; i != NumElts; ++i) {
4243       if (Mask[i] < 0)
4244         continue;
4245       Imm8 |= Mask[i] << (i*2);
4246     }
4247     return true;
4248   }
4249
4250   unsigned LaneSize = 4;
4251   SmallVector<int, 4> MaskVal(LaneSize, -1);
4252
4253   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4254     for (unsigned i = 0; i != LaneSize; ++i) {
4255       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4256         return false;
4257       if (Mask[i+l] < 0)
4258         continue;
4259       if (MaskVal[i] < 0) {
4260         MaskVal[i] = Mask[i+l] - l;
4261         Imm8 |= MaskVal[i] << (i*2);
4262         continue;
4263       }
4264       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4265         return false;
4266     }
4267   }
4268   return true;
4269 }
4270
4271 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4272 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4273 /// Note that VPERMIL mask matching is different depending whether theunderlying
4274 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4275 /// to the same elements of the low, but to the higher half of the source.
4276 /// In VPERMILPD the two lanes could be shuffled independently of each other
4277 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4278 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4279   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4280   if (VT.getSizeInBits() < 256 || EltSize < 32)
4281     return false;
4282   bool symetricMaskRequired = (EltSize == 32);
4283   unsigned NumElts = VT.getVectorNumElements();
4284
4285   unsigned NumLanes = VT.getSizeInBits()/128;
4286   unsigned LaneSize = NumElts/NumLanes;
4287   // 2 or 4 elements in one lane
4288
4289   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4290   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4291     for (unsigned i = 0; i != LaneSize; ++i) {
4292       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4293         return false;
4294       if (symetricMaskRequired) {
4295         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4296           ExpectedMaskVal[i] = Mask[i+l] - l;
4297           continue;
4298         }
4299         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4300           return false;
4301       }
4302     }
4303   }
4304   return true;
4305 }
4306
4307 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4308 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4309 /// element of vector 2 and the other elements to come from vector 1 in order.
4310 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4311                                bool V2IsSplat = false, bool V2IsUndef = false) {
4312   if (!VT.is128BitVector())
4313     return false;
4314
4315   unsigned NumOps = VT.getVectorNumElements();
4316   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4317     return false;
4318
4319   if (!isUndefOrEqual(Mask[0], 0))
4320     return false;
4321
4322   for (unsigned i = 1; i != NumOps; ++i)
4323     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4324           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4325           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4326       return false;
4327
4328   return true;
4329 }
4330
4331 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4332 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4333 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4334 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4335                            const X86Subtarget *Subtarget) {
4336   if (!Subtarget->hasSSE3())
4337     return false;
4338
4339   unsigned NumElems = VT.getVectorNumElements();
4340
4341   if ((VT.is128BitVector() && NumElems != 4) ||
4342       (VT.is256BitVector() && NumElems != 8) ||
4343       (VT.is512BitVector() && NumElems != 16))
4344     return false;
4345
4346   // "i+1" is the value the indexed mask element must have
4347   for (unsigned i = 0; i != NumElems; i += 2)
4348     if (!isUndefOrEqual(Mask[i], i+1) ||
4349         !isUndefOrEqual(Mask[i+1], i+1))
4350       return false;
4351
4352   return true;
4353 }
4354
4355 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4356 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4357 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4358 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4359                            const X86Subtarget *Subtarget) {
4360   if (!Subtarget->hasSSE3())
4361     return false;
4362
4363   unsigned NumElems = VT.getVectorNumElements();
4364
4365   if ((VT.is128BitVector() && NumElems != 4) ||
4366       (VT.is256BitVector() && NumElems != 8) ||
4367       (VT.is512BitVector() && NumElems != 16))
4368     return false;
4369
4370   // "i" is the value the indexed mask element must have
4371   for (unsigned i = 0; i != NumElems; i += 2)
4372     if (!isUndefOrEqual(Mask[i], i) ||
4373         !isUndefOrEqual(Mask[i+1], i))
4374       return false;
4375
4376   return true;
4377 }
4378
4379 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4380 /// specifies a shuffle of elements that is suitable for input to 256-bit
4381 /// version of MOVDDUP.
4382 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4383   if (!HasFp256 || !VT.is256BitVector())
4384     return false;
4385
4386   unsigned NumElts = VT.getVectorNumElements();
4387   if (NumElts != 4)
4388     return false;
4389
4390   for (unsigned i = 0; i != NumElts/2; ++i)
4391     if (!isUndefOrEqual(Mask[i], 0))
4392       return false;
4393   for (unsigned i = NumElts/2; i != NumElts; ++i)
4394     if (!isUndefOrEqual(Mask[i], NumElts/2))
4395       return false;
4396   return true;
4397 }
4398
4399 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4400 /// specifies a shuffle of elements that is suitable for input to 128-bit
4401 /// version of MOVDDUP.
4402 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4403   if (!VT.is128BitVector())
4404     return false;
4405
4406   unsigned e = VT.getVectorNumElements() / 2;
4407   for (unsigned i = 0; i != e; ++i)
4408     if (!isUndefOrEqual(Mask[i], i))
4409       return false;
4410   for (unsigned i = 0; i != e; ++i)
4411     if (!isUndefOrEqual(Mask[e+i], i))
4412       return false;
4413   return true;
4414 }
4415
4416 /// isVEXTRACTIndex - Return true if the specified
4417 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4418 /// suitable for instruction that extract 128 or 256 bit vectors
4419 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4420   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4421   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4422     return false;
4423
4424   // The index should be aligned on a vecWidth-bit boundary.
4425   uint64_t Index =
4426     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4427
4428   MVT VT = N->getSimpleValueType(0);
4429   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4430   bool Result = (Index * ElSize) % vecWidth == 0;
4431
4432   return Result;
4433 }
4434
4435 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4436 /// operand specifies a subvector insert that is suitable for input to
4437 /// insertion of 128 or 256-bit subvectors
4438 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4439   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4440   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4441     return false;
4442   // The index should be aligned on a vecWidth-bit boundary.
4443   uint64_t Index =
4444     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4445
4446   MVT VT = N->getSimpleValueType(0);
4447   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4448   bool Result = (Index * ElSize) % vecWidth == 0;
4449
4450   return Result;
4451 }
4452
4453 bool X86::isVINSERT128Index(SDNode *N) {
4454   return isVINSERTIndex(N, 128);
4455 }
4456
4457 bool X86::isVINSERT256Index(SDNode *N) {
4458   return isVINSERTIndex(N, 256);
4459 }
4460
4461 bool X86::isVEXTRACT128Index(SDNode *N) {
4462   return isVEXTRACTIndex(N, 128);
4463 }
4464
4465 bool X86::isVEXTRACT256Index(SDNode *N) {
4466   return isVEXTRACTIndex(N, 256);
4467 }
4468
4469 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4470 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4471 /// Handles 128-bit and 256-bit.
4472 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4473   MVT VT = N->getSimpleValueType(0);
4474
4475   assert((VT.getSizeInBits() >= 128) &&
4476          "Unsupported vector type for PSHUF/SHUFP");
4477
4478   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4479   // independently on 128-bit lanes.
4480   unsigned NumElts = VT.getVectorNumElements();
4481   unsigned NumLanes = VT.getSizeInBits()/128;
4482   unsigned NumLaneElts = NumElts/NumLanes;
4483
4484   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4485          "Only supports 2, 4 or 8 elements per lane");
4486
4487   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4488   unsigned Mask = 0;
4489   for (unsigned i = 0; i != NumElts; ++i) {
4490     int Elt = N->getMaskElt(i);
4491     if (Elt < 0) continue;
4492     Elt &= NumLaneElts - 1;
4493     unsigned ShAmt = (i << Shift) % 8;
4494     Mask |= Elt << ShAmt;
4495   }
4496
4497   return Mask;
4498 }
4499
4500 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4501 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4502 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4503   MVT VT = N->getSimpleValueType(0);
4504
4505   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4506          "Unsupported vector type for PSHUFHW");
4507
4508   unsigned NumElts = VT.getVectorNumElements();
4509
4510   unsigned Mask = 0;
4511   for (unsigned l = 0; l != NumElts; l += 8) {
4512     // 8 nodes per lane, but we only care about the last 4.
4513     for (unsigned i = 0; i < 4; ++i) {
4514       int Elt = N->getMaskElt(l+i+4);
4515       if (Elt < 0) continue;
4516       Elt &= 0x3; // only 2-bits.
4517       Mask |= Elt << (i * 2);
4518     }
4519   }
4520
4521   return Mask;
4522 }
4523
4524 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4525 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4526 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4527   MVT VT = N->getSimpleValueType(0);
4528
4529   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4530          "Unsupported vector type for PSHUFHW");
4531
4532   unsigned NumElts = VT.getVectorNumElements();
4533
4534   unsigned Mask = 0;
4535   for (unsigned l = 0; l != NumElts; l += 8) {
4536     // 8 nodes per lane, but we only care about the first 4.
4537     for (unsigned i = 0; i < 4; ++i) {
4538       int Elt = N->getMaskElt(l+i);
4539       if (Elt < 0) continue;
4540       Elt &= 0x3; // only 2-bits
4541       Mask |= Elt << (i * 2);
4542     }
4543   }
4544
4545   return Mask;
4546 }
4547
4548 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4549 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4550 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4551   MVT VT = SVOp->getSimpleValueType(0);
4552   unsigned EltSize = VT.is512BitVector() ? 1 :
4553     VT.getVectorElementType().getSizeInBits() >> 3;
4554
4555   unsigned NumElts = VT.getVectorNumElements();
4556   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4557   unsigned NumLaneElts = NumElts/NumLanes;
4558
4559   int Val = 0;
4560   unsigned i;
4561   for (i = 0; i != NumElts; ++i) {
4562     Val = SVOp->getMaskElt(i);
4563     if (Val >= 0)
4564       break;
4565   }
4566   if (Val >= (int)NumElts)
4567     Val -= NumElts - NumLaneElts;
4568
4569   assert(Val - i > 0 && "PALIGNR imm should be positive");
4570   return (Val - i) * EltSize;
4571 }
4572
4573 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4574   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4575   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4576     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4577
4578   uint64_t Index =
4579     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4580
4581   MVT VecVT = N->getOperand(0).getSimpleValueType();
4582   MVT ElVT = VecVT.getVectorElementType();
4583
4584   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4585   return Index / NumElemsPerChunk;
4586 }
4587
4588 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4589   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4590   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4591     llvm_unreachable("Illegal insert subvector for VINSERT");
4592
4593   uint64_t Index =
4594     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4595
4596   MVT VecVT = N->getSimpleValueType(0);
4597   MVT ElVT = VecVT.getVectorElementType();
4598
4599   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4600   return Index / NumElemsPerChunk;
4601 }
4602
4603 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4604 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4605 /// and VINSERTI128 instructions.
4606 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4607   return getExtractVEXTRACTImmediate(N, 128);
4608 }
4609
4610 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4611 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4612 /// and VINSERTI64x4 instructions.
4613 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4614   return getExtractVEXTRACTImmediate(N, 256);
4615 }
4616
4617 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4618 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4619 /// and VINSERTI128 instructions.
4620 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4621   return getInsertVINSERTImmediate(N, 128);
4622 }
4623
4624 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4625 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4626 /// and VINSERTI64x4 instructions.
4627 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4628   return getInsertVINSERTImmediate(N, 256);
4629 }
4630
4631 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4632 /// constant +0.0.
4633 bool X86::isZeroNode(SDValue Elt) {
4634   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4635     return CN->isNullValue();
4636   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4637     return CFP->getValueAPF().isPosZero();
4638   return false;
4639 }
4640
4641 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4642 /// their permute mask.
4643 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4644                                     SelectionDAG &DAG) {
4645   MVT VT = SVOp->getSimpleValueType(0);
4646   unsigned NumElems = VT.getVectorNumElements();
4647   SmallVector<int, 8> MaskVec;
4648
4649   for (unsigned i = 0; i != NumElems; ++i) {
4650     int Idx = SVOp->getMaskElt(i);
4651     if (Idx >= 0) {
4652       if (Idx < (int)NumElems)
4653         Idx += NumElems;
4654       else
4655         Idx -= NumElems;
4656     }
4657     MaskVec.push_back(Idx);
4658   }
4659   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4660                               SVOp->getOperand(0), &MaskVec[0]);
4661 }
4662
4663 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4664 /// match movhlps. The lower half elements should come from upper half of
4665 /// V1 (and in order), and the upper half elements should come from the upper
4666 /// half of V2 (and in order).
4667 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4668   if (!VT.is128BitVector())
4669     return false;
4670   if (VT.getVectorNumElements() != 4)
4671     return false;
4672   for (unsigned i = 0, e = 2; i != e; ++i)
4673     if (!isUndefOrEqual(Mask[i], i+2))
4674       return false;
4675   for (unsigned i = 2; i != 4; ++i)
4676     if (!isUndefOrEqual(Mask[i], i+4))
4677       return false;
4678   return true;
4679 }
4680
4681 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4682 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4683 /// required.
4684 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4685   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4686     return false;
4687   N = N->getOperand(0).getNode();
4688   if (!ISD::isNON_EXTLoad(N))
4689     return false;
4690   if (LD)
4691     *LD = cast<LoadSDNode>(N);
4692   return true;
4693 }
4694
4695 // Test whether the given value is a vector value which will be legalized
4696 // into a load.
4697 static bool WillBeConstantPoolLoad(SDNode *N) {
4698   if (N->getOpcode() != ISD::BUILD_VECTOR)
4699     return false;
4700
4701   // Check for any non-constant elements.
4702   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4703     switch (N->getOperand(i).getNode()->getOpcode()) {
4704     case ISD::UNDEF:
4705     case ISD::ConstantFP:
4706     case ISD::Constant:
4707       break;
4708     default:
4709       return false;
4710     }
4711
4712   // Vectors of all-zeros and all-ones are materialized with special
4713   // instructions rather than being loaded.
4714   return !ISD::isBuildVectorAllZeros(N) &&
4715          !ISD::isBuildVectorAllOnes(N);
4716 }
4717
4718 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4719 /// match movlp{s|d}. The lower half elements should come from lower half of
4720 /// V1 (and in order), and the upper half elements should come from the upper
4721 /// half of V2 (and in order). And since V1 will become the source of the
4722 /// MOVLP, it must be either a vector load or a scalar load to vector.
4723 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4724                                ArrayRef<int> Mask, MVT VT) {
4725   if (!VT.is128BitVector())
4726     return false;
4727
4728   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4729     return false;
4730   // Is V2 is a vector load, don't do this transformation. We will try to use
4731   // load folding shufps op.
4732   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4733     return false;
4734
4735   unsigned NumElems = VT.getVectorNumElements();
4736
4737   if (NumElems != 2 && NumElems != 4)
4738     return false;
4739   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4740     if (!isUndefOrEqual(Mask[i], i))
4741       return false;
4742   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4743     if (!isUndefOrEqual(Mask[i], i+NumElems))
4744       return false;
4745   return true;
4746 }
4747
4748 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4749 /// all the same.
4750 static bool isSplatVector(SDNode *N) {
4751   if (N->getOpcode() != ISD::BUILD_VECTOR)
4752     return false;
4753
4754   SDValue SplatValue = N->getOperand(0);
4755   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4756     if (N->getOperand(i) != SplatValue)
4757       return false;
4758   return true;
4759 }
4760
4761 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4762 /// to an zero vector.
4763 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4764 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4765   SDValue V1 = N->getOperand(0);
4766   SDValue V2 = N->getOperand(1);
4767   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4768   for (unsigned i = 0; i != NumElems; ++i) {
4769     int Idx = N->getMaskElt(i);
4770     if (Idx >= (int)NumElems) {
4771       unsigned Opc = V2.getOpcode();
4772       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4773         continue;
4774       if (Opc != ISD::BUILD_VECTOR ||
4775           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4776         return false;
4777     } else if (Idx >= 0) {
4778       unsigned Opc = V1.getOpcode();
4779       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4780         continue;
4781       if (Opc != ISD::BUILD_VECTOR ||
4782           !X86::isZeroNode(V1.getOperand(Idx)))
4783         return false;
4784     }
4785   }
4786   return true;
4787 }
4788
4789 /// getZeroVector - Returns a vector of specified type with all zero elements.
4790 ///
4791 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4792                              SelectionDAG &DAG, SDLoc dl) {
4793   assert(VT.isVector() && "Expected a vector type");
4794
4795   // Always build SSE zero vectors as <4 x i32> bitcasted
4796   // to their dest type. This ensures they get CSE'd.
4797   SDValue Vec;
4798   if (VT.is128BitVector()) {  // SSE
4799     if (Subtarget->hasSSE2()) {  // SSE2
4800       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4801       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4802     } else { // SSE1
4803       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4804       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4805     }
4806   } else if (VT.is256BitVector()) { // AVX
4807     if (Subtarget->hasInt256()) { // AVX2
4808       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4809       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4810       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4811                         array_lengthof(Ops));
4812     } else {
4813       // 256-bit logic and arithmetic instructions in AVX are all
4814       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4815       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4816       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4817       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4818                         array_lengthof(Ops));
4819     }
4820   } else if (VT.is512BitVector()) { // AVX-512
4821       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4822       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4823                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4824       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4825   } else if (VT.getScalarType() == MVT::i1) {
4826     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4827     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4828     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4829                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4830     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4831                        Ops, VT.getVectorNumElements());
4832   } else
4833     llvm_unreachable("Unexpected vector type");
4834
4835   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4836 }
4837
4838 /// getOnesVector - Returns a vector of specified type with all bits set.
4839 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4840 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4841 /// Then bitcast to their original type, ensuring they get CSE'd.
4842 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4843                              SDLoc dl) {
4844   assert(VT.isVector() && "Expected a vector type");
4845
4846   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4847   SDValue Vec;
4848   if (VT.is256BitVector()) {
4849     if (HasInt256) { // AVX2
4850       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4851       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4852                         array_lengthof(Ops));
4853     } else { // AVX
4854       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4855       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4856     }
4857   } else if (VT.is128BitVector()) {
4858     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4859   } else
4860     llvm_unreachable("Unexpected vector type");
4861
4862   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4863 }
4864
4865 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4866 /// that point to V2 points to its first element.
4867 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4868   for (unsigned i = 0; i != NumElems; ++i) {
4869     if (Mask[i] > (int)NumElems) {
4870       Mask[i] = NumElems;
4871     }
4872   }
4873 }
4874
4875 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4876 /// operation of specified width.
4877 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4878                        SDValue V2) {
4879   unsigned NumElems = VT.getVectorNumElements();
4880   SmallVector<int, 8> Mask;
4881   Mask.push_back(NumElems);
4882   for (unsigned i = 1; i != NumElems; ++i)
4883     Mask.push_back(i);
4884   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4885 }
4886
4887 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4888 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4889                           SDValue V2) {
4890   unsigned NumElems = VT.getVectorNumElements();
4891   SmallVector<int, 8> Mask;
4892   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4893     Mask.push_back(i);
4894     Mask.push_back(i + NumElems);
4895   }
4896   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4897 }
4898
4899 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4900 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4901                           SDValue V2) {
4902   unsigned NumElems = VT.getVectorNumElements();
4903   SmallVector<int, 8> Mask;
4904   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4905     Mask.push_back(i + Half);
4906     Mask.push_back(i + NumElems + Half);
4907   }
4908   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4909 }
4910
4911 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4912 // a generic shuffle instruction because the target has no such instructions.
4913 // Generate shuffles which repeat i16 and i8 several times until they can be
4914 // represented by v4f32 and then be manipulated by target suported shuffles.
4915 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4916   MVT VT = V.getSimpleValueType();
4917   int NumElems = VT.getVectorNumElements();
4918   SDLoc dl(V);
4919
4920   while (NumElems > 4) {
4921     if (EltNo < NumElems/2) {
4922       V = getUnpackl(DAG, dl, VT, V, V);
4923     } else {
4924       V = getUnpackh(DAG, dl, VT, V, V);
4925       EltNo -= NumElems/2;
4926     }
4927     NumElems >>= 1;
4928   }
4929   return V;
4930 }
4931
4932 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4933 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4934   MVT VT = V.getSimpleValueType();
4935   SDLoc dl(V);
4936
4937   if (VT.is128BitVector()) {
4938     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4939     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4940     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4941                              &SplatMask[0]);
4942   } else if (VT.is256BitVector()) {
4943     // To use VPERMILPS to splat scalars, the second half of indicies must
4944     // refer to the higher part, which is a duplication of the lower one,
4945     // because VPERMILPS can only handle in-lane permutations.
4946     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4947                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4948
4949     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4950     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4951                              &SplatMask[0]);
4952   } else
4953     llvm_unreachable("Vector size not supported");
4954
4955   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4956 }
4957
4958 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4959 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4960   MVT SrcVT = SV->getSimpleValueType(0);
4961   SDValue V1 = SV->getOperand(0);
4962   SDLoc dl(SV);
4963
4964   int EltNo = SV->getSplatIndex();
4965   int NumElems = SrcVT.getVectorNumElements();
4966   bool Is256BitVec = SrcVT.is256BitVector();
4967
4968   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4969          "Unknown how to promote splat for type");
4970
4971   // Extract the 128-bit part containing the splat element and update
4972   // the splat element index when it refers to the higher register.
4973   if (Is256BitVec) {
4974     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4975     if (EltNo >= NumElems/2)
4976       EltNo -= NumElems/2;
4977   }
4978
4979   // All i16 and i8 vector types can't be used directly by a generic shuffle
4980   // instruction because the target has no such instruction. Generate shuffles
4981   // which repeat i16 and i8 several times until they fit in i32, and then can
4982   // be manipulated by target suported shuffles.
4983   MVT EltVT = SrcVT.getVectorElementType();
4984   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4985     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4986
4987   // Recreate the 256-bit vector and place the same 128-bit vector
4988   // into the low and high part. This is necessary because we want
4989   // to use VPERM* to shuffle the vectors
4990   if (Is256BitVec) {
4991     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4992   }
4993
4994   return getLegalSplat(DAG, V1, EltNo);
4995 }
4996
4997 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4998 /// vector of zero or undef vector.  This produces a shuffle where the low
4999 /// element of V2 is swizzled into the zero/undef vector, landing at element
5000 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5001 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5002                                            bool IsZero,
5003                                            const X86Subtarget *Subtarget,
5004                                            SelectionDAG &DAG) {
5005   MVT VT = V2.getSimpleValueType();
5006   SDValue V1 = IsZero
5007     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5008   unsigned NumElems = VT.getVectorNumElements();
5009   SmallVector<int, 16> MaskVec;
5010   for (unsigned i = 0; i != NumElems; ++i)
5011     // If this is the insertion idx, put the low elt of V2 here.
5012     MaskVec.push_back(i == Idx ? NumElems : i);
5013   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5014 }
5015
5016 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5017 /// target specific opcode. Returns true if the Mask could be calculated.
5018 /// Sets IsUnary to true if only uses one source.
5019 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5020                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5021   unsigned NumElems = VT.getVectorNumElements();
5022   SDValue ImmN;
5023
5024   IsUnary = false;
5025   switch(N->getOpcode()) {
5026   case X86ISD::SHUFP:
5027     ImmN = N->getOperand(N->getNumOperands()-1);
5028     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5029     break;
5030   case X86ISD::UNPCKH:
5031     DecodeUNPCKHMask(VT, Mask);
5032     break;
5033   case X86ISD::UNPCKL:
5034     DecodeUNPCKLMask(VT, Mask);
5035     break;
5036   case X86ISD::MOVHLPS:
5037     DecodeMOVHLPSMask(NumElems, Mask);
5038     break;
5039   case X86ISD::MOVLHPS:
5040     DecodeMOVLHPSMask(NumElems, Mask);
5041     break;
5042   case X86ISD::PALIGNR:
5043     ImmN = N->getOperand(N->getNumOperands()-1);
5044     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5045     break;
5046   case X86ISD::PSHUFD:
5047   case X86ISD::VPERMILP:
5048     ImmN = N->getOperand(N->getNumOperands()-1);
5049     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5050     IsUnary = true;
5051     break;
5052   case X86ISD::PSHUFHW:
5053     ImmN = N->getOperand(N->getNumOperands()-1);
5054     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5055     IsUnary = true;
5056     break;
5057   case X86ISD::PSHUFLW:
5058     ImmN = N->getOperand(N->getNumOperands()-1);
5059     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5060     IsUnary = true;
5061     break;
5062   case X86ISD::VPERMI:
5063     ImmN = N->getOperand(N->getNumOperands()-1);
5064     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5065     IsUnary = true;
5066     break;
5067   case X86ISD::MOVSS:
5068   case X86ISD::MOVSD: {
5069     // The index 0 always comes from the first element of the second source,
5070     // this is why MOVSS and MOVSD are used in the first place. The other
5071     // elements come from the other positions of the first source vector
5072     Mask.push_back(NumElems);
5073     for (unsigned i = 1; i != NumElems; ++i) {
5074       Mask.push_back(i);
5075     }
5076     break;
5077   }
5078   case X86ISD::VPERM2X128:
5079     ImmN = N->getOperand(N->getNumOperands()-1);
5080     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5081     if (Mask.empty()) return false;
5082     break;
5083   case X86ISD::MOVDDUP:
5084   case X86ISD::MOVLHPD:
5085   case X86ISD::MOVLPD:
5086   case X86ISD::MOVLPS:
5087   case X86ISD::MOVSHDUP:
5088   case X86ISD::MOVSLDUP:
5089     // Not yet implemented
5090     return false;
5091   default: llvm_unreachable("unknown target shuffle node");
5092   }
5093
5094   return true;
5095 }
5096
5097 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5098 /// element of the result of the vector shuffle.
5099 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5100                                    unsigned Depth) {
5101   if (Depth == 6)
5102     return SDValue();  // Limit search depth.
5103
5104   SDValue V = SDValue(N, 0);
5105   EVT VT = V.getValueType();
5106   unsigned Opcode = V.getOpcode();
5107
5108   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5109   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5110     int Elt = SV->getMaskElt(Index);
5111
5112     if (Elt < 0)
5113       return DAG.getUNDEF(VT.getVectorElementType());
5114
5115     unsigned NumElems = VT.getVectorNumElements();
5116     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5117                                          : SV->getOperand(1);
5118     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5119   }
5120
5121   // Recurse into target specific vector shuffles to find scalars.
5122   if (isTargetShuffle(Opcode)) {
5123     MVT ShufVT = V.getSimpleValueType();
5124     unsigned NumElems = ShufVT.getVectorNumElements();
5125     SmallVector<int, 16> ShuffleMask;
5126     bool IsUnary;
5127
5128     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5129       return SDValue();
5130
5131     int Elt = ShuffleMask[Index];
5132     if (Elt < 0)
5133       return DAG.getUNDEF(ShufVT.getVectorElementType());
5134
5135     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5136                                          : N->getOperand(1);
5137     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5138                                Depth+1);
5139   }
5140
5141   // Actual nodes that may contain scalar elements
5142   if (Opcode == ISD::BITCAST) {
5143     V = V.getOperand(0);
5144     EVT SrcVT = V.getValueType();
5145     unsigned NumElems = VT.getVectorNumElements();
5146
5147     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5148       return SDValue();
5149   }
5150
5151   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5152     return (Index == 0) ? V.getOperand(0)
5153                         : DAG.getUNDEF(VT.getVectorElementType());
5154
5155   if (V.getOpcode() == ISD::BUILD_VECTOR)
5156     return V.getOperand(Index);
5157
5158   return SDValue();
5159 }
5160
5161 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5162 /// shuffle operation which come from a consecutively from a zero. The
5163 /// search can start in two different directions, from left or right.
5164 /// We count undefs as zeros until PreferredNum is reached.
5165 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5166                                          unsigned NumElems, bool ZerosFromLeft,
5167                                          SelectionDAG &DAG,
5168                                          unsigned PreferredNum = -1U) {
5169   unsigned NumZeros = 0;
5170   for (unsigned i = 0; i != NumElems; ++i) {
5171     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5172     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5173     if (!Elt.getNode())
5174       break;
5175
5176     if (X86::isZeroNode(Elt))
5177       ++NumZeros;
5178     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5179       NumZeros = std::min(NumZeros + 1, PreferredNum);
5180     else
5181       break;
5182   }
5183
5184   return NumZeros;
5185 }
5186
5187 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5188 /// correspond consecutively to elements from one of the vector operands,
5189 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5190 static
5191 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5192                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5193                               unsigned NumElems, unsigned &OpNum) {
5194   bool SeenV1 = false;
5195   bool SeenV2 = false;
5196
5197   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5198     int Idx = SVOp->getMaskElt(i);
5199     // Ignore undef indicies
5200     if (Idx < 0)
5201       continue;
5202
5203     if (Idx < (int)NumElems)
5204       SeenV1 = true;
5205     else
5206       SeenV2 = true;
5207
5208     // Only accept consecutive elements from the same vector
5209     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5210       return false;
5211   }
5212
5213   OpNum = SeenV1 ? 0 : 1;
5214   return true;
5215 }
5216
5217 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5218 /// logical left shift of a vector.
5219 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5220                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5221   unsigned NumElems =
5222     SVOp->getSimpleValueType(0).getVectorNumElements();
5223   unsigned NumZeros = getNumOfConsecutiveZeros(
5224       SVOp, NumElems, false /* check zeros from right */, DAG,
5225       SVOp->getMaskElt(0));
5226   unsigned OpSrc;
5227
5228   if (!NumZeros)
5229     return false;
5230
5231   // Considering the elements in the mask that are not consecutive zeros,
5232   // check if they consecutively come from only one of the source vectors.
5233   //
5234   //               V1 = {X, A, B, C}     0
5235   //                         \  \  \    /
5236   //   vector_shuffle V1, V2 <1, 2, 3, X>
5237   //
5238   if (!isShuffleMaskConsecutive(SVOp,
5239             0,                   // Mask Start Index
5240             NumElems-NumZeros,   // Mask End Index(exclusive)
5241             NumZeros,            // Where to start looking in the src vector
5242             NumElems,            // Number of elements in vector
5243             OpSrc))              // Which source operand ?
5244     return false;
5245
5246   isLeft = false;
5247   ShAmt = NumZeros;
5248   ShVal = SVOp->getOperand(OpSrc);
5249   return true;
5250 }
5251
5252 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5253 /// logical left shift of a vector.
5254 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5255                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5256   unsigned NumElems =
5257     SVOp->getSimpleValueType(0).getVectorNumElements();
5258   unsigned NumZeros = getNumOfConsecutiveZeros(
5259       SVOp, NumElems, true /* check zeros from left */, DAG,
5260       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5261   unsigned OpSrc;
5262
5263   if (!NumZeros)
5264     return false;
5265
5266   // Considering the elements in the mask that are not consecutive zeros,
5267   // check if they consecutively come from only one of the source vectors.
5268   //
5269   //                           0    { A, B, X, X } = V2
5270   //                          / \    /  /
5271   //   vector_shuffle V1, V2 <X, X, 4, 5>
5272   //
5273   if (!isShuffleMaskConsecutive(SVOp,
5274             NumZeros,     // Mask Start Index
5275             NumElems,     // Mask End Index(exclusive)
5276             0,            // Where to start looking in the src vector
5277             NumElems,     // Number of elements in vector
5278             OpSrc))       // Which source operand ?
5279     return false;
5280
5281   isLeft = true;
5282   ShAmt = NumZeros;
5283   ShVal = SVOp->getOperand(OpSrc);
5284   return true;
5285 }
5286
5287 /// isVectorShift - Returns true if the shuffle can be implemented as a
5288 /// logical left or right shift of a vector.
5289 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5290                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5291   // Although the logic below support any bitwidth size, there are no
5292   // shift instructions which handle more than 128-bit vectors.
5293   if (!SVOp->getSimpleValueType(0).is128BitVector())
5294     return false;
5295
5296   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5297       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5298     return true;
5299
5300   return false;
5301 }
5302
5303 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5304 ///
5305 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5306                                        unsigned NumNonZero, unsigned NumZero,
5307                                        SelectionDAG &DAG,
5308                                        const X86Subtarget* Subtarget,
5309                                        const TargetLowering &TLI) {
5310   if (NumNonZero > 8)
5311     return SDValue();
5312
5313   SDLoc dl(Op);
5314   SDValue V(0, 0);
5315   bool First = true;
5316   for (unsigned i = 0; i < 16; ++i) {
5317     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5318     if (ThisIsNonZero && First) {
5319       if (NumZero)
5320         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5321       else
5322         V = DAG.getUNDEF(MVT::v8i16);
5323       First = false;
5324     }
5325
5326     if ((i & 1) != 0) {
5327       SDValue ThisElt(0, 0), LastElt(0, 0);
5328       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5329       if (LastIsNonZero) {
5330         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5331                               MVT::i16, Op.getOperand(i-1));
5332       }
5333       if (ThisIsNonZero) {
5334         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5335         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5336                               ThisElt, DAG.getConstant(8, MVT::i8));
5337         if (LastIsNonZero)
5338           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5339       } else
5340         ThisElt = LastElt;
5341
5342       if (ThisElt.getNode())
5343         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5344                         DAG.getIntPtrConstant(i/2));
5345     }
5346   }
5347
5348   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5349 }
5350
5351 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5352 ///
5353 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5354                                      unsigned NumNonZero, unsigned NumZero,
5355                                      SelectionDAG &DAG,
5356                                      const X86Subtarget* Subtarget,
5357                                      const TargetLowering &TLI) {
5358   if (NumNonZero > 4)
5359     return SDValue();
5360
5361   SDLoc dl(Op);
5362   SDValue V(0, 0);
5363   bool First = true;
5364   for (unsigned i = 0; i < 8; ++i) {
5365     bool isNonZero = (NonZeros & (1 << i)) != 0;
5366     if (isNonZero) {
5367       if (First) {
5368         if (NumZero)
5369           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5370         else
5371           V = DAG.getUNDEF(MVT::v8i16);
5372         First = false;
5373       }
5374       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5375                       MVT::v8i16, V, Op.getOperand(i),
5376                       DAG.getIntPtrConstant(i));
5377     }
5378   }
5379
5380   return V;
5381 }
5382
5383 /// getVShift - Return a vector logical shift node.
5384 ///
5385 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5386                          unsigned NumBits, SelectionDAG &DAG,
5387                          const TargetLowering &TLI, SDLoc dl) {
5388   assert(VT.is128BitVector() && "Unknown type for VShift");
5389   EVT ShVT = MVT::v2i64;
5390   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5391   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5392   return DAG.getNode(ISD::BITCAST, dl, VT,
5393                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5394                              DAG.getConstant(NumBits,
5395                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5396 }
5397
5398 static SDValue
5399 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5400
5401   // Check if the scalar load can be widened into a vector load. And if
5402   // the address is "base + cst" see if the cst can be "absorbed" into
5403   // the shuffle mask.
5404   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5405     SDValue Ptr = LD->getBasePtr();
5406     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5407       return SDValue();
5408     EVT PVT = LD->getValueType(0);
5409     if (PVT != MVT::i32 && PVT != MVT::f32)
5410       return SDValue();
5411
5412     int FI = -1;
5413     int64_t Offset = 0;
5414     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5415       FI = FINode->getIndex();
5416       Offset = 0;
5417     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5418                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5419       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5420       Offset = Ptr.getConstantOperandVal(1);
5421       Ptr = Ptr.getOperand(0);
5422     } else {
5423       return SDValue();
5424     }
5425
5426     // FIXME: 256-bit vector instructions don't require a strict alignment,
5427     // improve this code to support it better.
5428     unsigned RequiredAlign = VT.getSizeInBits()/8;
5429     SDValue Chain = LD->getChain();
5430     // Make sure the stack object alignment is at least 16 or 32.
5431     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5432     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5433       if (MFI->isFixedObjectIndex(FI)) {
5434         // Can't change the alignment. FIXME: It's possible to compute
5435         // the exact stack offset and reference FI + adjust offset instead.
5436         // If someone *really* cares about this. That's the way to implement it.
5437         return SDValue();
5438       } else {
5439         MFI->setObjectAlignment(FI, RequiredAlign);
5440       }
5441     }
5442
5443     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5444     // Ptr + (Offset & ~15).
5445     if (Offset < 0)
5446       return SDValue();
5447     if ((Offset % RequiredAlign) & 3)
5448       return SDValue();
5449     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5450     if (StartOffset)
5451       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5452                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5453
5454     int EltNo = (Offset - StartOffset) >> 2;
5455     unsigned NumElems = VT.getVectorNumElements();
5456
5457     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5458     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5459                              LD->getPointerInfo().getWithOffset(StartOffset),
5460                              false, false, false, 0);
5461
5462     SmallVector<int, 8> Mask;
5463     for (unsigned i = 0; i != NumElems; ++i)
5464       Mask.push_back(EltNo);
5465
5466     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5467   }
5468
5469   return SDValue();
5470 }
5471
5472 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5473 /// vector of type 'VT', see if the elements can be replaced by a single large
5474 /// load which has the same value as a build_vector whose operands are 'elts'.
5475 ///
5476 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5477 ///
5478 /// FIXME: we'd also like to handle the case where the last elements are zero
5479 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5480 /// There's even a handy isZeroNode for that purpose.
5481 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5482                                         SDLoc &DL, SelectionDAG &DAG,
5483                                         bool isAfterLegalize) {
5484   EVT EltVT = VT.getVectorElementType();
5485   unsigned NumElems = Elts.size();
5486
5487   LoadSDNode *LDBase = NULL;
5488   unsigned LastLoadedElt = -1U;
5489
5490   // For each element in the initializer, see if we've found a load or an undef.
5491   // If we don't find an initial load element, or later load elements are
5492   // non-consecutive, bail out.
5493   for (unsigned i = 0; i < NumElems; ++i) {
5494     SDValue Elt = Elts[i];
5495
5496     if (!Elt.getNode() ||
5497         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5498       return SDValue();
5499     if (!LDBase) {
5500       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5501         return SDValue();
5502       LDBase = cast<LoadSDNode>(Elt.getNode());
5503       LastLoadedElt = i;
5504       continue;
5505     }
5506     if (Elt.getOpcode() == ISD::UNDEF)
5507       continue;
5508
5509     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5510     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5511       return SDValue();
5512     LastLoadedElt = i;
5513   }
5514
5515   // If we have found an entire vector of loads and undefs, then return a large
5516   // load of the entire vector width starting at the base pointer.  If we found
5517   // consecutive loads for the low half, generate a vzext_load node.
5518   if (LastLoadedElt == NumElems - 1) {
5519
5520     if (isAfterLegalize &&
5521         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5522       return SDValue();
5523
5524     SDValue NewLd = SDValue();
5525
5526     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5527       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5528                           LDBase->getPointerInfo(),
5529                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5530                           LDBase->isInvariant(), 0);
5531     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5532                         LDBase->getPointerInfo(),
5533                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5534                         LDBase->isInvariant(), LDBase->getAlignment());
5535
5536     if (LDBase->hasAnyUseOfValue(1)) {
5537       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5538                                      SDValue(LDBase, 1),
5539                                      SDValue(NewLd.getNode(), 1));
5540       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5541       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5542                              SDValue(NewLd.getNode(), 1));
5543     }
5544
5545     return NewLd;
5546   }
5547   if (NumElems == 4 && LastLoadedElt == 1 &&
5548       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5549     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5550     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5551     SDValue ResNode =
5552         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5553                                 array_lengthof(Ops), MVT::i64,
5554                                 LDBase->getPointerInfo(),
5555                                 LDBase->getAlignment(),
5556                                 false/*isVolatile*/, true/*ReadMem*/,
5557                                 false/*WriteMem*/);
5558
5559     // Make sure the newly-created LOAD is in the same position as LDBase in
5560     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5561     // update uses of LDBase's output chain to use the TokenFactor.
5562     if (LDBase->hasAnyUseOfValue(1)) {
5563       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5564                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5565       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5566       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5567                              SDValue(ResNode.getNode(), 1));
5568     }
5569
5570     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5571   }
5572   return SDValue();
5573 }
5574
5575 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5576 /// to generate a splat value for the following cases:
5577 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5578 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5579 /// a scalar load, or a constant.
5580 /// The VBROADCAST node is returned when a pattern is found,
5581 /// or SDValue() otherwise.
5582 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5583                                     SelectionDAG &DAG) {
5584   if (!Subtarget->hasFp256())
5585     return SDValue();
5586
5587   MVT VT = Op.getSimpleValueType();
5588   SDLoc dl(Op);
5589
5590   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5591          "Unsupported vector type for broadcast.");
5592
5593   SDValue Ld;
5594   bool ConstSplatVal;
5595
5596   switch (Op.getOpcode()) {
5597     default:
5598       // Unknown pattern found.
5599       return SDValue();
5600
5601     case ISD::BUILD_VECTOR: {
5602       // The BUILD_VECTOR node must be a splat.
5603       if (!isSplatVector(Op.getNode()))
5604         return SDValue();
5605
5606       Ld = Op.getOperand(0);
5607       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5608                      Ld.getOpcode() == ISD::ConstantFP);
5609
5610       // The suspected load node has several users. Make sure that all
5611       // of its users are from the BUILD_VECTOR node.
5612       // Constants may have multiple users.
5613       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5614         return SDValue();
5615       break;
5616     }
5617
5618     case ISD::VECTOR_SHUFFLE: {
5619       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5620
5621       // Shuffles must have a splat mask where the first element is
5622       // broadcasted.
5623       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5624         return SDValue();
5625
5626       SDValue Sc = Op.getOperand(0);
5627       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5628           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5629
5630         if (!Subtarget->hasInt256())
5631           return SDValue();
5632
5633         // Use the register form of the broadcast instruction available on AVX2.
5634         if (VT.getSizeInBits() >= 256)
5635           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5636         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5637       }
5638
5639       Ld = Sc.getOperand(0);
5640       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5641                        Ld.getOpcode() == ISD::ConstantFP);
5642
5643       // The scalar_to_vector node and the suspected
5644       // load node must have exactly one user.
5645       // Constants may have multiple users.
5646
5647       // AVX-512 has register version of the broadcast
5648       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5649         Ld.getValueType().getSizeInBits() >= 32;
5650       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5651           !hasRegVer))
5652         return SDValue();
5653       break;
5654     }
5655   }
5656
5657   bool IsGE256 = (VT.getSizeInBits() >= 256);
5658
5659   // Handle the broadcasting a single constant scalar from the constant pool
5660   // into a vector. On Sandybridge it is still better to load a constant vector
5661   // from the constant pool and not to broadcast it from a scalar.
5662   if (ConstSplatVal && Subtarget->hasInt256()) {
5663     EVT CVT = Ld.getValueType();
5664     assert(!CVT.isVector() && "Must not broadcast a vector type");
5665     unsigned ScalarSize = CVT.getSizeInBits();
5666
5667     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5668       const Constant *C = 0;
5669       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5670         C = CI->getConstantIntValue();
5671       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5672         C = CF->getConstantFPValue();
5673
5674       assert(C && "Invalid constant type");
5675
5676       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5677       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5678       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5679       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5680                        MachinePointerInfo::getConstantPool(),
5681                        false, false, false, Alignment);
5682
5683       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5684     }
5685   }
5686
5687   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5688   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5689
5690   // Handle AVX2 in-register broadcasts.
5691   if (!IsLoad && Subtarget->hasInt256() &&
5692       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5693     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5694
5695   // The scalar source must be a normal load.
5696   if (!IsLoad)
5697     return SDValue();
5698
5699   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5700     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5701
5702   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5703   // double since there is no vbroadcastsd xmm
5704   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5705     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5706       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5707   }
5708
5709   // Unsupported broadcast.
5710   return SDValue();
5711 }
5712
5713 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5714 /// underlying vector and index.
5715 ///
5716 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5717 /// index.
5718 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5719                                          SDValue ExtIdx) {
5720   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5721   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5722     return Idx;
5723
5724   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5725   // lowered this:
5726   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5727   // to:
5728   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5729   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5730   //                           undef)
5731   //                       Constant<0>)
5732   // In this case the vector is the extract_subvector expression and the index
5733   // is 2, as specified by the shuffle.
5734   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5735   SDValue ShuffleVec = SVOp->getOperand(0);
5736   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5737   assert(ShuffleVecVT.getVectorElementType() ==
5738          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5739
5740   int ShuffleIdx = SVOp->getMaskElt(Idx);
5741   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5742     ExtractedFromVec = ShuffleVec;
5743     return ShuffleIdx;
5744   }
5745   return Idx;
5746 }
5747
5748 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5749   MVT VT = Op.getSimpleValueType();
5750
5751   // Skip if insert_vec_elt is not supported.
5752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5753   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5754     return SDValue();
5755
5756   SDLoc DL(Op);
5757   unsigned NumElems = Op.getNumOperands();
5758
5759   SDValue VecIn1;
5760   SDValue VecIn2;
5761   SmallVector<unsigned, 4> InsertIndices;
5762   SmallVector<int, 8> Mask(NumElems, -1);
5763
5764   for (unsigned i = 0; i != NumElems; ++i) {
5765     unsigned Opc = Op.getOperand(i).getOpcode();
5766
5767     if (Opc == ISD::UNDEF)
5768       continue;
5769
5770     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5771       // Quit if more than 1 elements need inserting.
5772       if (InsertIndices.size() > 1)
5773         return SDValue();
5774
5775       InsertIndices.push_back(i);
5776       continue;
5777     }
5778
5779     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5780     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5781     // Quit if non-constant index.
5782     if (!isa<ConstantSDNode>(ExtIdx))
5783       return SDValue();
5784     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5785
5786     // Quit if extracted from vector of different type.
5787     if (ExtractedFromVec.getValueType() != VT)
5788       return SDValue();
5789
5790     if (VecIn1.getNode() == 0)
5791       VecIn1 = ExtractedFromVec;
5792     else if (VecIn1 != ExtractedFromVec) {
5793       if (VecIn2.getNode() == 0)
5794         VecIn2 = ExtractedFromVec;
5795       else if (VecIn2 != ExtractedFromVec)
5796         // Quit if more than 2 vectors to shuffle
5797         return SDValue();
5798     }
5799
5800     if (ExtractedFromVec == VecIn1)
5801       Mask[i] = Idx;
5802     else if (ExtractedFromVec == VecIn2)
5803       Mask[i] = Idx + NumElems;
5804   }
5805
5806   if (VecIn1.getNode() == 0)
5807     return SDValue();
5808
5809   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5810   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5811   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5812     unsigned Idx = InsertIndices[i];
5813     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5814                      DAG.getIntPtrConstant(Idx));
5815   }
5816
5817   return NV;
5818 }
5819
5820 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5821 SDValue
5822 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5823
5824   MVT VT = Op.getSimpleValueType();
5825   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5826          "Unexpected type in LowerBUILD_VECTORvXi1!");
5827
5828   SDLoc dl(Op);
5829   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5830     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5831     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5832                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5833     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5834                        Ops, VT.getVectorNumElements());
5835   }
5836
5837   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5838     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5839     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5840                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5841     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5842                        Ops, VT.getVectorNumElements());
5843   }
5844
5845   bool AllContants = true;
5846   uint64_t Immediate = 0;
5847   int NonConstIdx = -1;
5848   bool IsSplat = true;
5849   unsigned NumNonConsts = 0;
5850   unsigned NumConsts = 0;
5851   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5852     SDValue In = Op.getOperand(idx);
5853     if (In.getOpcode() == ISD::UNDEF)
5854       continue;
5855     if (!isa<ConstantSDNode>(In)) {
5856       AllContants = false;
5857       NonConstIdx = idx;
5858       NumNonConsts++;
5859     }
5860     else {
5861       NumConsts++;
5862       if (cast<ConstantSDNode>(In)->getZExtValue())
5863       Immediate |= (1ULL << idx);
5864     }
5865     if (In != Op.getOperand(0))
5866       IsSplat = false;
5867   }
5868
5869   if (AllContants) {
5870     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5871       DAG.getConstant(Immediate, MVT::i16));
5872     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5873                        DAG.getIntPtrConstant(0));
5874   }
5875
5876   if (NumNonConsts == 1 && NonConstIdx != 0) {
5877     SDValue DstVec;
5878     if (NumConsts) {
5879       SDValue VecAsImm = DAG.getConstant(Immediate,
5880                                          MVT::getIntegerVT(VT.getSizeInBits()));
5881       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5882     }
5883     else 
5884       DstVec = DAG.getUNDEF(VT);
5885     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5886                        Op.getOperand(NonConstIdx),
5887                        DAG.getIntPtrConstant(NonConstIdx));
5888   }
5889   if (!IsSplat && (NonConstIdx != 0))
5890     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5891   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5892   SDValue Select;
5893   if (IsSplat)
5894     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5895                           DAG.getConstant(-1, SelectVT),
5896                           DAG.getConstant(0, SelectVT));
5897   else
5898     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5899                          DAG.getConstant((Immediate | 1), SelectVT),
5900                          DAG.getConstant(Immediate, SelectVT));
5901   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5902 }
5903
5904 SDValue
5905 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5906   SDLoc dl(Op);
5907
5908   MVT VT = Op.getSimpleValueType();
5909   MVT ExtVT = VT.getVectorElementType();
5910   unsigned NumElems = Op.getNumOperands();
5911
5912   // Generate vectors for predicate vectors.
5913   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5914     return LowerBUILD_VECTORvXi1(Op, DAG);
5915
5916   // Vectors containing all zeros can be matched by pxor and xorps later
5917   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5918     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5919     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5920     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5921       return Op;
5922
5923     return getZeroVector(VT, Subtarget, DAG, dl);
5924   }
5925
5926   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5927   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5928   // vpcmpeqd on 256-bit vectors.
5929   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5930     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5931       return Op;
5932
5933     if (!VT.is512BitVector())
5934       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5935   }
5936
5937   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5938   if (Broadcast.getNode())
5939     return Broadcast;
5940
5941   unsigned EVTBits = ExtVT.getSizeInBits();
5942
5943   unsigned NumZero  = 0;
5944   unsigned NumNonZero = 0;
5945   unsigned NonZeros = 0;
5946   bool IsAllConstants = true;
5947   SmallSet<SDValue, 8> Values;
5948   for (unsigned i = 0; i < NumElems; ++i) {
5949     SDValue Elt = Op.getOperand(i);
5950     if (Elt.getOpcode() == ISD::UNDEF)
5951       continue;
5952     Values.insert(Elt);
5953     if (Elt.getOpcode() != ISD::Constant &&
5954         Elt.getOpcode() != ISD::ConstantFP)
5955       IsAllConstants = false;
5956     if (X86::isZeroNode(Elt))
5957       NumZero++;
5958     else {
5959       NonZeros |= (1 << i);
5960       NumNonZero++;
5961     }
5962   }
5963
5964   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5965   if (NumNonZero == 0)
5966     return DAG.getUNDEF(VT);
5967
5968   // Special case for single non-zero, non-undef, element.
5969   if (NumNonZero == 1) {
5970     unsigned Idx = countTrailingZeros(NonZeros);
5971     SDValue Item = Op.getOperand(Idx);
5972
5973     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5974     // the value are obviously zero, truncate the value to i32 and do the
5975     // insertion that way.  Only do this if the value is non-constant or if the
5976     // value is a constant being inserted into element 0.  It is cheaper to do
5977     // a constant pool load than it is to do a movd + shuffle.
5978     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5979         (!IsAllConstants || Idx == 0)) {
5980       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5981         // Handle SSE only.
5982         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5983         EVT VecVT = MVT::v4i32;
5984         unsigned VecElts = 4;
5985
5986         // Truncate the value (which may itself be a constant) to i32, and
5987         // convert it to a vector with movd (S2V+shuffle to zero extend).
5988         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5989         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5990         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5991
5992         // Now we have our 32-bit value zero extended in the low element of
5993         // a vector.  If Idx != 0, swizzle it into place.
5994         if (Idx != 0) {
5995           SmallVector<int, 4> Mask;
5996           Mask.push_back(Idx);
5997           for (unsigned i = 1; i != VecElts; ++i)
5998             Mask.push_back(i);
5999           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6000                                       &Mask[0]);
6001         }
6002         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6003       }
6004     }
6005
6006     // If we have a constant or non-constant insertion into the low element of
6007     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6008     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6009     // depending on what the source datatype is.
6010     if (Idx == 0) {
6011       if (NumZero == 0)
6012         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6013
6014       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6015           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6016         if (VT.is256BitVector() || VT.is512BitVector()) {
6017           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6018           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6019                              Item, DAG.getIntPtrConstant(0));
6020         }
6021         assert(VT.is128BitVector() && "Expected an SSE value type!");
6022         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6023         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6024         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6025       }
6026
6027       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6028         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6029         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6030         if (VT.is256BitVector()) {
6031           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6032           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6033         } else {
6034           assert(VT.is128BitVector() && "Expected an SSE value type!");
6035           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6036         }
6037         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6038       }
6039     }
6040
6041     // Is it a vector logical left shift?
6042     if (NumElems == 2 && Idx == 1 &&
6043         X86::isZeroNode(Op.getOperand(0)) &&
6044         !X86::isZeroNode(Op.getOperand(1))) {
6045       unsigned NumBits = VT.getSizeInBits();
6046       return getVShift(true, VT,
6047                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6048                                    VT, Op.getOperand(1)),
6049                        NumBits/2, DAG, *this, dl);
6050     }
6051
6052     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6053       return SDValue();
6054
6055     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6056     // is a non-constant being inserted into an element other than the low one,
6057     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6058     // movd/movss) to move this into the low element, then shuffle it into
6059     // place.
6060     if (EVTBits == 32) {
6061       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6062
6063       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6064       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6065       SmallVector<int, 8> MaskVec;
6066       for (unsigned i = 0; i != NumElems; ++i)
6067         MaskVec.push_back(i == Idx ? 0 : 1);
6068       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6069     }
6070   }
6071
6072   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6073   if (Values.size() == 1) {
6074     if (EVTBits == 32) {
6075       // Instead of a shuffle like this:
6076       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6077       // Check if it's possible to issue this instead.
6078       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6079       unsigned Idx = countTrailingZeros(NonZeros);
6080       SDValue Item = Op.getOperand(Idx);
6081       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6082         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6083     }
6084     return SDValue();
6085   }
6086
6087   // A vector full of immediates; various special cases are already
6088   // handled, so this is best done with a single constant-pool load.
6089   if (IsAllConstants)
6090     return SDValue();
6091
6092   // For AVX-length vectors, build the individual 128-bit pieces and use
6093   // shuffles to put them in place.
6094   if (VT.is256BitVector() || VT.is512BitVector()) {
6095     SmallVector<SDValue, 64> V;
6096     for (unsigned i = 0; i != NumElems; ++i)
6097       V.push_back(Op.getOperand(i));
6098
6099     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6100
6101     // Build both the lower and upper subvector.
6102     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6103     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6104                                 NumElems/2);
6105
6106     // Recreate the wider vector with the lower and upper part.
6107     if (VT.is256BitVector())
6108       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6109     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6110   }
6111
6112   // Let legalizer expand 2-wide build_vectors.
6113   if (EVTBits == 64) {
6114     if (NumNonZero == 1) {
6115       // One half is zero or undef.
6116       unsigned Idx = countTrailingZeros(NonZeros);
6117       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6118                                  Op.getOperand(Idx));
6119       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6120     }
6121     return SDValue();
6122   }
6123
6124   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6125   if (EVTBits == 8 && NumElems == 16) {
6126     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6127                                         Subtarget, *this);
6128     if (V.getNode()) return V;
6129   }
6130
6131   if (EVTBits == 16 && NumElems == 8) {
6132     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6133                                       Subtarget, *this);
6134     if (V.getNode()) return V;
6135   }
6136
6137   // If element VT is == 32 bits, turn it into a number of shuffles.
6138   SmallVector<SDValue, 8> V(NumElems);
6139   if (NumElems == 4 && NumZero > 0) {
6140     for (unsigned i = 0; i < 4; ++i) {
6141       bool isZero = !(NonZeros & (1 << i));
6142       if (isZero)
6143         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6144       else
6145         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6146     }
6147
6148     for (unsigned i = 0; i < 2; ++i) {
6149       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6150         default: break;
6151         case 0:
6152           V[i] = V[i*2];  // Must be a zero vector.
6153           break;
6154         case 1:
6155           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6156           break;
6157         case 2:
6158           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6159           break;
6160         case 3:
6161           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6162           break;
6163       }
6164     }
6165
6166     bool Reverse1 = (NonZeros & 0x3) == 2;
6167     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6168     int MaskVec[] = {
6169       Reverse1 ? 1 : 0,
6170       Reverse1 ? 0 : 1,
6171       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6172       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6173     };
6174     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6175   }
6176
6177   if (Values.size() > 1 && VT.is128BitVector()) {
6178     // Check for a build vector of consecutive loads.
6179     for (unsigned i = 0; i < NumElems; ++i)
6180       V[i] = Op.getOperand(i);
6181
6182     // Check for elements which are consecutive loads.
6183     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6184     if (LD.getNode())
6185       return LD;
6186
6187     // Check for a build vector from mostly shuffle plus few inserting.
6188     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6189     if (Sh.getNode())
6190       return Sh;
6191
6192     // For SSE 4.1, use insertps to put the high elements into the low element.
6193     if (getSubtarget()->hasSSE41()) {
6194       SDValue Result;
6195       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6196         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6197       else
6198         Result = DAG.getUNDEF(VT);
6199
6200       for (unsigned i = 1; i < NumElems; ++i) {
6201         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6202         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6203                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6204       }
6205       return Result;
6206     }
6207
6208     // Otherwise, expand into a number of unpckl*, start by extending each of
6209     // our (non-undef) elements to the full vector width with the element in the
6210     // bottom slot of the vector (which generates no code for SSE).
6211     for (unsigned i = 0; i < NumElems; ++i) {
6212       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6213         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6214       else
6215         V[i] = DAG.getUNDEF(VT);
6216     }
6217
6218     // Next, we iteratively mix elements, e.g. for v4f32:
6219     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6220     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6221     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6222     unsigned EltStride = NumElems >> 1;
6223     while (EltStride != 0) {
6224       for (unsigned i = 0; i < EltStride; ++i) {
6225         // If V[i+EltStride] is undef and this is the first round of mixing,
6226         // then it is safe to just drop this shuffle: V[i] is already in the
6227         // right place, the one element (since it's the first round) being
6228         // inserted as undef can be dropped.  This isn't safe for successive
6229         // rounds because they will permute elements within both vectors.
6230         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6231             EltStride == NumElems/2)
6232           continue;
6233
6234         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6235       }
6236       EltStride >>= 1;
6237     }
6238     return V[0];
6239   }
6240   return SDValue();
6241 }
6242
6243 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6244 // to create 256-bit vectors from two other 128-bit ones.
6245 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6246   SDLoc dl(Op);
6247   MVT ResVT = Op.getSimpleValueType();
6248
6249   assert((ResVT.is256BitVector() ||
6250           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6251
6252   SDValue V1 = Op.getOperand(0);
6253   SDValue V2 = Op.getOperand(1);
6254   unsigned NumElems = ResVT.getVectorNumElements();
6255   if(ResVT.is256BitVector())
6256     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6257
6258   if (Op.getNumOperands() == 4) {
6259     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6260                                 ResVT.getVectorNumElements()/2);
6261     SDValue V3 = Op.getOperand(2);
6262     SDValue V4 = Op.getOperand(3);
6263     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6264       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6265   }
6266   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6267 }
6268
6269 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6270   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6271   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6272          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6273           Op.getNumOperands() == 4)));
6274
6275   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6276   // from two other 128-bit ones.
6277
6278   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6279   return LowerAVXCONCAT_VECTORS(Op, DAG);
6280 }
6281
6282 // Try to lower a shuffle node into a simple blend instruction.
6283 static SDValue
6284 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6285                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6286   SDValue V1 = SVOp->getOperand(0);
6287   SDValue V2 = SVOp->getOperand(1);
6288   SDLoc dl(SVOp);
6289   MVT VT = SVOp->getSimpleValueType(0);
6290   MVT EltVT = VT.getVectorElementType();
6291   unsigned NumElems = VT.getVectorNumElements();
6292
6293   // There is no blend with immediate in AVX-512.
6294   if (VT.is512BitVector())
6295     return SDValue();
6296
6297   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6298     return SDValue();
6299   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6300     return SDValue();
6301
6302   // Check the mask for BLEND and build the value.
6303   unsigned MaskValue = 0;
6304   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6305   unsigned NumLanes = (NumElems-1)/8 + 1;
6306   unsigned NumElemsInLane = NumElems / NumLanes;
6307
6308   // Blend for v16i16 should be symetric for the both lanes.
6309   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6310
6311     int SndLaneEltIdx = (NumLanes == 2) ?
6312       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6313     int EltIdx = SVOp->getMaskElt(i);
6314
6315     if ((EltIdx < 0 || EltIdx == (int)i) &&
6316         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6317       continue;
6318
6319     if (((unsigned)EltIdx == (i + NumElems)) &&
6320         (SndLaneEltIdx < 0 ||
6321          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6322       MaskValue |= (1<<i);
6323     else
6324       return SDValue();
6325   }
6326
6327   // Convert i32 vectors to floating point if it is not AVX2.
6328   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6329   MVT BlendVT = VT;
6330   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6331     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6332                                NumElems);
6333     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6334     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6335   }
6336
6337   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6338                             DAG.getConstant(MaskValue, MVT::i32));
6339   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6340 }
6341
6342 /// In vector type \p VT, return true if the element at index \p InputIdx
6343 /// falls on a different 128-bit lane than \p OutputIdx.
6344 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6345                                      unsigned OutputIdx) {
6346   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6347   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6348 }
6349
6350 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6351 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6352 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6353 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6354 /// zero.
6355 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6356                          SelectionDAG &DAG) {
6357   MVT VT = V1.getSimpleValueType();
6358   assert(VT.is128BitVector() || VT.is256BitVector());
6359
6360   MVT EltVT = VT.getVectorElementType();
6361   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6362   unsigned NumElts = VT.getVectorNumElements();
6363
6364   SmallVector<SDValue, 32> PshufbMask;
6365   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6366     int InputIdx = MaskVals[OutputIdx];
6367     unsigned InputByteIdx;
6368
6369     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6370       InputByteIdx = 0x80;
6371     else {
6372       // Cross lane is not allowed.
6373       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6374         return SDValue();
6375       InputByteIdx = InputIdx * EltSizeInBytes;
6376       // Index is an byte offset within the 128-bit lane.
6377       InputByteIdx &= 0xf;
6378     }
6379
6380     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6381       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6382       if (InputByteIdx != 0x80)
6383         ++InputByteIdx;
6384     }
6385   }
6386
6387   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6388   if (ShufVT != VT)
6389     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6390   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6391                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6392                                  PshufbMask.data(), PshufbMask.size()));
6393 }
6394
6395 // v8i16 shuffles - Prefer shuffles in the following order:
6396 // 1. [all]   pshuflw, pshufhw, optional move
6397 // 2. [ssse3] 1 x pshufb
6398 // 3. [ssse3] 2 x pshufb + 1 x por
6399 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6400 static SDValue
6401 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6402                          SelectionDAG &DAG) {
6403   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6404   SDValue V1 = SVOp->getOperand(0);
6405   SDValue V2 = SVOp->getOperand(1);
6406   SDLoc dl(SVOp);
6407   SmallVector<int, 8> MaskVals;
6408
6409   // Determine if more than 1 of the words in each of the low and high quadwords
6410   // of the result come from the same quadword of one of the two inputs.  Undef
6411   // mask values count as coming from any quadword, for better codegen.
6412   //
6413   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6414   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6415   unsigned LoQuad[] = { 0, 0, 0, 0 };
6416   unsigned HiQuad[] = { 0, 0, 0, 0 };
6417   // Indices of quads used.
6418   std::bitset<4> InputQuads;
6419   for (unsigned i = 0; i < 8; ++i) {
6420     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6421     int EltIdx = SVOp->getMaskElt(i);
6422     MaskVals.push_back(EltIdx);
6423     if (EltIdx < 0) {
6424       ++Quad[0];
6425       ++Quad[1];
6426       ++Quad[2];
6427       ++Quad[3];
6428       continue;
6429     }
6430     ++Quad[EltIdx / 4];
6431     InputQuads.set(EltIdx / 4);
6432   }
6433
6434   int BestLoQuad = -1;
6435   unsigned MaxQuad = 1;
6436   for (unsigned i = 0; i < 4; ++i) {
6437     if (LoQuad[i] > MaxQuad) {
6438       BestLoQuad = i;
6439       MaxQuad = LoQuad[i];
6440     }
6441   }
6442
6443   int BestHiQuad = -1;
6444   MaxQuad = 1;
6445   for (unsigned i = 0; i < 4; ++i) {
6446     if (HiQuad[i] > MaxQuad) {
6447       BestHiQuad = i;
6448       MaxQuad = HiQuad[i];
6449     }
6450   }
6451
6452   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6453   // of the two input vectors, shuffle them into one input vector so only a
6454   // single pshufb instruction is necessary. If there are more than 2 input
6455   // quads, disable the next transformation since it does not help SSSE3.
6456   bool V1Used = InputQuads[0] || InputQuads[1];
6457   bool V2Used = InputQuads[2] || InputQuads[3];
6458   if (Subtarget->hasSSSE3()) {
6459     if (InputQuads.count() == 2 && V1Used && V2Used) {
6460       BestLoQuad = InputQuads[0] ? 0 : 1;
6461       BestHiQuad = InputQuads[2] ? 2 : 3;
6462     }
6463     if (InputQuads.count() > 2) {
6464       BestLoQuad = -1;
6465       BestHiQuad = -1;
6466     }
6467   }
6468
6469   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6470   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6471   // words from all 4 input quadwords.
6472   SDValue NewV;
6473   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6474     int MaskV[] = {
6475       BestLoQuad < 0 ? 0 : BestLoQuad,
6476       BestHiQuad < 0 ? 1 : BestHiQuad
6477     };
6478     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6479                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6480                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6481     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6482
6483     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6484     // source words for the shuffle, to aid later transformations.
6485     bool AllWordsInNewV = true;
6486     bool InOrder[2] = { true, true };
6487     for (unsigned i = 0; i != 8; ++i) {
6488       int idx = MaskVals[i];
6489       if (idx != (int)i)
6490         InOrder[i/4] = false;
6491       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6492         continue;
6493       AllWordsInNewV = false;
6494       break;
6495     }
6496
6497     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6498     if (AllWordsInNewV) {
6499       for (int i = 0; i != 8; ++i) {
6500         int idx = MaskVals[i];
6501         if (idx < 0)
6502           continue;
6503         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6504         if ((idx != i) && idx < 4)
6505           pshufhw = false;
6506         if ((idx != i) && idx > 3)
6507           pshuflw = false;
6508       }
6509       V1 = NewV;
6510       V2Used = false;
6511       BestLoQuad = 0;
6512       BestHiQuad = 1;
6513     }
6514
6515     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6516     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6517     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6518       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6519       unsigned TargetMask = 0;
6520       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6521                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6522       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6523       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6524                              getShufflePSHUFLWImmediate(SVOp);
6525       V1 = NewV.getOperand(0);
6526       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6527     }
6528   }
6529
6530   // Promote splats to a larger type which usually leads to more efficient code.
6531   // FIXME: Is this true if pshufb is available?
6532   if (SVOp->isSplat())
6533     return PromoteSplat(SVOp, DAG);
6534
6535   // If we have SSSE3, and all words of the result are from 1 input vector,
6536   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6537   // is present, fall back to case 4.
6538   if (Subtarget->hasSSSE3()) {
6539     SmallVector<SDValue,16> pshufbMask;
6540
6541     // If we have elements from both input vectors, set the high bit of the
6542     // shuffle mask element to zero out elements that come from V2 in the V1
6543     // mask, and elements that come from V1 in the V2 mask, so that the two
6544     // results can be OR'd together.
6545     bool TwoInputs = V1Used && V2Used;
6546     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6547     if (!TwoInputs)
6548       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6549
6550     // Calculate the shuffle mask for the second input, shuffle it, and
6551     // OR it with the first shuffled input.
6552     CommuteVectorShuffleMask(MaskVals, 8);
6553     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6554     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6555     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6556   }
6557
6558   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6559   // and update MaskVals with new element order.
6560   std::bitset<8> InOrder;
6561   if (BestLoQuad >= 0) {
6562     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6563     for (int i = 0; i != 4; ++i) {
6564       int idx = MaskVals[i];
6565       if (idx < 0) {
6566         InOrder.set(i);
6567       } else if ((idx / 4) == BestLoQuad) {
6568         MaskV[i] = idx & 3;
6569         InOrder.set(i);
6570       }
6571     }
6572     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6573                                 &MaskV[0]);
6574
6575     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6576       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6577       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6578                                   NewV.getOperand(0),
6579                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6580     }
6581   }
6582
6583   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6584   // and update MaskVals with the new element order.
6585   if (BestHiQuad >= 0) {
6586     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6587     for (unsigned i = 4; i != 8; ++i) {
6588       int idx = MaskVals[i];
6589       if (idx < 0) {
6590         InOrder.set(i);
6591       } else if ((idx / 4) == BestHiQuad) {
6592         MaskV[i] = (idx & 3) + 4;
6593         InOrder.set(i);
6594       }
6595     }
6596     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6597                                 &MaskV[0]);
6598
6599     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6600       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6601       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6602                                   NewV.getOperand(0),
6603                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6604     }
6605   }
6606
6607   // In case BestHi & BestLo were both -1, which means each quadword has a word
6608   // from each of the four input quadwords, calculate the InOrder bitvector now
6609   // before falling through to the insert/extract cleanup.
6610   if (BestLoQuad == -1 && BestHiQuad == -1) {
6611     NewV = V1;
6612     for (int i = 0; i != 8; ++i)
6613       if (MaskVals[i] < 0 || MaskVals[i] == i)
6614         InOrder.set(i);
6615   }
6616
6617   // The other elements are put in the right place using pextrw and pinsrw.
6618   for (unsigned i = 0; i != 8; ++i) {
6619     if (InOrder[i])
6620       continue;
6621     int EltIdx = MaskVals[i];
6622     if (EltIdx < 0)
6623       continue;
6624     SDValue ExtOp = (EltIdx < 8) ?
6625       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6626                   DAG.getIntPtrConstant(EltIdx)) :
6627       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6628                   DAG.getIntPtrConstant(EltIdx - 8));
6629     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6630                        DAG.getIntPtrConstant(i));
6631   }
6632   return NewV;
6633 }
6634
6635 /// \brief v16i16 shuffles
6636 ///
6637 /// FIXME: We only support generation of a single pshufb currently.  We can
6638 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6639 /// well (e.g 2 x pshufb + 1 x por).
6640 static SDValue
6641 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6642   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6643   SDValue V1 = SVOp->getOperand(0);
6644   SDValue V2 = SVOp->getOperand(1);
6645   SDLoc dl(SVOp);
6646
6647   if (V2.getOpcode() != ISD::UNDEF)
6648     return SDValue();
6649
6650   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6651   return getPSHUFB(MaskVals, V1, dl, DAG);
6652 }
6653
6654 // v16i8 shuffles - Prefer shuffles in the following order:
6655 // 1. [ssse3] 1 x pshufb
6656 // 2. [ssse3] 2 x pshufb + 1 x por
6657 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6658 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6659                                         const X86Subtarget* Subtarget,
6660                                         SelectionDAG &DAG) {
6661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6662   SDValue V1 = SVOp->getOperand(0);
6663   SDValue V2 = SVOp->getOperand(1);
6664   SDLoc dl(SVOp);
6665   ArrayRef<int> MaskVals = SVOp->getMask();
6666
6667   // Promote splats to a larger type which usually leads to more efficient code.
6668   // FIXME: Is this true if pshufb is available?
6669   if (SVOp->isSplat())
6670     return PromoteSplat(SVOp, DAG);
6671
6672   // If we have SSSE3, case 1 is generated when all result bytes come from
6673   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6674   // present, fall back to case 3.
6675
6676   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6677   if (Subtarget->hasSSSE3()) {
6678     SmallVector<SDValue,16> pshufbMask;
6679
6680     // If all result elements are from one input vector, then only translate
6681     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6682     //
6683     // Otherwise, we have elements from both input vectors, and must zero out
6684     // elements that come from V2 in the first mask, and V1 in the second mask
6685     // so that we can OR them together.
6686     for (unsigned i = 0; i != 16; ++i) {
6687       int EltIdx = MaskVals[i];
6688       if (EltIdx < 0 || EltIdx >= 16)
6689         EltIdx = 0x80;
6690       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6691     }
6692     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6693                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6694                                  MVT::v16i8, &pshufbMask[0], 16));
6695
6696     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6697     // the 2nd operand if it's undefined or zero.
6698     if (V2.getOpcode() == ISD::UNDEF ||
6699         ISD::isBuildVectorAllZeros(V2.getNode()))
6700       return V1;
6701
6702     // Calculate the shuffle mask for the second input, shuffle it, and
6703     // OR it with the first shuffled input.
6704     pshufbMask.clear();
6705     for (unsigned i = 0; i != 16; ++i) {
6706       int EltIdx = MaskVals[i];
6707       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6708       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6709     }
6710     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6711                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6712                                  MVT::v16i8, &pshufbMask[0], 16));
6713     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6714   }
6715
6716   // No SSSE3 - Calculate in place words and then fix all out of place words
6717   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6718   // the 16 different words that comprise the two doublequadword input vectors.
6719   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6720   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6721   SDValue NewV = V1;
6722   for (int i = 0; i != 8; ++i) {
6723     int Elt0 = MaskVals[i*2];
6724     int Elt1 = MaskVals[i*2+1];
6725
6726     // This word of the result is all undef, skip it.
6727     if (Elt0 < 0 && Elt1 < 0)
6728       continue;
6729
6730     // This word of the result is already in the correct place, skip it.
6731     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6732       continue;
6733
6734     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6735     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6736     SDValue InsElt;
6737
6738     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6739     // using a single extract together, load it and store it.
6740     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6741       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6742                            DAG.getIntPtrConstant(Elt1 / 2));
6743       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6744                         DAG.getIntPtrConstant(i));
6745       continue;
6746     }
6747
6748     // If Elt1 is defined, extract it from the appropriate source.  If the
6749     // source byte is not also odd, shift the extracted word left 8 bits
6750     // otherwise clear the bottom 8 bits if we need to do an or.
6751     if (Elt1 >= 0) {
6752       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6753                            DAG.getIntPtrConstant(Elt1 / 2));
6754       if ((Elt1 & 1) == 0)
6755         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6756                              DAG.getConstant(8,
6757                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6758       else if (Elt0 >= 0)
6759         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6760                              DAG.getConstant(0xFF00, MVT::i16));
6761     }
6762     // If Elt0 is defined, extract it from the appropriate source.  If the
6763     // source byte is not also even, shift the extracted word right 8 bits. If
6764     // Elt1 was also defined, OR the extracted values together before
6765     // inserting them in the result.
6766     if (Elt0 >= 0) {
6767       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6768                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6769       if ((Elt0 & 1) != 0)
6770         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6771                               DAG.getConstant(8,
6772                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6773       else if (Elt1 >= 0)
6774         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6775                              DAG.getConstant(0x00FF, MVT::i16));
6776       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6777                          : InsElt0;
6778     }
6779     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6780                        DAG.getIntPtrConstant(i));
6781   }
6782   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6783 }
6784
6785 // v32i8 shuffles - Translate to VPSHUFB if possible.
6786 static
6787 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6788                                  const X86Subtarget *Subtarget,
6789                                  SelectionDAG &DAG) {
6790   MVT VT = SVOp->getSimpleValueType(0);
6791   SDValue V1 = SVOp->getOperand(0);
6792   SDValue V2 = SVOp->getOperand(1);
6793   SDLoc dl(SVOp);
6794   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6795
6796   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6797   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6798   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6799
6800   // VPSHUFB may be generated if
6801   // (1) one of input vector is undefined or zeroinitializer.
6802   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6803   // And (2) the mask indexes don't cross the 128-bit lane.
6804   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6805       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6806     return SDValue();
6807
6808   if (V1IsAllZero && !V2IsAllZero) {
6809     CommuteVectorShuffleMask(MaskVals, 32);
6810     V1 = V2;
6811   }
6812   return getPSHUFB(MaskVals, V1, dl, DAG);
6813 }
6814
6815 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6816 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6817 /// done when every pair / quad of shuffle mask elements point to elements in
6818 /// the right sequence. e.g.
6819 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6820 static
6821 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6822                                  SelectionDAG &DAG) {
6823   MVT VT = SVOp->getSimpleValueType(0);
6824   SDLoc dl(SVOp);
6825   unsigned NumElems = VT.getVectorNumElements();
6826   MVT NewVT;
6827   unsigned Scale;
6828   switch (VT.SimpleTy) {
6829   default: llvm_unreachable("Unexpected!");
6830   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6831   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6832   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6833   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6834   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6835   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6836   }
6837
6838   SmallVector<int, 8> MaskVec;
6839   for (unsigned i = 0; i != NumElems; i += Scale) {
6840     int StartIdx = -1;
6841     for (unsigned j = 0; j != Scale; ++j) {
6842       int EltIdx = SVOp->getMaskElt(i+j);
6843       if (EltIdx < 0)
6844         continue;
6845       if (StartIdx < 0)
6846         StartIdx = (EltIdx / Scale);
6847       if (EltIdx != (int)(StartIdx*Scale + j))
6848         return SDValue();
6849     }
6850     MaskVec.push_back(StartIdx);
6851   }
6852
6853   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6854   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6855   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6856 }
6857
6858 /// getVZextMovL - Return a zero-extending vector move low node.
6859 ///
6860 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6861                             SDValue SrcOp, SelectionDAG &DAG,
6862                             const X86Subtarget *Subtarget, SDLoc dl) {
6863   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6864     LoadSDNode *LD = NULL;
6865     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6866       LD = dyn_cast<LoadSDNode>(SrcOp);
6867     if (!LD) {
6868       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6869       // instead.
6870       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6871       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6872           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6873           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6874           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6875         // PR2108
6876         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6877         return DAG.getNode(ISD::BITCAST, dl, VT,
6878                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6879                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6880                                                    OpVT,
6881                                                    SrcOp.getOperand(0)
6882                                                           .getOperand(0))));
6883       }
6884     }
6885   }
6886
6887   return DAG.getNode(ISD::BITCAST, dl, VT,
6888                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6889                                  DAG.getNode(ISD::BITCAST, dl,
6890                                              OpVT, SrcOp)));
6891 }
6892
6893 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6894 /// which could not be matched by any known target speficic shuffle
6895 static SDValue
6896 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6897
6898   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6899   if (NewOp.getNode())
6900     return NewOp;
6901
6902   MVT VT = SVOp->getSimpleValueType(0);
6903
6904   unsigned NumElems = VT.getVectorNumElements();
6905   unsigned NumLaneElems = NumElems / 2;
6906
6907   SDLoc dl(SVOp);
6908   MVT EltVT = VT.getVectorElementType();
6909   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6910   SDValue Output[2];
6911
6912   SmallVector<int, 16> Mask;
6913   for (unsigned l = 0; l < 2; ++l) {
6914     // Build a shuffle mask for the output, discovering on the fly which
6915     // input vectors to use as shuffle operands (recorded in InputUsed).
6916     // If building a suitable shuffle vector proves too hard, then bail
6917     // out with UseBuildVector set.
6918     bool UseBuildVector = false;
6919     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6920     unsigned LaneStart = l * NumLaneElems;
6921     for (unsigned i = 0; i != NumLaneElems; ++i) {
6922       // The mask element.  This indexes into the input.
6923       int Idx = SVOp->getMaskElt(i+LaneStart);
6924       if (Idx < 0) {
6925         // the mask element does not index into any input vector.
6926         Mask.push_back(-1);
6927         continue;
6928       }
6929
6930       // The input vector this mask element indexes into.
6931       int Input = Idx / NumLaneElems;
6932
6933       // Turn the index into an offset from the start of the input vector.
6934       Idx -= Input * NumLaneElems;
6935
6936       // Find or create a shuffle vector operand to hold this input.
6937       unsigned OpNo;
6938       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6939         if (InputUsed[OpNo] == Input)
6940           // This input vector is already an operand.
6941           break;
6942         if (InputUsed[OpNo] < 0) {
6943           // Create a new operand for this input vector.
6944           InputUsed[OpNo] = Input;
6945           break;
6946         }
6947       }
6948
6949       if (OpNo >= array_lengthof(InputUsed)) {
6950         // More than two input vectors used!  Give up on trying to create a
6951         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6952         UseBuildVector = true;
6953         break;
6954       }
6955
6956       // Add the mask index for the new shuffle vector.
6957       Mask.push_back(Idx + OpNo * NumLaneElems);
6958     }
6959
6960     if (UseBuildVector) {
6961       SmallVector<SDValue, 16> SVOps;
6962       for (unsigned i = 0; i != NumLaneElems; ++i) {
6963         // The mask element.  This indexes into the input.
6964         int Idx = SVOp->getMaskElt(i+LaneStart);
6965         if (Idx < 0) {
6966           SVOps.push_back(DAG.getUNDEF(EltVT));
6967           continue;
6968         }
6969
6970         // The input vector this mask element indexes into.
6971         int Input = Idx / NumElems;
6972
6973         // Turn the index into an offset from the start of the input vector.
6974         Idx -= Input * NumElems;
6975
6976         // Extract the vector element by hand.
6977         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6978                                     SVOp->getOperand(Input),
6979                                     DAG.getIntPtrConstant(Idx)));
6980       }
6981
6982       // Construct the output using a BUILD_VECTOR.
6983       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6984                               SVOps.size());
6985     } else if (InputUsed[0] < 0) {
6986       // No input vectors were used! The result is undefined.
6987       Output[l] = DAG.getUNDEF(NVT);
6988     } else {
6989       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6990                                         (InputUsed[0] % 2) * NumLaneElems,
6991                                         DAG, dl);
6992       // If only one input was used, use an undefined vector for the other.
6993       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6994         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6995                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6996       // At least one input vector was used. Create a new shuffle vector.
6997       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6998     }
6999
7000     Mask.clear();
7001   }
7002
7003   // Concatenate the result back
7004   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7005 }
7006
7007 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7008 /// 4 elements, and match them with several different shuffle types.
7009 static SDValue
7010 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7011   SDValue V1 = SVOp->getOperand(0);
7012   SDValue V2 = SVOp->getOperand(1);
7013   SDLoc dl(SVOp);
7014   MVT VT = SVOp->getSimpleValueType(0);
7015
7016   assert(VT.is128BitVector() && "Unsupported vector size");
7017
7018   std::pair<int, int> Locs[4];
7019   int Mask1[] = { -1, -1, -1, -1 };
7020   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7021
7022   unsigned NumHi = 0;
7023   unsigned NumLo = 0;
7024   for (unsigned i = 0; i != 4; ++i) {
7025     int Idx = PermMask[i];
7026     if (Idx < 0) {
7027       Locs[i] = std::make_pair(-1, -1);
7028     } else {
7029       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7030       if (Idx < 4) {
7031         Locs[i] = std::make_pair(0, NumLo);
7032         Mask1[NumLo] = Idx;
7033         NumLo++;
7034       } else {
7035         Locs[i] = std::make_pair(1, NumHi);
7036         if (2+NumHi < 4)
7037           Mask1[2+NumHi] = Idx;
7038         NumHi++;
7039       }
7040     }
7041   }
7042
7043   if (NumLo <= 2 && NumHi <= 2) {
7044     // If no more than two elements come from either vector. This can be
7045     // implemented with two shuffles. First shuffle gather the elements.
7046     // The second shuffle, which takes the first shuffle as both of its
7047     // vector operands, put the elements into the right order.
7048     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7049
7050     int Mask2[] = { -1, -1, -1, -1 };
7051
7052     for (unsigned i = 0; i != 4; ++i)
7053       if (Locs[i].first != -1) {
7054         unsigned Idx = (i < 2) ? 0 : 4;
7055         Idx += Locs[i].first * 2 + Locs[i].second;
7056         Mask2[i] = Idx;
7057       }
7058
7059     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7060   }
7061
7062   if (NumLo == 3 || NumHi == 3) {
7063     // Otherwise, we must have three elements from one vector, call it X, and
7064     // one element from the other, call it Y.  First, use a shufps to build an
7065     // intermediate vector with the one element from Y and the element from X
7066     // that will be in the same half in the final destination (the indexes don't
7067     // matter). Then, use a shufps to build the final vector, taking the half
7068     // containing the element from Y from the intermediate, and the other half
7069     // from X.
7070     if (NumHi == 3) {
7071       // Normalize it so the 3 elements come from V1.
7072       CommuteVectorShuffleMask(PermMask, 4);
7073       std::swap(V1, V2);
7074     }
7075
7076     // Find the element from V2.
7077     unsigned HiIndex;
7078     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7079       int Val = PermMask[HiIndex];
7080       if (Val < 0)
7081         continue;
7082       if (Val >= 4)
7083         break;
7084     }
7085
7086     Mask1[0] = PermMask[HiIndex];
7087     Mask1[1] = -1;
7088     Mask1[2] = PermMask[HiIndex^1];
7089     Mask1[3] = -1;
7090     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7091
7092     if (HiIndex >= 2) {
7093       Mask1[0] = PermMask[0];
7094       Mask1[1] = PermMask[1];
7095       Mask1[2] = HiIndex & 1 ? 6 : 4;
7096       Mask1[3] = HiIndex & 1 ? 4 : 6;
7097       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7098     }
7099
7100     Mask1[0] = HiIndex & 1 ? 2 : 0;
7101     Mask1[1] = HiIndex & 1 ? 0 : 2;
7102     Mask1[2] = PermMask[2];
7103     Mask1[3] = PermMask[3];
7104     if (Mask1[2] >= 0)
7105       Mask1[2] += 4;
7106     if (Mask1[3] >= 0)
7107       Mask1[3] += 4;
7108     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7109   }
7110
7111   // Break it into (shuffle shuffle_hi, shuffle_lo).
7112   int LoMask[] = { -1, -1, -1, -1 };
7113   int HiMask[] = { -1, -1, -1, -1 };
7114
7115   int *MaskPtr = LoMask;
7116   unsigned MaskIdx = 0;
7117   unsigned LoIdx = 0;
7118   unsigned HiIdx = 2;
7119   for (unsigned i = 0; i != 4; ++i) {
7120     if (i == 2) {
7121       MaskPtr = HiMask;
7122       MaskIdx = 1;
7123       LoIdx = 0;
7124       HiIdx = 2;
7125     }
7126     int Idx = PermMask[i];
7127     if (Idx < 0) {
7128       Locs[i] = std::make_pair(-1, -1);
7129     } else if (Idx < 4) {
7130       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7131       MaskPtr[LoIdx] = Idx;
7132       LoIdx++;
7133     } else {
7134       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7135       MaskPtr[HiIdx] = Idx;
7136       HiIdx++;
7137     }
7138   }
7139
7140   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7141   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7142   int MaskOps[] = { -1, -1, -1, -1 };
7143   for (unsigned i = 0; i != 4; ++i)
7144     if (Locs[i].first != -1)
7145       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7146   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7147 }
7148
7149 static bool MayFoldVectorLoad(SDValue V) {
7150   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7151     V = V.getOperand(0);
7152
7153   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7154     V = V.getOperand(0);
7155   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7156       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7157     // BUILD_VECTOR (load), undef
7158     V = V.getOperand(0);
7159
7160   return MayFoldLoad(V);
7161 }
7162
7163 static
7164 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7165   MVT VT = Op.getSimpleValueType();
7166
7167   // Canonizalize to v2f64.
7168   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7169   return DAG.getNode(ISD::BITCAST, dl, VT,
7170                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7171                                           V1, DAG));
7172 }
7173
7174 static
7175 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7176                         bool HasSSE2) {
7177   SDValue V1 = Op.getOperand(0);
7178   SDValue V2 = Op.getOperand(1);
7179   MVT VT = Op.getSimpleValueType();
7180
7181   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7182
7183   if (HasSSE2 && VT == MVT::v2f64)
7184     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7185
7186   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7187   return DAG.getNode(ISD::BITCAST, dl, VT,
7188                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7189                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7190                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7191 }
7192
7193 static
7194 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7195   SDValue V1 = Op.getOperand(0);
7196   SDValue V2 = Op.getOperand(1);
7197   MVT VT = Op.getSimpleValueType();
7198
7199   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7200          "unsupported shuffle type");
7201
7202   if (V2.getOpcode() == ISD::UNDEF)
7203     V2 = V1;
7204
7205   // v4i32 or v4f32
7206   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7207 }
7208
7209 static
7210 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7211   SDValue V1 = Op.getOperand(0);
7212   SDValue V2 = Op.getOperand(1);
7213   MVT VT = Op.getSimpleValueType();
7214   unsigned NumElems = VT.getVectorNumElements();
7215
7216   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7217   // operand of these instructions is only memory, so check if there's a
7218   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7219   // same masks.
7220   bool CanFoldLoad = false;
7221
7222   // Trivial case, when V2 comes from a load.
7223   if (MayFoldVectorLoad(V2))
7224     CanFoldLoad = true;
7225
7226   // When V1 is a load, it can be folded later into a store in isel, example:
7227   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7228   //    turns into:
7229   //  (MOVLPSmr addr:$src1, VR128:$src2)
7230   // So, recognize this potential and also use MOVLPS or MOVLPD
7231   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7232     CanFoldLoad = true;
7233
7234   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7235   if (CanFoldLoad) {
7236     if (HasSSE2 && NumElems == 2)
7237       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7238
7239     if (NumElems == 4)
7240       // If we don't care about the second element, proceed to use movss.
7241       if (SVOp->getMaskElt(1) != -1)
7242         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7243   }
7244
7245   // movl and movlp will both match v2i64, but v2i64 is never matched by
7246   // movl earlier because we make it strict to avoid messing with the movlp load
7247   // folding logic (see the code above getMOVLP call). Match it here then,
7248   // this is horrible, but will stay like this until we move all shuffle
7249   // matching to x86 specific nodes. Note that for the 1st condition all
7250   // types are matched with movsd.
7251   if (HasSSE2) {
7252     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7253     // as to remove this logic from here, as much as possible
7254     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7255       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7256     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7257   }
7258
7259   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7260
7261   // Invert the operand order and use SHUFPS to match it.
7262   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7263                               getShuffleSHUFImmediate(SVOp), DAG);
7264 }
7265
7266 // Reduce a vector shuffle to zext.
7267 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7268                                     SelectionDAG &DAG) {
7269   // PMOVZX is only available from SSE41.
7270   if (!Subtarget->hasSSE41())
7271     return SDValue();
7272
7273   MVT VT = Op.getSimpleValueType();
7274
7275   // Only AVX2 support 256-bit vector integer extending.
7276   if (!Subtarget->hasInt256() && VT.is256BitVector())
7277     return SDValue();
7278
7279   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7280   SDLoc DL(Op);
7281   SDValue V1 = Op.getOperand(0);
7282   SDValue V2 = Op.getOperand(1);
7283   unsigned NumElems = VT.getVectorNumElements();
7284
7285   // Extending is an unary operation and the element type of the source vector
7286   // won't be equal to or larger than i64.
7287   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7288       VT.getVectorElementType() == MVT::i64)
7289     return SDValue();
7290
7291   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7292   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7293   while ((1U << Shift) < NumElems) {
7294     if (SVOp->getMaskElt(1U << Shift) == 1)
7295       break;
7296     Shift += 1;
7297     // The maximal ratio is 8, i.e. from i8 to i64.
7298     if (Shift > 3)
7299       return SDValue();
7300   }
7301
7302   // Check the shuffle mask.
7303   unsigned Mask = (1U << Shift) - 1;
7304   for (unsigned i = 0; i != NumElems; ++i) {
7305     int EltIdx = SVOp->getMaskElt(i);
7306     if ((i & Mask) != 0 && EltIdx != -1)
7307       return SDValue();
7308     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7309       return SDValue();
7310   }
7311
7312   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7313   MVT NeVT = MVT::getIntegerVT(NBits);
7314   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7315
7316   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7317     return SDValue();
7318
7319   // Simplify the operand as it's prepared to be fed into shuffle.
7320   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7321   if (V1.getOpcode() == ISD::BITCAST &&
7322       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7323       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7324       V1.getOperand(0).getOperand(0)
7325         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7326     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7327     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7328     ConstantSDNode *CIdx =
7329       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7330     // If it's foldable, i.e. normal load with single use, we will let code
7331     // selection to fold it. Otherwise, we will short the conversion sequence.
7332     if (CIdx && CIdx->getZExtValue() == 0 &&
7333         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7334       MVT FullVT = V.getSimpleValueType();
7335       MVT V1VT = V1.getSimpleValueType();
7336       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7337         // The "ext_vec_elt" node is wider than the result node.
7338         // In this case we should extract subvector from V.
7339         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7340         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7341         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7342                                         FullVT.getVectorNumElements()/Ratio);
7343         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7344                         DAG.getIntPtrConstant(0));
7345       }
7346       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7347     }
7348   }
7349
7350   return DAG.getNode(ISD::BITCAST, DL, VT,
7351                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7352 }
7353
7354 static SDValue
7355 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7356                        SelectionDAG &DAG) {
7357   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7358   MVT VT = Op.getSimpleValueType();
7359   SDLoc dl(Op);
7360   SDValue V1 = Op.getOperand(0);
7361   SDValue V2 = Op.getOperand(1);
7362
7363   if (isZeroShuffle(SVOp))
7364     return getZeroVector(VT, Subtarget, DAG, dl);
7365
7366   // Handle splat operations
7367   if (SVOp->isSplat()) {
7368     // Use vbroadcast whenever the splat comes from a foldable load
7369     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7370     if (Broadcast.getNode())
7371       return Broadcast;
7372   }
7373
7374   // Check integer expanding shuffles.
7375   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7376   if (NewOp.getNode())
7377     return NewOp;
7378
7379   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7380   // do it!
7381   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7382       VT == MVT::v16i16 || VT == MVT::v32i8) {
7383     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7384     if (NewOp.getNode())
7385       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7386   } else if ((VT == MVT::v4i32 ||
7387              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7388     // FIXME: Figure out a cleaner way to do this.
7389     // Try to make use of movq to zero out the top part.
7390     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7391       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7392       if (NewOp.getNode()) {
7393         MVT NewVT = NewOp.getSimpleValueType();
7394         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7395                                NewVT, true, false))
7396           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7397                               DAG, Subtarget, dl);
7398       }
7399     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7400       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7401       if (NewOp.getNode()) {
7402         MVT NewVT = NewOp.getSimpleValueType();
7403         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7404           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7405                               DAG, Subtarget, dl);
7406       }
7407     }
7408   }
7409   return SDValue();
7410 }
7411
7412 SDValue
7413 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7414   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7415   SDValue V1 = Op.getOperand(0);
7416   SDValue V2 = Op.getOperand(1);
7417   MVT VT = Op.getSimpleValueType();
7418   SDLoc dl(Op);
7419   unsigned NumElems = VT.getVectorNumElements();
7420   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7421   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7422   bool V1IsSplat = false;
7423   bool V2IsSplat = false;
7424   bool HasSSE2 = Subtarget->hasSSE2();
7425   bool HasFp256    = Subtarget->hasFp256();
7426   bool HasInt256   = Subtarget->hasInt256();
7427   MachineFunction &MF = DAG.getMachineFunction();
7428   bool OptForSize = MF.getFunction()->getAttributes().
7429     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7430
7431   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7432
7433   if (V1IsUndef && V2IsUndef)
7434     return DAG.getUNDEF(VT);
7435
7436   // When we create a shuffle node we put the UNDEF node to second operand,
7437   // but in some cases the first operand may be transformed to UNDEF.
7438   // In this case we should just commute the node.
7439   if (V1IsUndef)
7440     return CommuteVectorShuffle(SVOp, DAG);
7441
7442   // Vector shuffle lowering takes 3 steps:
7443   //
7444   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7445   //    narrowing and commutation of operands should be handled.
7446   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7447   //    shuffle nodes.
7448   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7449   //    so the shuffle can be broken into other shuffles and the legalizer can
7450   //    try the lowering again.
7451   //
7452   // The general idea is that no vector_shuffle operation should be left to
7453   // be matched during isel, all of them must be converted to a target specific
7454   // node here.
7455
7456   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7457   // narrowing and commutation of operands should be handled. The actual code
7458   // doesn't include all of those, work in progress...
7459   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7460   if (NewOp.getNode())
7461     return NewOp;
7462
7463   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7464
7465   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7466   // unpckh_undef). Only use pshufd if speed is more important than size.
7467   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7468     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7469   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7470     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7471
7472   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7473       V2IsUndef && MayFoldVectorLoad(V1))
7474     return getMOVDDup(Op, dl, V1, DAG);
7475
7476   if (isMOVHLPS_v_undef_Mask(M, VT))
7477     return getMOVHighToLow(Op, dl, DAG);
7478
7479   // Use to match splats
7480   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7481       (VT == MVT::v2f64 || VT == MVT::v2i64))
7482     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7483
7484   if (isPSHUFDMask(M, VT)) {
7485     // The actual implementation will match the mask in the if above and then
7486     // during isel it can match several different instructions, not only pshufd
7487     // as its name says, sad but true, emulate the behavior for now...
7488     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7489       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7490
7491     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7492
7493     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7494       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7495
7496     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7497       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7498                                   DAG);
7499
7500     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7501                                 TargetMask, DAG);
7502   }
7503
7504   if (isPALIGNRMask(M, VT, Subtarget))
7505     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7506                                 getShufflePALIGNRImmediate(SVOp),
7507                                 DAG);
7508
7509   // Check if this can be converted into a logical shift.
7510   bool isLeft = false;
7511   unsigned ShAmt = 0;
7512   SDValue ShVal;
7513   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7514   if (isShift && ShVal.hasOneUse()) {
7515     // If the shifted value has multiple uses, it may be cheaper to use
7516     // v_set0 + movlhps or movhlps, etc.
7517     MVT EltVT = VT.getVectorElementType();
7518     ShAmt *= EltVT.getSizeInBits();
7519     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7520   }
7521
7522   if (isMOVLMask(M, VT)) {
7523     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7524       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7525     if (!isMOVLPMask(M, VT)) {
7526       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7527         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7528
7529       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7530         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7531     }
7532   }
7533
7534   // FIXME: fold these into legal mask.
7535   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7536     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7537
7538   if (isMOVHLPSMask(M, VT))
7539     return getMOVHighToLow(Op, dl, DAG);
7540
7541   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7542     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7543
7544   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7545     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7546
7547   if (isMOVLPMask(M, VT))
7548     return getMOVLP(Op, dl, DAG, HasSSE2);
7549
7550   if (ShouldXformToMOVHLPS(M, VT) ||
7551       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7552     return CommuteVectorShuffle(SVOp, DAG);
7553
7554   if (isShift) {
7555     // No better options. Use a vshldq / vsrldq.
7556     MVT EltVT = VT.getVectorElementType();
7557     ShAmt *= EltVT.getSizeInBits();
7558     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7559   }
7560
7561   bool Commuted = false;
7562   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7563   // 1,1,1,1 -> v8i16 though.
7564   V1IsSplat = isSplatVector(V1.getNode());
7565   V2IsSplat = isSplatVector(V2.getNode());
7566
7567   // Canonicalize the splat or undef, if present, to be on the RHS.
7568   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7569     CommuteVectorShuffleMask(M, NumElems);
7570     std::swap(V1, V2);
7571     std::swap(V1IsSplat, V2IsSplat);
7572     Commuted = true;
7573   }
7574
7575   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7576     // Shuffling low element of v1 into undef, just return v1.
7577     if (V2IsUndef)
7578       return V1;
7579     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7580     // the instruction selector will not match, so get a canonical MOVL with
7581     // swapped operands to undo the commute.
7582     return getMOVL(DAG, dl, VT, V2, V1);
7583   }
7584
7585   if (isUNPCKLMask(M, VT, HasInt256))
7586     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7587
7588   if (isUNPCKHMask(M, VT, HasInt256))
7589     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7590
7591   if (V2IsSplat) {
7592     // Normalize mask so all entries that point to V2 points to its first
7593     // element then try to match unpck{h|l} again. If match, return a
7594     // new vector_shuffle with the corrected mask.p
7595     SmallVector<int, 8> NewMask(M.begin(), M.end());
7596     NormalizeMask(NewMask, NumElems);
7597     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7598       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7599     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7600       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7601   }
7602
7603   if (Commuted) {
7604     // Commute is back and try unpck* again.
7605     // FIXME: this seems wrong.
7606     CommuteVectorShuffleMask(M, NumElems);
7607     std::swap(V1, V2);
7608     std::swap(V1IsSplat, V2IsSplat);
7609
7610     if (isUNPCKLMask(M, VT, HasInt256))
7611       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7612
7613     if (isUNPCKHMask(M, VT, HasInt256))
7614       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7615   }
7616
7617   // Normalize the node to match x86 shuffle ops if needed
7618   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7619     return CommuteVectorShuffle(SVOp, DAG);
7620
7621   // The checks below are all present in isShuffleMaskLegal, but they are
7622   // inlined here right now to enable us to directly emit target specific
7623   // nodes, and remove one by one until they don't return Op anymore.
7624
7625   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7626       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7627     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7628       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7629   }
7630
7631   if (isPSHUFHWMask(M, VT, HasInt256))
7632     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7633                                 getShufflePSHUFHWImmediate(SVOp),
7634                                 DAG);
7635
7636   if (isPSHUFLWMask(M, VT, HasInt256))
7637     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7638                                 getShufflePSHUFLWImmediate(SVOp),
7639                                 DAG);
7640
7641   if (isSHUFPMask(M, VT))
7642     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7643                                 getShuffleSHUFImmediate(SVOp), DAG);
7644
7645   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7646     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7647   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7648     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7649
7650   //===--------------------------------------------------------------------===//
7651   // Generate target specific nodes for 128 or 256-bit shuffles only
7652   // supported in the AVX instruction set.
7653   //
7654
7655   // Handle VMOVDDUPY permutations
7656   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7657     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7658
7659   // Handle VPERMILPS/D* permutations
7660   if (isVPERMILPMask(M, VT)) {
7661     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7662       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7663                                   getShuffleSHUFImmediate(SVOp), DAG);
7664     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7665                                 getShuffleSHUFImmediate(SVOp), DAG);
7666   }
7667
7668   // Handle VPERM2F128/VPERM2I128 permutations
7669   if (isVPERM2X128Mask(M, VT, HasFp256))
7670     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7671                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7672
7673   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7674   if (BlendOp.getNode())
7675     return BlendOp;
7676
7677   unsigned Imm8;
7678   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7679     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7680
7681   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7682       VT.is512BitVector()) {
7683     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7684     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7685     SmallVector<SDValue, 16> permclMask;
7686     for (unsigned i = 0; i != NumElems; ++i) {
7687       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7688     }
7689
7690     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7691                                 &permclMask[0], NumElems);
7692     if (V2IsUndef)
7693       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7694       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7695                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7696     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7697                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7698   }
7699
7700   //===--------------------------------------------------------------------===//
7701   // Since no target specific shuffle was selected for this generic one,
7702   // lower it into other known shuffles. FIXME: this isn't true yet, but
7703   // this is the plan.
7704   //
7705
7706   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7707   if (VT == MVT::v8i16) {
7708     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7709     if (NewOp.getNode())
7710       return NewOp;
7711   }
7712
7713   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7714     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7715     if (NewOp.getNode())
7716       return NewOp;
7717   }
7718
7719   if (VT == MVT::v16i8) {
7720     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7721     if (NewOp.getNode())
7722       return NewOp;
7723   }
7724
7725   if (VT == MVT::v32i8) {
7726     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7727     if (NewOp.getNode())
7728       return NewOp;
7729   }
7730
7731   // Handle all 128-bit wide vectors with 4 elements, and match them with
7732   // several different shuffle types.
7733   if (NumElems == 4 && VT.is128BitVector())
7734     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7735
7736   // Handle general 256-bit shuffles
7737   if (VT.is256BitVector())
7738     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7739
7740   return SDValue();
7741 }
7742
7743 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7744   MVT VT = Op.getSimpleValueType();
7745   SDLoc dl(Op);
7746
7747   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7748     return SDValue();
7749
7750   if (VT.getSizeInBits() == 8) {
7751     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7752                                   Op.getOperand(0), Op.getOperand(1));
7753     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7754                                   DAG.getValueType(VT));
7755     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7756   }
7757
7758   if (VT.getSizeInBits() == 16) {
7759     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7760     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7761     if (Idx == 0)
7762       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7763                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7764                                      DAG.getNode(ISD::BITCAST, dl,
7765                                                  MVT::v4i32,
7766                                                  Op.getOperand(0)),
7767                                      Op.getOperand(1)));
7768     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7769                                   Op.getOperand(0), Op.getOperand(1));
7770     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7771                                   DAG.getValueType(VT));
7772     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7773   }
7774
7775   if (VT == MVT::f32) {
7776     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7777     // the result back to FR32 register. It's only worth matching if the
7778     // result has a single use which is a store or a bitcast to i32.  And in
7779     // the case of a store, it's not worth it if the index is a constant 0,
7780     // because a MOVSSmr can be used instead, which is smaller and faster.
7781     if (!Op.hasOneUse())
7782       return SDValue();
7783     SDNode *User = *Op.getNode()->use_begin();
7784     if ((User->getOpcode() != ISD::STORE ||
7785          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7786           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7787         (User->getOpcode() != ISD::BITCAST ||
7788          User->getValueType(0) != MVT::i32))
7789       return SDValue();
7790     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7791                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7792                                               Op.getOperand(0)),
7793                                               Op.getOperand(1));
7794     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7795   }
7796
7797   if (VT == MVT::i32 || VT == MVT::i64) {
7798     // ExtractPS/pextrq works with constant index.
7799     if (isa<ConstantSDNode>(Op.getOperand(1)))
7800       return Op;
7801   }
7802   return SDValue();
7803 }
7804
7805 /// Extract one bit from mask vector, like v16i1 or v8i1.
7806 /// AVX-512 feature.
7807 SDValue
7808 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7809   SDValue Vec = Op.getOperand(0);
7810   SDLoc dl(Vec);
7811   MVT VecVT = Vec.getSimpleValueType();
7812   SDValue Idx = Op.getOperand(1);
7813   MVT EltVT = Op.getSimpleValueType();
7814
7815   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7816
7817   // variable index can't be handled in mask registers,
7818   // extend vector to VR512
7819   if (!isa<ConstantSDNode>(Idx)) {
7820     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7821     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7822     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7823                               ExtVT.getVectorElementType(), Ext, Idx);
7824     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7825   }
7826
7827   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7828   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7829   unsigned MaxSift = rc->getSize()*8 - 1;
7830   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7831                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7832   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7833                     DAG.getConstant(MaxSift, MVT::i8));
7834   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7835                        DAG.getIntPtrConstant(0));
7836 }
7837
7838 SDValue
7839 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7840                                            SelectionDAG &DAG) const {
7841   SDLoc dl(Op);
7842   SDValue Vec = Op.getOperand(0);
7843   MVT VecVT = Vec.getSimpleValueType();
7844   SDValue Idx = Op.getOperand(1);
7845
7846   if (Op.getSimpleValueType() == MVT::i1)
7847     return ExtractBitFromMaskVector(Op, DAG);
7848
7849   if (!isa<ConstantSDNode>(Idx)) {
7850     if (VecVT.is512BitVector() ||
7851         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7852          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7853
7854       MVT MaskEltVT =
7855         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7856       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7857                                     MaskEltVT.getSizeInBits());
7858
7859       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7860       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7861                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7862                                 Idx, DAG.getConstant(0, getPointerTy()));
7863       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7864       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7865                         Perm, DAG.getConstant(0, getPointerTy()));
7866     }
7867     return SDValue();
7868   }
7869
7870   // If this is a 256-bit vector result, first extract the 128-bit vector and
7871   // then extract the element from the 128-bit vector.
7872   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7873
7874     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7875     // Get the 128-bit vector.
7876     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7877     MVT EltVT = VecVT.getVectorElementType();
7878
7879     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7880
7881     //if (IdxVal >= NumElems/2)
7882     //  IdxVal -= NumElems/2;
7883     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7884     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7885                        DAG.getConstant(IdxVal, MVT::i32));
7886   }
7887
7888   assert(VecVT.is128BitVector() && "Unexpected vector length");
7889
7890   if (Subtarget->hasSSE41()) {
7891     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7892     if (Res.getNode())
7893       return Res;
7894   }
7895
7896   MVT VT = Op.getSimpleValueType();
7897   // TODO: handle v16i8.
7898   if (VT.getSizeInBits() == 16) {
7899     SDValue Vec = Op.getOperand(0);
7900     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7901     if (Idx == 0)
7902       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7903                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7904                                      DAG.getNode(ISD::BITCAST, dl,
7905                                                  MVT::v4i32, Vec),
7906                                      Op.getOperand(1)));
7907     // Transform it so it match pextrw which produces a 32-bit result.
7908     MVT EltVT = MVT::i32;
7909     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7910                                   Op.getOperand(0), Op.getOperand(1));
7911     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7912                                   DAG.getValueType(VT));
7913     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7914   }
7915
7916   if (VT.getSizeInBits() == 32) {
7917     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7918     if (Idx == 0)
7919       return Op;
7920
7921     // SHUFPS the element to the lowest double word, then movss.
7922     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7923     MVT VVT = Op.getOperand(0).getSimpleValueType();
7924     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7925                                        DAG.getUNDEF(VVT), Mask);
7926     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7927                        DAG.getIntPtrConstant(0));
7928   }
7929
7930   if (VT.getSizeInBits() == 64) {
7931     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7932     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7933     //        to match extract_elt for f64.
7934     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7935     if (Idx == 0)
7936       return Op;
7937
7938     // UNPCKHPD the element to the lowest double word, then movsd.
7939     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7940     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7941     int Mask[2] = { 1, -1 };
7942     MVT VVT = Op.getOperand(0).getSimpleValueType();
7943     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7944                                        DAG.getUNDEF(VVT), Mask);
7945     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7946                        DAG.getIntPtrConstant(0));
7947   }
7948
7949   return SDValue();
7950 }
7951
7952 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7953   MVT VT = Op.getSimpleValueType();
7954   MVT EltVT = VT.getVectorElementType();
7955   SDLoc dl(Op);
7956
7957   SDValue N0 = Op.getOperand(0);
7958   SDValue N1 = Op.getOperand(1);
7959   SDValue N2 = Op.getOperand(2);
7960
7961   if (!VT.is128BitVector())
7962     return SDValue();
7963
7964   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7965       isa<ConstantSDNode>(N2)) {
7966     unsigned Opc;
7967     if (VT == MVT::v8i16)
7968       Opc = X86ISD::PINSRW;
7969     else if (VT == MVT::v16i8)
7970       Opc = X86ISD::PINSRB;
7971     else
7972       Opc = X86ISD::PINSRB;
7973
7974     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7975     // argument.
7976     if (N1.getValueType() != MVT::i32)
7977       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7978     if (N2.getValueType() != MVT::i32)
7979       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7980     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7981   }
7982
7983   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7984     // Bits [7:6] of the constant are the source select.  This will always be
7985     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7986     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7987     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7988     // Bits [5:4] of the constant are the destination select.  This is the
7989     //  value of the incoming immediate.
7990     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7991     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7992     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7993     // Create this as a scalar to vector..
7994     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7995     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7996   }
7997
7998   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7999     // PINSR* works with constant index.
8000     return Op;
8001   }
8002   return SDValue();
8003 }
8004
8005 /// Insert one bit to mask vector, like v16i1 or v8i1.
8006 /// AVX-512 feature.
8007 SDValue 
8008 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8009   SDLoc dl(Op);
8010   SDValue Vec = Op.getOperand(0);
8011   SDValue Elt = Op.getOperand(1);
8012   SDValue Idx = Op.getOperand(2);
8013   MVT VecVT = Vec.getSimpleValueType();
8014
8015   if (!isa<ConstantSDNode>(Idx)) {
8016     // Non constant index. Extend source and destination,
8017     // insert element and then truncate the result.
8018     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8019     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8020     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8021       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8022       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8023     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8024   }
8025
8026   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8027   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8028   if (Vec.getOpcode() == ISD::UNDEF)
8029     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8030                        DAG.getConstant(IdxVal, MVT::i8));
8031   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8032   unsigned MaxSift = rc->getSize()*8 - 1;
8033   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8034                     DAG.getConstant(MaxSift, MVT::i8));
8035   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8036                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8037   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8038 }
8039 SDValue
8040 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8041   MVT VT = Op.getSimpleValueType();
8042   MVT EltVT = VT.getVectorElementType();
8043   
8044   if (EltVT == MVT::i1)
8045     return InsertBitToMaskVector(Op, DAG);
8046
8047   SDLoc dl(Op);
8048   SDValue N0 = Op.getOperand(0);
8049   SDValue N1 = Op.getOperand(1);
8050   SDValue N2 = Op.getOperand(2);
8051
8052   // If this is a 256-bit vector result, first extract the 128-bit vector,
8053   // insert the element into the extracted half and then place it back.
8054   if (VT.is256BitVector() || VT.is512BitVector()) {
8055     if (!isa<ConstantSDNode>(N2))
8056       return SDValue();
8057
8058     // Get the desired 128-bit vector half.
8059     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8060     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8061
8062     // Insert the element into the desired half.
8063     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8064     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8065
8066     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8067                     DAG.getConstant(IdxIn128, MVT::i32));
8068
8069     // Insert the changed part back to the 256-bit vector
8070     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8071   }
8072
8073   if (Subtarget->hasSSE41())
8074     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8075
8076   if (EltVT == MVT::i8)
8077     return SDValue();
8078
8079   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8080     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8081     // as its second argument.
8082     if (N1.getValueType() != MVT::i32)
8083       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8084     if (N2.getValueType() != MVT::i32)
8085       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8086     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8087   }
8088   return SDValue();
8089 }
8090
8091 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8092   SDLoc dl(Op);
8093   MVT OpVT = Op.getSimpleValueType();
8094
8095   // If this is a 256-bit vector result, first insert into a 128-bit
8096   // vector and then insert into the 256-bit vector.
8097   if (!OpVT.is128BitVector()) {
8098     // Insert into a 128-bit vector.
8099     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8100     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8101                                  OpVT.getVectorNumElements() / SizeFactor);
8102
8103     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8104
8105     // Insert the 128-bit vector.
8106     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8107   }
8108
8109   if (OpVT == MVT::v1i64 &&
8110       Op.getOperand(0).getValueType() == MVT::i64)
8111     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8112
8113   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8114   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8115   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8116                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8117 }
8118
8119 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8120 // a simple subregister reference or explicit instructions to grab
8121 // upper bits of a vector.
8122 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8123                                       SelectionDAG &DAG) {
8124   SDLoc dl(Op);
8125   SDValue In =  Op.getOperand(0);
8126   SDValue Idx = Op.getOperand(1);
8127   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8128   MVT ResVT   = Op.getSimpleValueType();
8129   MVT InVT    = In.getSimpleValueType();
8130
8131   if (Subtarget->hasFp256()) {
8132     if (ResVT.is128BitVector() &&
8133         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8134         isa<ConstantSDNode>(Idx)) {
8135       return Extract128BitVector(In, IdxVal, DAG, dl);
8136     }
8137     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8138         isa<ConstantSDNode>(Idx)) {
8139       return Extract256BitVector(In, IdxVal, DAG, dl);
8140     }
8141   }
8142   return SDValue();
8143 }
8144
8145 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8146 // simple superregister reference or explicit instructions to insert
8147 // the upper bits of a vector.
8148 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8149                                      SelectionDAG &DAG) {
8150   if (Subtarget->hasFp256()) {
8151     SDLoc dl(Op.getNode());
8152     SDValue Vec = Op.getNode()->getOperand(0);
8153     SDValue SubVec = Op.getNode()->getOperand(1);
8154     SDValue Idx = Op.getNode()->getOperand(2);
8155
8156     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8157          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8158         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8159         isa<ConstantSDNode>(Idx)) {
8160       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8161       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8162     }
8163
8164     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8165         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8166         isa<ConstantSDNode>(Idx)) {
8167       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8168       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8169     }
8170   }
8171   return SDValue();
8172 }
8173
8174 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8175 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8176 // one of the above mentioned nodes. It has to be wrapped because otherwise
8177 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8178 // be used to form addressing mode. These wrapped nodes will be selected
8179 // into MOV32ri.
8180 SDValue
8181 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8182   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8183
8184   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8185   // global base reg.
8186   unsigned char OpFlag = 0;
8187   unsigned WrapperKind = X86ISD::Wrapper;
8188   CodeModel::Model M = getTargetMachine().getCodeModel();
8189
8190   if (Subtarget->isPICStyleRIPRel() &&
8191       (M == CodeModel::Small || M == CodeModel::Kernel))
8192     WrapperKind = X86ISD::WrapperRIP;
8193   else if (Subtarget->isPICStyleGOT())
8194     OpFlag = X86II::MO_GOTOFF;
8195   else if (Subtarget->isPICStyleStubPIC())
8196     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8197
8198   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8199                                              CP->getAlignment(),
8200                                              CP->getOffset(), OpFlag);
8201   SDLoc DL(CP);
8202   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8203   // With PIC, the address is actually $g + Offset.
8204   if (OpFlag) {
8205     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8206                          DAG.getNode(X86ISD::GlobalBaseReg,
8207                                      SDLoc(), getPointerTy()),
8208                          Result);
8209   }
8210
8211   return Result;
8212 }
8213
8214 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8215   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8216
8217   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8218   // global base reg.
8219   unsigned char OpFlag = 0;
8220   unsigned WrapperKind = X86ISD::Wrapper;
8221   CodeModel::Model M = getTargetMachine().getCodeModel();
8222
8223   if (Subtarget->isPICStyleRIPRel() &&
8224       (M == CodeModel::Small || M == CodeModel::Kernel))
8225     WrapperKind = X86ISD::WrapperRIP;
8226   else if (Subtarget->isPICStyleGOT())
8227     OpFlag = X86II::MO_GOTOFF;
8228   else if (Subtarget->isPICStyleStubPIC())
8229     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8230
8231   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8232                                           OpFlag);
8233   SDLoc DL(JT);
8234   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8235
8236   // With PIC, the address is actually $g + Offset.
8237   if (OpFlag)
8238     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8239                          DAG.getNode(X86ISD::GlobalBaseReg,
8240                                      SDLoc(), getPointerTy()),
8241                          Result);
8242
8243   return Result;
8244 }
8245
8246 SDValue
8247 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8248   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8249
8250   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8251   // global base reg.
8252   unsigned char OpFlag = 0;
8253   unsigned WrapperKind = X86ISD::Wrapper;
8254   CodeModel::Model M = getTargetMachine().getCodeModel();
8255
8256   if (Subtarget->isPICStyleRIPRel() &&
8257       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8258     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8259       OpFlag = X86II::MO_GOTPCREL;
8260     WrapperKind = X86ISD::WrapperRIP;
8261   } else if (Subtarget->isPICStyleGOT()) {
8262     OpFlag = X86II::MO_GOT;
8263   } else if (Subtarget->isPICStyleStubPIC()) {
8264     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8265   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8266     OpFlag = X86II::MO_DARWIN_NONLAZY;
8267   }
8268
8269   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8270
8271   SDLoc DL(Op);
8272   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8273
8274   // With PIC, the address is actually $g + Offset.
8275   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8276       !Subtarget->is64Bit()) {
8277     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8278                          DAG.getNode(X86ISD::GlobalBaseReg,
8279                                      SDLoc(), getPointerTy()),
8280                          Result);
8281   }
8282
8283   // For symbols that require a load from a stub to get the address, emit the
8284   // load.
8285   if (isGlobalStubReference(OpFlag))
8286     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8287                          MachinePointerInfo::getGOT(), false, false, false, 0);
8288
8289   return Result;
8290 }
8291
8292 SDValue
8293 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8294   // Create the TargetBlockAddressAddress node.
8295   unsigned char OpFlags =
8296     Subtarget->ClassifyBlockAddressReference();
8297   CodeModel::Model M = getTargetMachine().getCodeModel();
8298   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8299   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8300   SDLoc dl(Op);
8301   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8302                                              OpFlags);
8303
8304   if (Subtarget->isPICStyleRIPRel() &&
8305       (M == CodeModel::Small || M == CodeModel::Kernel))
8306     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8307   else
8308     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8309
8310   // With PIC, the address is actually $g + Offset.
8311   if (isGlobalRelativeToPICBase(OpFlags)) {
8312     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8313                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8314                          Result);
8315   }
8316
8317   return Result;
8318 }
8319
8320 SDValue
8321 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8322                                       int64_t Offset, SelectionDAG &DAG) const {
8323   // Create the TargetGlobalAddress node, folding in the constant
8324   // offset if it is legal.
8325   unsigned char OpFlags =
8326     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8327   CodeModel::Model M = getTargetMachine().getCodeModel();
8328   SDValue Result;
8329   if (OpFlags == X86II::MO_NO_FLAG &&
8330       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8331     // A direct static reference to a global.
8332     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8333     Offset = 0;
8334   } else {
8335     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8336   }
8337
8338   if (Subtarget->isPICStyleRIPRel() &&
8339       (M == CodeModel::Small || M == CodeModel::Kernel))
8340     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8341   else
8342     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8343
8344   // With PIC, the address is actually $g + Offset.
8345   if (isGlobalRelativeToPICBase(OpFlags)) {
8346     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8347                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8348                          Result);
8349   }
8350
8351   // For globals that require a load from a stub to get the address, emit the
8352   // load.
8353   if (isGlobalStubReference(OpFlags))
8354     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8355                          MachinePointerInfo::getGOT(), false, false, false, 0);
8356
8357   // If there was a non-zero offset that we didn't fold, create an explicit
8358   // addition for it.
8359   if (Offset != 0)
8360     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8361                          DAG.getConstant(Offset, getPointerTy()));
8362
8363   return Result;
8364 }
8365
8366 SDValue
8367 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8368   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8369   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8370   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8371 }
8372
8373 static SDValue
8374 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8375            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8376            unsigned char OperandFlags, bool LocalDynamic = false) {
8377   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8378   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8379   SDLoc dl(GA);
8380   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8381                                            GA->getValueType(0),
8382                                            GA->getOffset(),
8383                                            OperandFlags);
8384
8385   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8386                                            : X86ISD::TLSADDR;
8387
8388   if (InFlag) {
8389     SDValue Ops[] = { Chain,  TGA, *InFlag };
8390     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8391   } else {
8392     SDValue Ops[]  = { Chain, TGA };
8393     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8394   }
8395
8396   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8397   MFI->setAdjustsStack(true);
8398
8399   SDValue Flag = Chain.getValue(1);
8400   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8401 }
8402
8403 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8404 static SDValue
8405 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8406                                 const EVT PtrVT) {
8407   SDValue InFlag;
8408   SDLoc dl(GA);  // ? function entry point might be better
8409   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8410                                    DAG.getNode(X86ISD::GlobalBaseReg,
8411                                                SDLoc(), PtrVT), InFlag);
8412   InFlag = Chain.getValue(1);
8413
8414   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8415 }
8416
8417 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8418 static SDValue
8419 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8420                                 const EVT PtrVT) {
8421   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8422                     X86::RAX, X86II::MO_TLSGD);
8423 }
8424
8425 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8426                                            SelectionDAG &DAG,
8427                                            const EVT PtrVT,
8428                                            bool is64Bit) {
8429   SDLoc dl(GA);
8430
8431   // Get the start address of the TLS block for this module.
8432   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8433       .getInfo<X86MachineFunctionInfo>();
8434   MFI->incNumLocalDynamicTLSAccesses();
8435
8436   SDValue Base;
8437   if (is64Bit) {
8438     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8439                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8440   } else {
8441     SDValue InFlag;
8442     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8443         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8444     InFlag = Chain.getValue(1);
8445     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8446                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8447   }
8448
8449   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8450   // of Base.
8451
8452   // Build x@dtpoff.
8453   unsigned char OperandFlags = X86II::MO_DTPOFF;
8454   unsigned WrapperKind = X86ISD::Wrapper;
8455   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8456                                            GA->getValueType(0),
8457                                            GA->getOffset(), OperandFlags);
8458   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8459
8460   // Add x@dtpoff with the base.
8461   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8462 }
8463
8464 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8465 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8466                                    const EVT PtrVT, TLSModel::Model model,
8467                                    bool is64Bit, bool isPIC) {
8468   SDLoc dl(GA);
8469
8470   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8471   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8472                                                          is64Bit ? 257 : 256));
8473
8474   SDValue ThreadPointer =
8475       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8476                   MachinePointerInfo(Ptr), false, false, false, 0);
8477
8478   unsigned char OperandFlags = 0;
8479   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8480   // initialexec.
8481   unsigned WrapperKind = X86ISD::Wrapper;
8482   if (model == TLSModel::LocalExec) {
8483     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8484   } else if (model == TLSModel::InitialExec) {
8485     if (is64Bit) {
8486       OperandFlags = X86II::MO_GOTTPOFF;
8487       WrapperKind = X86ISD::WrapperRIP;
8488     } else {
8489       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8490     }
8491   } else {
8492     llvm_unreachable("Unexpected model");
8493   }
8494
8495   // emit "addl x@ntpoff,%eax" (local exec)
8496   // or "addl x@indntpoff,%eax" (initial exec)
8497   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8498   SDValue TGA =
8499       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8500                                  GA->getOffset(), OperandFlags);
8501   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8502
8503   if (model == TLSModel::InitialExec) {
8504     if (isPIC && !is64Bit) {
8505       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8506                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8507                            Offset);
8508     }
8509
8510     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8511                          MachinePointerInfo::getGOT(), false, false, false, 0);
8512   }
8513
8514   // The address of the thread local variable is the add of the thread
8515   // pointer with the offset of the variable.
8516   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8517 }
8518
8519 SDValue
8520 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8521
8522   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8523   const GlobalValue *GV = GA->getGlobal();
8524
8525   if (Subtarget->isTargetELF()) {
8526     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8527
8528     switch (model) {
8529       case TLSModel::GeneralDynamic:
8530         if (Subtarget->is64Bit())
8531           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8532         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8533       case TLSModel::LocalDynamic:
8534         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8535                                            Subtarget->is64Bit());
8536       case TLSModel::InitialExec:
8537       case TLSModel::LocalExec:
8538         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8539                                    Subtarget->is64Bit(),
8540                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8541     }
8542     llvm_unreachable("Unknown TLS model.");
8543   }
8544
8545   if (Subtarget->isTargetDarwin()) {
8546     // Darwin only has one model of TLS.  Lower to that.
8547     unsigned char OpFlag = 0;
8548     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8549                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8550
8551     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8552     // global base reg.
8553     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8554                   !Subtarget->is64Bit();
8555     if (PIC32)
8556       OpFlag = X86II::MO_TLVP_PIC_BASE;
8557     else
8558       OpFlag = X86II::MO_TLVP;
8559     SDLoc DL(Op);
8560     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8561                                                 GA->getValueType(0),
8562                                                 GA->getOffset(), OpFlag);
8563     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8564
8565     // With PIC32, the address is actually $g + Offset.
8566     if (PIC32)
8567       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8568                            DAG.getNode(X86ISD::GlobalBaseReg,
8569                                        SDLoc(), getPointerTy()),
8570                            Offset);
8571
8572     // Lowering the machine isd will make sure everything is in the right
8573     // location.
8574     SDValue Chain = DAG.getEntryNode();
8575     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8576     SDValue Args[] = { Chain, Offset };
8577     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8578
8579     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8580     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8581     MFI->setAdjustsStack(true);
8582
8583     // And our return value (tls address) is in the standard call return value
8584     // location.
8585     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8586     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8587                               Chain.getValue(1));
8588   }
8589
8590   if (Subtarget->isTargetKnownWindowsMSVC() ||
8591       Subtarget->isTargetWindowsGNU()) {
8592     // Just use the implicit TLS architecture
8593     // Need to generate someting similar to:
8594     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8595     //                                  ; from TEB
8596     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8597     //   mov     rcx, qword [rdx+rcx*8]
8598     //   mov     eax, .tls$:tlsvar
8599     //   [rax+rcx] contains the address
8600     // Windows 64bit: gs:0x58
8601     // Windows 32bit: fs:__tls_array
8602
8603     // If GV is an alias then use the aliasee for determining
8604     // thread-localness.
8605     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8606       GV = GA->getAliasedGlobal();
8607     SDLoc dl(GA);
8608     SDValue Chain = DAG.getEntryNode();
8609
8610     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8611     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8612     // use its literal value of 0x2C.
8613     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8614                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8615                                                              256)
8616                                         : Type::getInt32PtrTy(*DAG.getContext(),
8617                                                               257));
8618
8619     SDValue TlsArray =
8620         Subtarget->is64Bit()
8621             ? DAG.getIntPtrConstant(0x58)
8622             : (Subtarget->isTargetWindowsGNU()
8623                    ? DAG.getIntPtrConstant(0x2C)
8624                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8625
8626     SDValue ThreadPointer =
8627         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8628                     MachinePointerInfo(Ptr), false, false, false, 0);
8629
8630     // Load the _tls_index variable
8631     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8632     if (Subtarget->is64Bit())
8633       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8634                            IDX, MachinePointerInfo(), MVT::i32,
8635                            false, false, 0);
8636     else
8637       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8638                         false, false, false, 0);
8639
8640     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8641                                     getPointerTy());
8642     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8643
8644     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8645     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8646                       false, false, false, 0);
8647
8648     // Get the offset of start of .tls section
8649     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8650                                              GA->getValueType(0),
8651                                              GA->getOffset(), X86II::MO_SECREL);
8652     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8653
8654     // The address of the thread local variable is the add of the thread
8655     // pointer with the offset of the variable.
8656     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8657   }
8658
8659   llvm_unreachable("TLS not implemented for this target.");
8660 }
8661
8662 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8663 /// and take a 2 x i32 value to shift plus a shift amount.
8664 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8665   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8666   MVT VT = Op.getSimpleValueType();
8667   unsigned VTBits = VT.getSizeInBits();
8668   SDLoc dl(Op);
8669   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8670   SDValue ShOpLo = Op.getOperand(0);
8671   SDValue ShOpHi = Op.getOperand(1);
8672   SDValue ShAmt  = Op.getOperand(2);
8673   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8674   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8675   // during isel.
8676   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8677                                   DAG.getConstant(VTBits - 1, MVT::i8));
8678   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8679                                      DAG.getConstant(VTBits - 1, MVT::i8))
8680                        : DAG.getConstant(0, VT);
8681
8682   SDValue Tmp2, Tmp3;
8683   if (Op.getOpcode() == ISD::SHL_PARTS) {
8684     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8685     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8686   } else {
8687     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8688     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8689   }
8690
8691   // If the shift amount is larger or equal than the width of a part we can't
8692   // rely on the results of shld/shrd. Insert a test and select the appropriate
8693   // values for large shift amounts.
8694   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8695                                 DAG.getConstant(VTBits, MVT::i8));
8696   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8697                              AndNode, DAG.getConstant(0, MVT::i8));
8698
8699   SDValue Hi, Lo;
8700   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8701   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8702   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8703
8704   if (Op.getOpcode() == ISD::SHL_PARTS) {
8705     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8706     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8707   } else {
8708     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8709     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8710   }
8711
8712   SDValue Ops[2] = { Lo, Hi };
8713   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8714 }
8715
8716 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8717                                            SelectionDAG &DAG) const {
8718   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8719
8720   if (SrcVT.isVector())
8721     return SDValue();
8722
8723   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8724          "Unknown SINT_TO_FP to lower!");
8725
8726   // These are really Legal; return the operand so the caller accepts it as
8727   // Legal.
8728   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8729     return Op;
8730   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8731       Subtarget->is64Bit()) {
8732     return Op;
8733   }
8734
8735   SDLoc dl(Op);
8736   unsigned Size = SrcVT.getSizeInBits()/8;
8737   MachineFunction &MF = DAG.getMachineFunction();
8738   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8739   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8740   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8741                                StackSlot,
8742                                MachinePointerInfo::getFixedStack(SSFI),
8743                                false, false, 0);
8744   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8745 }
8746
8747 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8748                                      SDValue StackSlot,
8749                                      SelectionDAG &DAG) const {
8750   // Build the FILD
8751   SDLoc DL(Op);
8752   SDVTList Tys;
8753   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8754   if (useSSE)
8755     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8756   else
8757     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8758
8759   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8760
8761   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8762   MachineMemOperand *MMO;
8763   if (FI) {
8764     int SSFI = FI->getIndex();
8765     MMO =
8766       DAG.getMachineFunction()
8767       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8768                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8769   } else {
8770     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8771     StackSlot = StackSlot.getOperand(1);
8772   }
8773   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8774   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8775                                            X86ISD::FILD, DL,
8776                                            Tys, Ops, array_lengthof(Ops),
8777                                            SrcVT, MMO);
8778
8779   if (useSSE) {
8780     Chain = Result.getValue(1);
8781     SDValue InFlag = Result.getValue(2);
8782
8783     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8784     // shouldn't be necessary except that RFP cannot be live across
8785     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8786     MachineFunction &MF = DAG.getMachineFunction();
8787     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8788     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8789     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8790     Tys = DAG.getVTList(MVT::Other);
8791     SDValue Ops[] = {
8792       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8793     };
8794     MachineMemOperand *MMO =
8795       DAG.getMachineFunction()
8796       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8797                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8798
8799     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8800                                     Ops, array_lengthof(Ops),
8801                                     Op.getValueType(), MMO);
8802     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8803                          MachinePointerInfo::getFixedStack(SSFI),
8804                          false, false, false, 0);
8805   }
8806
8807   return Result;
8808 }
8809
8810 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8811 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8812                                                SelectionDAG &DAG) const {
8813   // This algorithm is not obvious. Here it is what we're trying to output:
8814   /*
8815      movq       %rax,  %xmm0
8816      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8817      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8818      #ifdef __SSE3__
8819        haddpd   %xmm0, %xmm0
8820      #else
8821        pshufd   $0x4e, %xmm0, %xmm1
8822        addpd    %xmm1, %xmm0
8823      #endif
8824   */
8825
8826   SDLoc dl(Op);
8827   LLVMContext *Context = DAG.getContext();
8828
8829   // Build some magic constants.
8830   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8831   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8832   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8833
8834   SmallVector<Constant*,2> CV1;
8835   CV1.push_back(
8836     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8837                                       APInt(64, 0x4330000000000000ULL))));
8838   CV1.push_back(
8839     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8840                                       APInt(64, 0x4530000000000000ULL))));
8841   Constant *C1 = ConstantVector::get(CV1);
8842   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8843
8844   // Load the 64-bit value into an XMM register.
8845   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8846                             Op.getOperand(0));
8847   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8848                               MachinePointerInfo::getConstantPool(),
8849                               false, false, false, 16);
8850   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8851                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8852                               CLod0);
8853
8854   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8855                               MachinePointerInfo::getConstantPool(),
8856                               false, false, false, 16);
8857   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8858   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8859   SDValue Result;
8860
8861   if (Subtarget->hasSSE3()) {
8862     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8863     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8864   } else {
8865     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8866     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8867                                            S2F, 0x4E, DAG);
8868     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8869                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8870                          Sub);
8871   }
8872
8873   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8874                      DAG.getIntPtrConstant(0));
8875 }
8876
8877 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8878 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8879                                                SelectionDAG &DAG) const {
8880   SDLoc dl(Op);
8881   // FP constant to bias correct the final result.
8882   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8883                                    MVT::f64);
8884
8885   // Load the 32-bit value into an XMM register.
8886   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8887                              Op.getOperand(0));
8888
8889   // Zero out the upper parts of the register.
8890   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8891
8892   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8893                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8894                      DAG.getIntPtrConstant(0));
8895
8896   // Or the load with the bias.
8897   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8898                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8899                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8900                                                    MVT::v2f64, Load)),
8901                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8902                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8903                                                    MVT::v2f64, Bias)));
8904   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8905                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8906                    DAG.getIntPtrConstant(0));
8907
8908   // Subtract the bias.
8909   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8910
8911   // Handle final rounding.
8912   EVT DestVT = Op.getValueType();
8913
8914   if (DestVT.bitsLT(MVT::f64))
8915     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8916                        DAG.getIntPtrConstant(0));
8917   if (DestVT.bitsGT(MVT::f64))
8918     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8919
8920   // Handle final rounding.
8921   return Sub;
8922 }
8923
8924 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8925                                                SelectionDAG &DAG) const {
8926   SDValue N0 = Op.getOperand(0);
8927   MVT SVT = N0.getSimpleValueType();
8928   SDLoc dl(Op);
8929
8930   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8931           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8932          "Custom UINT_TO_FP is not supported!");
8933
8934   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8935   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8936                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8937 }
8938
8939 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8940                                            SelectionDAG &DAG) const {
8941   SDValue N0 = Op.getOperand(0);
8942   SDLoc dl(Op);
8943
8944   if (Op.getValueType().isVector())
8945     return lowerUINT_TO_FP_vec(Op, DAG);
8946
8947   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8948   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8949   // the optimization here.
8950   if (DAG.SignBitIsZero(N0))
8951     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8952
8953   MVT SrcVT = N0.getSimpleValueType();
8954   MVT DstVT = Op.getSimpleValueType();
8955   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8956     return LowerUINT_TO_FP_i64(Op, DAG);
8957   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8958     return LowerUINT_TO_FP_i32(Op, DAG);
8959   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8960     return SDValue();
8961
8962   // Make a 64-bit buffer, and use it to build an FILD.
8963   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8964   if (SrcVT == MVT::i32) {
8965     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8966     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8967                                      getPointerTy(), StackSlot, WordOff);
8968     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8969                                   StackSlot, MachinePointerInfo(),
8970                                   false, false, 0);
8971     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8972                                   OffsetSlot, MachinePointerInfo(),
8973                                   false, false, 0);
8974     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8975     return Fild;
8976   }
8977
8978   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8979   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8980                                StackSlot, MachinePointerInfo(),
8981                                false, false, 0);
8982   // For i64 source, we need to add the appropriate power of 2 if the input
8983   // was negative.  This is the same as the optimization in
8984   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8985   // we must be careful to do the computation in x87 extended precision, not
8986   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8987   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8988   MachineMemOperand *MMO =
8989     DAG.getMachineFunction()
8990     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8991                           MachineMemOperand::MOLoad, 8, 8);
8992
8993   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8994   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8995   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8996                                          array_lengthof(Ops), MVT::i64, MMO);
8997
8998   APInt FF(32, 0x5F800000ULL);
8999
9000   // Check whether the sign bit is set.
9001   SDValue SignSet = DAG.getSetCC(dl,
9002                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9003                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9004                                  ISD::SETLT);
9005
9006   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9007   SDValue FudgePtr = DAG.getConstantPool(
9008                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9009                                          getPointerTy());
9010
9011   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9012   SDValue Zero = DAG.getIntPtrConstant(0);
9013   SDValue Four = DAG.getIntPtrConstant(4);
9014   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9015                                Zero, Four);
9016   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9017
9018   // Load the value out, extending it from f32 to f80.
9019   // FIXME: Avoid the extend by constructing the right constant pool?
9020   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9021                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9022                                  MVT::f32, false, false, 4);
9023   // Extend everything to 80 bits to force it to be done on x87.
9024   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9025   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9026 }
9027
9028 std::pair<SDValue,SDValue>
9029 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9030                                     bool IsSigned, bool IsReplace) const {
9031   SDLoc DL(Op);
9032
9033   EVT DstTy = Op.getValueType();
9034
9035   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9036     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9037     DstTy = MVT::i64;
9038   }
9039
9040   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9041          DstTy.getSimpleVT() >= MVT::i16 &&
9042          "Unknown FP_TO_INT to lower!");
9043
9044   // These are really Legal.
9045   if (DstTy == MVT::i32 &&
9046       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9047     return std::make_pair(SDValue(), SDValue());
9048   if (Subtarget->is64Bit() &&
9049       DstTy == MVT::i64 &&
9050       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9051     return std::make_pair(SDValue(), SDValue());
9052
9053   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9054   // stack slot, or into the FTOL runtime function.
9055   MachineFunction &MF = DAG.getMachineFunction();
9056   unsigned MemSize = DstTy.getSizeInBits()/8;
9057   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9058   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9059
9060   unsigned Opc;
9061   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9062     Opc = X86ISD::WIN_FTOL;
9063   else
9064     switch (DstTy.getSimpleVT().SimpleTy) {
9065     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9066     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9067     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9068     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9069     }
9070
9071   SDValue Chain = DAG.getEntryNode();
9072   SDValue Value = Op.getOperand(0);
9073   EVT TheVT = Op.getOperand(0).getValueType();
9074   // FIXME This causes a redundant load/store if the SSE-class value is already
9075   // in memory, such as if it is on the callstack.
9076   if (isScalarFPTypeInSSEReg(TheVT)) {
9077     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9078     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9079                          MachinePointerInfo::getFixedStack(SSFI),
9080                          false, false, 0);
9081     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9082     SDValue Ops[] = {
9083       Chain, StackSlot, DAG.getValueType(TheVT)
9084     };
9085
9086     MachineMemOperand *MMO =
9087       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9088                               MachineMemOperand::MOLoad, MemSize, MemSize);
9089     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9090                                     array_lengthof(Ops), DstTy, MMO);
9091     Chain = Value.getValue(1);
9092     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9093     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9094   }
9095
9096   MachineMemOperand *MMO =
9097     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9098                             MachineMemOperand::MOStore, MemSize, MemSize);
9099
9100   if (Opc != X86ISD::WIN_FTOL) {
9101     // Build the FP_TO_INT*_IN_MEM
9102     SDValue Ops[] = { Chain, Value, StackSlot };
9103     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9104                                            Ops, array_lengthof(Ops), DstTy,
9105                                            MMO);
9106     return std::make_pair(FIST, StackSlot);
9107   } else {
9108     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9109       DAG.getVTList(MVT::Other, MVT::Glue),
9110       Chain, Value);
9111     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9112       MVT::i32, ftol.getValue(1));
9113     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9114       MVT::i32, eax.getValue(2));
9115     SDValue Ops[] = { eax, edx };
9116     SDValue pair = IsReplace
9117       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9118       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9119     return std::make_pair(pair, SDValue());
9120   }
9121 }
9122
9123 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9124                               const X86Subtarget *Subtarget) {
9125   MVT VT = Op->getSimpleValueType(0);
9126   SDValue In = Op->getOperand(0);
9127   MVT InVT = In.getSimpleValueType();
9128   SDLoc dl(Op);
9129
9130   // Optimize vectors in AVX mode:
9131   //
9132   //   v8i16 -> v8i32
9133   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9134   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9135   //   Concat upper and lower parts.
9136   //
9137   //   v4i32 -> v4i64
9138   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9139   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9140   //   Concat upper and lower parts.
9141   //
9142
9143   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9144       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9145       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9146     return SDValue();
9147
9148   if (Subtarget->hasInt256())
9149     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9150
9151   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9152   SDValue Undef = DAG.getUNDEF(InVT);
9153   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9154   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9155   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9156
9157   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9158                              VT.getVectorNumElements()/2);
9159
9160   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9161   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9162
9163   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9164 }
9165
9166 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9167                                         SelectionDAG &DAG) {
9168   MVT VT = Op->getSimpleValueType(0);
9169   SDValue In = Op->getOperand(0);
9170   MVT InVT = In.getSimpleValueType();
9171   SDLoc DL(Op);
9172   unsigned int NumElts = VT.getVectorNumElements();
9173   if (NumElts != 8 && NumElts != 16)
9174     return SDValue();
9175
9176   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9177     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9178
9179   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9181   // Now we have only mask extension
9182   assert(InVT.getVectorElementType() == MVT::i1);
9183   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9184   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9185   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9186   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9187   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9188                            MachinePointerInfo::getConstantPool(),
9189                            false, false, false, Alignment);
9190
9191   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9192   if (VT.is512BitVector())
9193     return Brcst;
9194   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9195 }
9196
9197 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9198                                SelectionDAG &DAG) {
9199   if (Subtarget->hasFp256()) {
9200     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9201     if (Res.getNode())
9202       return Res;
9203   }
9204
9205   return SDValue();
9206 }
9207
9208 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9209                                 SelectionDAG &DAG) {
9210   SDLoc DL(Op);
9211   MVT VT = Op.getSimpleValueType();
9212   SDValue In = Op.getOperand(0);
9213   MVT SVT = In.getSimpleValueType();
9214
9215   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9216     return LowerZERO_EXTEND_AVX512(Op, DAG);
9217
9218   if (Subtarget->hasFp256()) {
9219     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9220     if (Res.getNode())
9221       return Res;
9222   }
9223
9224   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9225          VT.getVectorNumElements() != SVT.getVectorNumElements());
9226   return SDValue();
9227 }
9228
9229 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9230   SDLoc DL(Op);
9231   MVT VT = Op.getSimpleValueType();
9232   SDValue In = Op.getOperand(0);
9233   MVT InVT = In.getSimpleValueType();
9234
9235   if (VT == MVT::i1) {
9236     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9237            "Invalid scalar TRUNCATE operation");
9238     if (InVT == MVT::i32)
9239       return SDValue();
9240     if (InVT.getSizeInBits() == 64)
9241       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9242     else if (InVT.getSizeInBits() < 32)
9243       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9244     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9245   }
9246   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9247          "Invalid TRUNCATE operation");
9248
9249   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9250     if (VT.getVectorElementType().getSizeInBits() >=8)
9251       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9252
9253     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9254     unsigned NumElts = InVT.getVectorNumElements();
9255     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9256     if (InVT.getSizeInBits() < 512) {
9257       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9258       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9259       InVT = ExtVT;
9260     }
9261     
9262     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9263     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9264     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9265     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9266     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9267                            MachinePointerInfo::getConstantPool(),
9268                            false, false, false, Alignment);
9269     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9270     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9271     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9272   }
9273
9274   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9275     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9276     if (Subtarget->hasInt256()) {
9277       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9278       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9279       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9280                                 ShufMask);
9281       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9282                          DAG.getIntPtrConstant(0));
9283     }
9284
9285     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9286                                DAG.getIntPtrConstant(0));
9287     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9288                                DAG.getIntPtrConstant(2));
9289     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9290     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9291     static const int ShufMask[] = {0, 2, 4, 6};
9292     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9293   }
9294
9295   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9296     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9297     if (Subtarget->hasInt256()) {
9298       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9299
9300       SmallVector<SDValue,32> pshufbMask;
9301       for (unsigned i = 0; i < 2; ++i) {
9302         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9303         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9304         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9305         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9306         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9307         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9308         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9309         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9310         for (unsigned j = 0; j < 8; ++j)
9311           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9312       }
9313       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9314                                &pshufbMask[0], 32);
9315       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9316       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9317
9318       static const int ShufMask[] = {0,  2,  -1,  -1};
9319       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9320                                 &ShufMask[0]);
9321       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9322                        DAG.getIntPtrConstant(0));
9323       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9324     }
9325
9326     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9327                                DAG.getIntPtrConstant(0));
9328
9329     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9330                                DAG.getIntPtrConstant(4));
9331
9332     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9333     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9334
9335     // The PSHUFB mask:
9336     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9337                                    -1, -1, -1, -1, -1, -1, -1, -1};
9338
9339     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9340     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9341     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9342
9343     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9344     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9345
9346     // The MOVLHPS Mask:
9347     static const int ShufMask2[] = {0, 1, 4, 5};
9348     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9349     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9350   }
9351
9352   // Handle truncation of V256 to V128 using shuffles.
9353   if (!VT.is128BitVector() || !InVT.is256BitVector())
9354     return SDValue();
9355
9356   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9357
9358   unsigned NumElems = VT.getVectorNumElements();
9359   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9360
9361   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9362   // Prepare truncation shuffle mask
9363   for (unsigned i = 0; i != NumElems; ++i)
9364     MaskVec[i] = i * 2;
9365   SDValue V = DAG.getVectorShuffle(NVT, DL,
9366                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9367                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9368   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9369                      DAG.getIntPtrConstant(0));
9370 }
9371
9372 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9373                                            SelectionDAG &DAG) const {
9374   assert(!Op.getSimpleValueType().isVector());
9375
9376   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9377     /*IsSigned=*/ true, /*IsReplace=*/ false);
9378   SDValue FIST = Vals.first, StackSlot = Vals.second;
9379   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9380   if (FIST.getNode() == 0) return Op;
9381
9382   if (StackSlot.getNode())
9383     // Load the result.
9384     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9385                        FIST, StackSlot, MachinePointerInfo(),
9386                        false, false, false, 0);
9387
9388   // The node is the result.
9389   return FIST;
9390 }
9391
9392 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9393                                            SelectionDAG &DAG) const {
9394   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9395     /*IsSigned=*/ false, /*IsReplace=*/ false);
9396   SDValue FIST = Vals.first, StackSlot = Vals.second;
9397   assert(FIST.getNode() && "Unexpected failure");
9398
9399   if (StackSlot.getNode())
9400     // Load the result.
9401     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9402                        FIST, StackSlot, MachinePointerInfo(),
9403                        false, false, false, 0);
9404
9405   // The node is the result.
9406   return FIST;
9407 }
9408
9409 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9410   SDLoc DL(Op);
9411   MVT VT = Op.getSimpleValueType();
9412   SDValue In = Op.getOperand(0);
9413   MVT SVT = In.getSimpleValueType();
9414
9415   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9416
9417   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9418                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9419                                  In, DAG.getUNDEF(SVT)));
9420 }
9421
9422 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9423   LLVMContext *Context = DAG.getContext();
9424   SDLoc dl(Op);
9425   MVT VT = Op.getSimpleValueType();
9426   MVT EltVT = VT;
9427   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9428   if (VT.isVector()) {
9429     EltVT = VT.getVectorElementType();
9430     NumElts = VT.getVectorNumElements();
9431   }
9432   Constant *C;
9433   if (EltVT == MVT::f64)
9434     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9435                                           APInt(64, ~(1ULL << 63))));
9436   else
9437     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9438                                           APInt(32, ~(1U << 31))));
9439   C = ConstantVector::getSplat(NumElts, C);
9440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9441   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9442   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9443   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9444                              MachinePointerInfo::getConstantPool(),
9445                              false, false, false, Alignment);
9446   if (VT.isVector()) {
9447     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9448     return DAG.getNode(ISD::BITCAST, dl, VT,
9449                        DAG.getNode(ISD::AND, dl, ANDVT,
9450                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9451                                                Op.getOperand(0)),
9452                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9453   }
9454   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9455 }
9456
9457 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9458   LLVMContext *Context = DAG.getContext();
9459   SDLoc dl(Op);
9460   MVT VT = Op.getSimpleValueType();
9461   MVT EltVT = VT;
9462   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9463   if (VT.isVector()) {
9464     EltVT = VT.getVectorElementType();
9465     NumElts = VT.getVectorNumElements();
9466   }
9467   Constant *C;
9468   if (EltVT == MVT::f64)
9469     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9470                                           APInt(64, 1ULL << 63)));
9471   else
9472     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9473                                           APInt(32, 1U << 31)));
9474   C = ConstantVector::getSplat(NumElts, C);
9475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9476   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9477   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9478   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9479                              MachinePointerInfo::getConstantPool(),
9480                              false, false, false, Alignment);
9481   if (VT.isVector()) {
9482     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9483     return DAG.getNode(ISD::BITCAST, dl, VT,
9484                        DAG.getNode(ISD::XOR, dl, XORVT,
9485                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9486                                                Op.getOperand(0)),
9487                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9488   }
9489
9490   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9491 }
9492
9493 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9495   LLVMContext *Context = DAG.getContext();
9496   SDValue Op0 = Op.getOperand(0);
9497   SDValue Op1 = Op.getOperand(1);
9498   SDLoc dl(Op);
9499   MVT VT = Op.getSimpleValueType();
9500   MVT SrcVT = Op1.getSimpleValueType();
9501
9502   // If second operand is smaller, extend it first.
9503   if (SrcVT.bitsLT(VT)) {
9504     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9505     SrcVT = VT;
9506   }
9507   // And if it is bigger, shrink it first.
9508   if (SrcVT.bitsGT(VT)) {
9509     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9510     SrcVT = VT;
9511   }
9512
9513   // At this point the operands and the result should have the same
9514   // type, and that won't be f80 since that is not custom lowered.
9515
9516   // First get the sign bit of second operand.
9517   SmallVector<Constant*,4> CV;
9518   if (SrcVT == MVT::f64) {
9519     const fltSemantics &Sem = APFloat::IEEEdouble;
9520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9521     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9522   } else {
9523     const fltSemantics &Sem = APFloat::IEEEsingle;
9524     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9525     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9526     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9527     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9528   }
9529   Constant *C = ConstantVector::get(CV);
9530   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9531   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9532                               MachinePointerInfo::getConstantPool(),
9533                               false, false, false, 16);
9534   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9535
9536   // Shift sign bit right or left if the two operands have different types.
9537   if (SrcVT.bitsGT(VT)) {
9538     // Op0 is MVT::f32, Op1 is MVT::f64.
9539     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9540     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9541                           DAG.getConstant(32, MVT::i32));
9542     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9543     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9544                           DAG.getIntPtrConstant(0));
9545   }
9546
9547   // Clear first operand sign bit.
9548   CV.clear();
9549   if (VT == MVT::f64) {
9550     const fltSemantics &Sem = APFloat::IEEEdouble;
9551     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9552                                                    APInt(64, ~(1ULL << 63)))));
9553     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9554   } else {
9555     const fltSemantics &Sem = APFloat::IEEEsingle;
9556     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9557                                                    APInt(32, ~(1U << 31)))));
9558     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9559     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9560     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9561   }
9562   C = ConstantVector::get(CV);
9563   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9564   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9565                               MachinePointerInfo::getConstantPool(),
9566                               false, false, false, 16);
9567   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9568
9569   // Or the value with the sign bit.
9570   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9571 }
9572
9573 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9574   SDValue N0 = Op.getOperand(0);
9575   SDLoc dl(Op);
9576   MVT VT = Op.getSimpleValueType();
9577
9578   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9579   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9580                                   DAG.getConstant(1, VT));
9581   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9582 }
9583
9584 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9585 //
9586 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9587                                       SelectionDAG &DAG) {
9588   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9589
9590   if (!Subtarget->hasSSE41())
9591     return SDValue();
9592
9593   if (!Op->hasOneUse())
9594     return SDValue();
9595
9596   SDNode *N = Op.getNode();
9597   SDLoc DL(N);
9598
9599   SmallVector<SDValue, 8> Opnds;
9600   DenseMap<SDValue, unsigned> VecInMap;
9601   SmallVector<SDValue, 8> VecIns;
9602   EVT VT = MVT::Other;
9603
9604   // Recognize a special case where a vector is casted into wide integer to
9605   // test all 0s.
9606   Opnds.push_back(N->getOperand(0));
9607   Opnds.push_back(N->getOperand(1));
9608
9609   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9610     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9611     // BFS traverse all OR'd operands.
9612     if (I->getOpcode() == ISD::OR) {
9613       Opnds.push_back(I->getOperand(0));
9614       Opnds.push_back(I->getOperand(1));
9615       // Re-evaluate the number of nodes to be traversed.
9616       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9617       continue;
9618     }
9619
9620     // Quit if a non-EXTRACT_VECTOR_ELT
9621     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9622       return SDValue();
9623
9624     // Quit if without a constant index.
9625     SDValue Idx = I->getOperand(1);
9626     if (!isa<ConstantSDNode>(Idx))
9627       return SDValue();
9628
9629     SDValue ExtractedFromVec = I->getOperand(0);
9630     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9631     if (M == VecInMap.end()) {
9632       VT = ExtractedFromVec.getValueType();
9633       // Quit if not 128/256-bit vector.
9634       if (!VT.is128BitVector() && !VT.is256BitVector())
9635         return SDValue();
9636       // Quit if not the same type.
9637       if (VecInMap.begin() != VecInMap.end() &&
9638           VT != VecInMap.begin()->first.getValueType())
9639         return SDValue();
9640       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9641       VecIns.push_back(ExtractedFromVec);
9642     }
9643     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9644   }
9645
9646   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9647          "Not extracted from 128-/256-bit vector.");
9648
9649   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9650
9651   for (DenseMap<SDValue, unsigned>::const_iterator
9652         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9653     // Quit if not all elements are used.
9654     if (I->second != FullMask)
9655       return SDValue();
9656   }
9657
9658   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9659
9660   // Cast all vectors into TestVT for PTEST.
9661   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9662     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9663
9664   // If more than one full vectors are evaluated, OR them first before PTEST.
9665   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9666     // Each iteration will OR 2 nodes and append the result until there is only
9667     // 1 node left, i.e. the final OR'd value of all vectors.
9668     SDValue LHS = VecIns[Slot];
9669     SDValue RHS = VecIns[Slot + 1];
9670     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9671   }
9672
9673   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9674                      VecIns.back(), VecIns.back());
9675 }
9676
9677 /// \brief return true if \c Op has a use that doesn't just read flags.
9678 static bool hasNonFlagsUse(SDValue Op) {
9679   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9680        ++UI) {
9681     SDNode *User = *UI;
9682     unsigned UOpNo = UI.getOperandNo();
9683     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9684       // Look pass truncate.
9685       UOpNo = User->use_begin().getOperandNo();
9686       User = *User->use_begin();
9687     }
9688
9689     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9690         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9691       return true;
9692   }
9693   return false;
9694 }
9695
9696 /// Emit nodes that will be selected as "test Op0,Op0", or something
9697 /// equivalent.
9698 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9699                                     SelectionDAG &DAG) const {
9700   if (Op.getValueType() == MVT::i1)
9701     // KORTEST instruction should be selected
9702     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9703                        DAG.getConstant(0, Op.getValueType()));
9704
9705   // CF and OF aren't always set the way we want. Determine which
9706   // of these we need.
9707   bool NeedCF = false;
9708   bool NeedOF = false;
9709   switch (X86CC) {
9710   default: break;
9711   case X86::COND_A: case X86::COND_AE:
9712   case X86::COND_B: case X86::COND_BE:
9713     NeedCF = true;
9714     break;
9715   case X86::COND_G: case X86::COND_GE:
9716   case X86::COND_L: case X86::COND_LE:
9717   case X86::COND_O: case X86::COND_NO:
9718     NeedOF = true;
9719     break;
9720   }
9721   // See if we can use the EFLAGS value from the operand instead of
9722   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9723   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9724   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9725     // Emit a CMP with 0, which is the TEST pattern.
9726     //if (Op.getValueType() == MVT::i1)
9727     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9728     //                     DAG.getConstant(0, MVT::i1));
9729     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9730                        DAG.getConstant(0, Op.getValueType()));
9731   }
9732   unsigned Opcode = 0;
9733   unsigned NumOperands = 0;
9734
9735   // Truncate operations may prevent the merge of the SETCC instruction
9736   // and the arithmetic instruction before it. Attempt to truncate the operands
9737   // of the arithmetic instruction and use a reduced bit-width instruction.
9738   bool NeedTruncation = false;
9739   SDValue ArithOp = Op;
9740   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9741     SDValue Arith = Op->getOperand(0);
9742     // Both the trunc and the arithmetic op need to have one user each.
9743     if (Arith->hasOneUse())
9744       switch (Arith.getOpcode()) {
9745         default: break;
9746         case ISD::ADD:
9747         case ISD::SUB:
9748         case ISD::AND:
9749         case ISD::OR:
9750         case ISD::XOR: {
9751           NeedTruncation = true;
9752           ArithOp = Arith;
9753         }
9754       }
9755   }
9756
9757   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9758   // which may be the result of a CAST.  We use the variable 'Op', which is the
9759   // non-casted variable when we check for possible users.
9760   switch (ArithOp.getOpcode()) {
9761   case ISD::ADD:
9762     // Due to an isel shortcoming, be conservative if this add is likely to be
9763     // selected as part of a load-modify-store instruction. When the root node
9764     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9765     // uses of other nodes in the match, such as the ADD in this case. This
9766     // leads to the ADD being left around and reselected, with the result being
9767     // two adds in the output.  Alas, even if none our users are stores, that
9768     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9769     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9770     // climbing the DAG back to the root, and it doesn't seem to be worth the
9771     // effort.
9772     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9773          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9774       if (UI->getOpcode() != ISD::CopyToReg &&
9775           UI->getOpcode() != ISD::SETCC &&
9776           UI->getOpcode() != ISD::STORE)
9777         goto default_case;
9778
9779     if (ConstantSDNode *C =
9780         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9781       // An add of one will be selected as an INC.
9782       if (C->getAPIntValue() == 1) {
9783         Opcode = X86ISD::INC;
9784         NumOperands = 1;
9785         break;
9786       }
9787
9788       // An add of negative one (subtract of one) will be selected as a DEC.
9789       if (C->getAPIntValue().isAllOnesValue()) {
9790         Opcode = X86ISD::DEC;
9791         NumOperands = 1;
9792         break;
9793       }
9794     }
9795
9796     // Otherwise use a regular EFLAGS-setting add.
9797     Opcode = X86ISD::ADD;
9798     NumOperands = 2;
9799     break;
9800   case ISD::SHL:
9801   case ISD::SRL:
9802     // If we have a constant logical shift that's only used in a comparison
9803     // against zero turn it into an equivalent AND. This allows turning it into
9804     // a TEST instruction later.
9805     if (isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9806       EVT VT = Op.getValueType();
9807       unsigned BitWidth = VT.getSizeInBits();
9808       unsigned ShAmt = Op->getConstantOperandVal(1);
9809       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9810         break;
9811       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9812                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9813                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9814       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9815         break;
9816       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9817                                 DAG.getConstant(Mask, VT));
9818       DAG.ReplaceAllUsesWith(Op, New);
9819       Op = New;
9820     }
9821     break;
9822
9823   case ISD::AND:
9824     // If the primary and result isn't used, don't bother using X86ISD::AND,
9825     // because a TEST instruction will be better.
9826     if (!hasNonFlagsUse(Op))
9827       break;
9828     // FALL THROUGH
9829   case ISD::SUB:
9830   case ISD::OR:
9831   case ISD::XOR:
9832     // Due to the ISEL shortcoming noted above, be conservative if this op is
9833     // likely to be selected as part of a load-modify-store instruction.
9834     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9835            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9836       if (UI->getOpcode() == ISD::STORE)
9837         goto default_case;
9838
9839     // Otherwise use a regular EFLAGS-setting instruction.
9840     switch (ArithOp.getOpcode()) {
9841     default: llvm_unreachable("unexpected operator!");
9842     case ISD::SUB: Opcode = X86ISD::SUB; break;
9843     case ISD::XOR: Opcode = X86ISD::XOR; break;
9844     case ISD::AND: Opcode = X86ISD::AND; break;
9845     case ISD::OR: {
9846       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9847         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9848         if (EFLAGS.getNode())
9849           return EFLAGS;
9850       }
9851       Opcode = X86ISD::OR;
9852       break;
9853     }
9854     }
9855
9856     NumOperands = 2;
9857     break;
9858   case X86ISD::ADD:
9859   case X86ISD::SUB:
9860   case X86ISD::INC:
9861   case X86ISD::DEC:
9862   case X86ISD::OR:
9863   case X86ISD::XOR:
9864   case X86ISD::AND:
9865     return SDValue(Op.getNode(), 1);
9866   default:
9867   default_case:
9868     break;
9869   }
9870
9871   // If we found that truncation is beneficial, perform the truncation and
9872   // update 'Op'.
9873   if (NeedTruncation) {
9874     EVT VT = Op.getValueType();
9875     SDValue WideVal = Op->getOperand(0);
9876     EVT WideVT = WideVal.getValueType();
9877     unsigned ConvertedOp = 0;
9878     // Use a target machine opcode to prevent further DAGCombine
9879     // optimizations that may separate the arithmetic operations
9880     // from the setcc node.
9881     switch (WideVal.getOpcode()) {
9882       default: break;
9883       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9884       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9885       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9886       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9887       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9888     }
9889
9890     if (ConvertedOp) {
9891       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9892       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9893         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9894         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9895         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9896       }
9897     }
9898   }
9899
9900   if (Opcode == 0)
9901     // Emit a CMP with 0, which is the TEST pattern.
9902     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9903                        DAG.getConstant(0, Op.getValueType()));
9904
9905   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9906   SmallVector<SDValue, 4> Ops;
9907   for (unsigned i = 0; i != NumOperands; ++i)
9908     Ops.push_back(Op.getOperand(i));
9909
9910   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9911   DAG.ReplaceAllUsesWith(Op, New);
9912   return SDValue(New.getNode(), 1);
9913 }
9914
9915 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9916 /// equivalent.
9917 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9918                                    SDLoc dl, SelectionDAG &DAG) const {
9919   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9920     if (C->getAPIntValue() == 0)
9921       return EmitTest(Op0, X86CC, dl, DAG);
9922
9923      if (Op0.getValueType() == MVT::i1)
9924        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9925   }
9926  
9927   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9928        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9929     // Do the comparison at i32 if it's smaller, besides the Atom case. 
9930     // This avoids subregister aliasing issues. Keep the smaller reference 
9931     // if we're optimizing for size, however, as that'll allow better folding 
9932     // of memory operations.
9933     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9934         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9935              AttributeSet::FunctionIndex, Attribute::MinSize) &&
9936         !Subtarget->isAtom()) {
9937       unsigned ExtendOp =
9938           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9939       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9940       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9941     }
9942     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9943     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9944     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9945                               Op0, Op1);
9946     return SDValue(Sub.getNode(), 1);
9947   }
9948   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9949 }
9950
9951 /// Convert a comparison if required by the subtarget.
9952 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9953                                                  SelectionDAG &DAG) const {
9954   // If the subtarget does not support the FUCOMI instruction, floating-point
9955   // comparisons have to be converted.
9956   if (Subtarget->hasCMov() ||
9957       Cmp.getOpcode() != X86ISD::CMP ||
9958       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9959       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9960     return Cmp;
9961
9962   // The instruction selector will select an FUCOM instruction instead of
9963   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9964   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9965   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9966   SDLoc dl(Cmp);
9967   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9968   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9969   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9970                             DAG.getConstant(8, MVT::i8));
9971   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9972   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9973 }
9974
9975 static bool isAllOnes(SDValue V) {
9976   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9977   return C && C->isAllOnesValue();
9978 }
9979
9980 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9981 /// if it's possible.
9982 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9983                                      SDLoc dl, SelectionDAG &DAG) const {
9984   SDValue Op0 = And.getOperand(0);
9985   SDValue Op1 = And.getOperand(1);
9986   if (Op0.getOpcode() == ISD::TRUNCATE)
9987     Op0 = Op0.getOperand(0);
9988   if (Op1.getOpcode() == ISD::TRUNCATE)
9989     Op1 = Op1.getOperand(0);
9990
9991   SDValue LHS, RHS;
9992   if (Op1.getOpcode() == ISD::SHL)
9993     std::swap(Op0, Op1);
9994   if (Op0.getOpcode() == ISD::SHL) {
9995     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9996       if (And00C->getZExtValue() == 1) {
9997         // If we looked past a truncate, check that it's only truncating away
9998         // known zeros.
9999         unsigned BitWidth = Op0.getValueSizeInBits();
10000         unsigned AndBitWidth = And.getValueSizeInBits();
10001         if (BitWidth > AndBitWidth) {
10002           APInt Zeros, Ones;
10003           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10004           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10005             return SDValue();
10006         }
10007         LHS = Op1;
10008         RHS = Op0.getOperand(1);
10009       }
10010   } else if (Op1.getOpcode() == ISD::Constant) {
10011     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10012     uint64_t AndRHSVal = AndRHS->getZExtValue();
10013     SDValue AndLHS = Op0;
10014
10015     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10016       LHS = AndLHS.getOperand(0);
10017       RHS = AndLHS.getOperand(1);
10018     }
10019
10020     // Use BT if the immediate can't be encoded in a TEST instruction.
10021     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10022       LHS = AndLHS;
10023       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10024     }
10025   }
10026
10027   if (LHS.getNode()) {
10028     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10029     // instruction.  Since the shift amount is in-range-or-undefined, we know
10030     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10031     // the encoding for the i16 version is larger than the i32 version.
10032     // Also promote i16 to i32 for performance / code size reason.
10033     if (LHS.getValueType() == MVT::i8 ||
10034         LHS.getValueType() == MVT::i16)
10035       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10036
10037     // If the operand types disagree, extend the shift amount to match.  Since
10038     // BT ignores high bits (like shifts) we can use anyextend.
10039     if (LHS.getValueType() != RHS.getValueType())
10040       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10041
10042     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10043     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10044     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10045                        DAG.getConstant(Cond, MVT::i8), BT);
10046   }
10047
10048   return SDValue();
10049 }
10050
10051 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10052 /// mask CMPs.
10053 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10054                               SDValue &Op1) {
10055   unsigned SSECC;
10056   bool Swap = false;
10057
10058   // SSE Condition code mapping:
10059   //  0 - EQ
10060   //  1 - LT
10061   //  2 - LE
10062   //  3 - UNORD
10063   //  4 - NEQ
10064   //  5 - NLT
10065   //  6 - NLE
10066   //  7 - ORD
10067   switch (SetCCOpcode) {
10068   default: llvm_unreachable("Unexpected SETCC condition");
10069   case ISD::SETOEQ:
10070   case ISD::SETEQ:  SSECC = 0; break;
10071   case ISD::SETOGT:
10072   case ISD::SETGT:  Swap = true; // Fallthrough
10073   case ISD::SETLT:
10074   case ISD::SETOLT: SSECC = 1; break;
10075   case ISD::SETOGE:
10076   case ISD::SETGE:  Swap = true; // Fallthrough
10077   case ISD::SETLE:
10078   case ISD::SETOLE: SSECC = 2; break;
10079   case ISD::SETUO:  SSECC = 3; break;
10080   case ISD::SETUNE:
10081   case ISD::SETNE:  SSECC = 4; break;
10082   case ISD::SETULE: Swap = true; // Fallthrough
10083   case ISD::SETUGE: SSECC = 5; break;
10084   case ISD::SETULT: Swap = true; // Fallthrough
10085   case ISD::SETUGT: SSECC = 6; break;
10086   case ISD::SETO:   SSECC = 7; break;
10087   case ISD::SETUEQ:
10088   case ISD::SETONE: SSECC = 8; break;
10089   }
10090   if (Swap)
10091     std::swap(Op0, Op1);
10092
10093   return SSECC;
10094 }
10095
10096 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10097 // ones, and then concatenate the result back.
10098 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10099   MVT VT = Op.getSimpleValueType();
10100
10101   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10102          "Unsupported value type for operation");
10103
10104   unsigned NumElems = VT.getVectorNumElements();
10105   SDLoc dl(Op);
10106   SDValue CC = Op.getOperand(2);
10107
10108   // Extract the LHS vectors
10109   SDValue LHS = Op.getOperand(0);
10110   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10111   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10112
10113   // Extract the RHS vectors
10114   SDValue RHS = Op.getOperand(1);
10115   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10116   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10117
10118   // Issue the operation on the smaller types and concatenate the result back
10119   MVT EltVT = VT.getVectorElementType();
10120   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10121   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10122                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10123                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10124 }
10125
10126 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10127                                      const X86Subtarget *Subtarget) {
10128   SDValue Op0 = Op.getOperand(0);
10129   SDValue Op1 = Op.getOperand(1);
10130   SDValue CC = Op.getOperand(2);
10131   MVT VT = Op.getSimpleValueType();
10132   SDLoc dl(Op);
10133
10134   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10135          Op.getValueType().getScalarType() == MVT::i1 &&
10136          "Cannot set masked compare for this operation");
10137
10138   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10139   unsigned  Opc = 0;
10140   bool Unsigned = false;
10141   bool Swap = false;
10142   unsigned SSECC;
10143   switch (SetCCOpcode) {
10144   default: llvm_unreachable("Unexpected SETCC condition");
10145   case ISD::SETNE:  SSECC = 4; break;
10146   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10147   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10148   case ISD::SETLT:  Swap = true; //fall-through
10149   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10150   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10151   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10152   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10153   case ISD::SETULE: Unsigned = true; //fall-through
10154   case ISD::SETLE:  SSECC = 2; break;
10155   }
10156
10157   if (Swap)
10158     std::swap(Op0, Op1);
10159   if (Opc)
10160     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10161   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10162   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10163                      DAG.getConstant(SSECC, MVT::i8));
10164 }
10165
10166 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10167 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10168 /// return an empty value.
10169 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10170 {
10171   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10172   if (!BV)
10173     return SDValue();
10174
10175   MVT VT = Op1.getSimpleValueType();
10176   MVT EVT = VT.getVectorElementType();
10177   unsigned n = VT.getVectorNumElements();
10178   SmallVector<SDValue, 8> ULTOp1;
10179
10180   for (unsigned i = 0; i < n; ++i) {
10181     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10182     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10183       return SDValue();
10184
10185     // Avoid underflow.
10186     APInt Val = Elt->getAPIntValue();
10187     if (Val == 0)
10188       return SDValue();
10189
10190     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10191   }
10192
10193   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10194 }
10195
10196 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10197                            SelectionDAG &DAG) {
10198   SDValue Op0 = Op.getOperand(0);
10199   SDValue Op1 = Op.getOperand(1);
10200   SDValue CC = Op.getOperand(2);
10201   MVT VT = Op.getSimpleValueType();
10202   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10203   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10204   SDLoc dl(Op);
10205
10206   if (isFP) {
10207 #ifndef NDEBUG
10208     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10209     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10210 #endif
10211
10212     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10213     unsigned Opc = X86ISD::CMPP;
10214     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10215       assert(VT.getVectorNumElements() <= 16);
10216       Opc = X86ISD::CMPM;
10217     }
10218     // In the two special cases we can't handle, emit two comparisons.
10219     if (SSECC == 8) {
10220       unsigned CC0, CC1;
10221       unsigned CombineOpc;
10222       if (SetCCOpcode == ISD::SETUEQ) {
10223         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10224       } else {
10225         assert(SetCCOpcode == ISD::SETONE);
10226         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10227       }
10228
10229       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10230                                  DAG.getConstant(CC0, MVT::i8));
10231       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10232                                  DAG.getConstant(CC1, MVT::i8));
10233       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10234     }
10235     // Handle all other FP comparisons here.
10236     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10237                        DAG.getConstant(SSECC, MVT::i8));
10238   }
10239
10240   // Break 256-bit integer vector compare into smaller ones.
10241   if (VT.is256BitVector() && !Subtarget->hasInt256())
10242     return Lower256IntVSETCC(Op, DAG);
10243
10244   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10245   EVT OpVT = Op1.getValueType();
10246   if (Subtarget->hasAVX512()) {
10247     if (Op1.getValueType().is512BitVector() ||
10248         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10249       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10250
10251     // In AVX-512 architecture setcc returns mask with i1 elements,
10252     // But there is no compare instruction for i8 and i16 elements.
10253     // We are not talking about 512-bit operands in this case, these
10254     // types are illegal.
10255     if (MaskResult &&
10256         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10257          OpVT.getVectorElementType().getSizeInBits() >= 8))
10258       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10259                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10260   }
10261
10262   // We are handling one of the integer comparisons here.  Since SSE only has
10263   // GT and EQ comparisons for integer, swapping operands and multiple
10264   // operations may be required for some comparisons.
10265   unsigned Opc;
10266   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10267   bool Subus = false;
10268
10269   switch (SetCCOpcode) {
10270   default: llvm_unreachable("Unexpected SETCC condition");
10271   case ISD::SETNE:  Invert = true;
10272   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10273   case ISD::SETLT:  Swap = true;
10274   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10275   case ISD::SETGE:  Swap = true;
10276   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10277                     Invert = true; break;
10278   case ISD::SETULT: Swap = true;
10279   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10280                     FlipSigns = true; break;
10281   case ISD::SETUGE: Swap = true;
10282   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10283                     FlipSigns = true; Invert = true; break;
10284   }
10285
10286   // Special case: Use min/max operations for SETULE/SETUGE
10287   MVT VET = VT.getVectorElementType();
10288   bool hasMinMax =
10289        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10290     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10291
10292   if (hasMinMax) {
10293     switch (SetCCOpcode) {
10294     default: break;
10295     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10296     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10297     }
10298
10299     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10300   }
10301
10302   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10303   if (!MinMax && hasSubus) {
10304     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10305     // Op0 u<= Op1:
10306     //   t = psubus Op0, Op1
10307     //   pcmpeq t, <0..0>
10308     switch (SetCCOpcode) {
10309     default: break;
10310     case ISD::SETULT: {
10311       // If the comparison is against a constant we can turn this into a
10312       // setule.  With psubus, setule does not require a swap.  This is
10313       // beneficial because the constant in the register is no longer
10314       // destructed as the destination so it can be hoisted out of a loop.
10315       // Only do this pre-AVX since vpcmp* is no longer destructive.
10316       if (Subtarget->hasAVX())
10317         break;
10318       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10319       if (ULEOp1.getNode()) {
10320         Op1 = ULEOp1;
10321         Subus = true; Invert = false; Swap = false;
10322       }
10323       break;
10324     }
10325     // Psubus is better than flip-sign because it requires no inversion.
10326     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10327     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10328     }
10329
10330     if (Subus) {
10331       Opc = X86ISD::SUBUS;
10332       FlipSigns = false;
10333     }
10334   }
10335
10336   if (Swap)
10337     std::swap(Op0, Op1);
10338
10339   // Check that the operation in question is available (most are plain SSE2,
10340   // but PCMPGTQ and PCMPEQQ have different requirements).
10341   if (VT == MVT::v2i64) {
10342     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10343       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10344
10345       // First cast everything to the right type.
10346       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10347       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10348
10349       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10350       // bits of the inputs before performing those operations. The lower
10351       // compare is always unsigned.
10352       SDValue SB;
10353       if (FlipSigns) {
10354         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10355       } else {
10356         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10357         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10358         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10359                          Sign, Zero, Sign, Zero);
10360       }
10361       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10362       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10363
10364       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10365       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10366       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10367
10368       // Create masks for only the low parts/high parts of the 64 bit integers.
10369       static const int MaskHi[] = { 1, 1, 3, 3 };
10370       static const int MaskLo[] = { 0, 0, 2, 2 };
10371       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10372       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10373       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10374
10375       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10376       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10377
10378       if (Invert)
10379         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10380
10381       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10382     }
10383
10384     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10385       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10386       // pcmpeqd + pshufd + pand.
10387       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10388
10389       // First cast everything to the right type.
10390       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10391       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10392
10393       // Do the compare.
10394       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10395
10396       // Make sure the lower and upper halves are both all-ones.
10397       static const int Mask[] = { 1, 0, 3, 2 };
10398       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10399       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10400
10401       if (Invert)
10402         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10403
10404       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10405     }
10406   }
10407
10408   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10409   // bits of the inputs before performing those operations.
10410   if (FlipSigns) {
10411     EVT EltVT = VT.getVectorElementType();
10412     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10413     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10414     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10415   }
10416
10417   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10418
10419   // If the logical-not of the result is required, perform that now.
10420   if (Invert)
10421     Result = DAG.getNOT(dl, Result, VT);
10422
10423   if (MinMax)
10424     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10425
10426   if (Subus)
10427     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10428                          getZeroVector(VT, Subtarget, DAG, dl));
10429
10430   return Result;
10431 }
10432
10433 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10434
10435   MVT VT = Op.getSimpleValueType();
10436
10437   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10438
10439   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10440          && "SetCC type must be 8-bit or 1-bit integer");
10441   SDValue Op0 = Op.getOperand(0);
10442   SDValue Op1 = Op.getOperand(1);
10443   SDLoc dl(Op);
10444   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10445
10446   // Optimize to BT if possible.
10447   // Lower (X & (1 << N)) == 0 to BT(X, N).
10448   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10449   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10450   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10451       Op1.getOpcode() == ISD::Constant &&
10452       cast<ConstantSDNode>(Op1)->isNullValue() &&
10453       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10454     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10455     if (NewSetCC.getNode())
10456       return NewSetCC;
10457   }
10458
10459   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10460   // these.
10461   if (Op1.getOpcode() == ISD::Constant &&
10462       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10463        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10464       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10465
10466     // If the input is a setcc, then reuse the input setcc or use a new one with
10467     // the inverted condition.
10468     if (Op0.getOpcode() == X86ISD::SETCC) {
10469       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10470       bool Invert = (CC == ISD::SETNE) ^
10471         cast<ConstantSDNode>(Op1)->isNullValue();
10472       if (!Invert)
10473         return Op0;
10474
10475       CCode = X86::GetOppositeBranchCondition(CCode);
10476       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10477                                   DAG.getConstant(CCode, MVT::i8),
10478                                   Op0.getOperand(1));
10479       if (VT == MVT::i1)
10480         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10481       return SetCC;
10482     }
10483   }
10484   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10485       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10486       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10487
10488     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10489     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10490   }
10491
10492   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10493   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10494   if (X86CC == X86::COND_INVALID)
10495     return SDValue();
10496
10497   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10498   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10499   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10500                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10501   if (VT == MVT::i1)
10502     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10503   return SetCC;
10504 }
10505
10506 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10507 static bool isX86LogicalCmp(SDValue Op) {
10508   unsigned Opc = Op.getNode()->getOpcode();
10509   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10510       Opc == X86ISD::SAHF)
10511     return true;
10512   if (Op.getResNo() == 1 &&
10513       (Opc == X86ISD::ADD ||
10514        Opc == X86ISD::SUB ||
10515        Opc == X86ISD::ADC ||
10516        Opc == X86ISD::SBB ||
10517        Opc == X86ISD::SMUL ||
10518        Opc == X86ISD::UMUL ||
10519        Opc == X86ISD::INC ||
10520        Opc == X86ISD::DEC ||
10521        Opc == X86ISD::OR ||
10522        Opc == X86ISD::XOR ||
10523        Opc == X86ISD::AND))
10524     return true;
10525
10526   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10527     return true;
10528
10529   return false;
10530 }
10531
10532 static bool isZero(SDValue V) {
10533   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10534   return C && C->isNullValue();
10535 }
10536
10537 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10538   if (V.getOpcode() != ISD::TRUNCATE)
10539     return false;
10540
10541   SDValue VOp0 = V.getOperand(0);
10542   unsigned InBits = VOp0.getValueSizeInBits();
10543   unsigned Bits = V.getValueSizeInBits();
10544   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10545 }
10546
10547 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10548   bool addTest = true;
10549   SDValue Cond  = Op.getOperand(0);
10550   SDValue Op1 = Op.getOperand(1);
10551   SDValue Op2 = Op.getOperand(2);
10552   SDLoc DL(Op);
10553   EVT VT = Op1.getValueType();
10554   SDValue CC;
10555
10556   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10557   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10558   // sequence later on.
10559   if (Cond.getOpcode() == ISD::SETCC &&
10560       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10561        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10562       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10563     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10564     int SSECC = translateX86FSETCC(
10565         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10566
10567     if (SSECC != 8) {
10568       if (Subtarget->hasAVX512()) {
10569         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10570                                   DAG.getConstant(SSECC, MVT::i8));
10571         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10572       }
10573       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10574                                 DAG.getConstant(SSECC, MVT::i8));
10575       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10576       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10577       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10578     }
10579   }
10580
10581   if (Cond.getOpcode() == ISD::SETCC) {
10582     SDValue NewCond = LowerSETCC(Cond, DAG);
10583     if (NewCond.getNode())
10584       Cond = NewCond;
10585   }
10586
10587   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10588   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10589   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10590   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10591   if (Cond.getOpcode() == X86ISD::SETCC &&
10592       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10593       isZero(Cond.getOperand(1).getOperand(1))) {
10594     SDValue Cmp = Cond.getOperand(1);
10595
10596     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10597
10598     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10599         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10600       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10601
10602       SDValue CmpOp0 = Cmp.getOperand(0);
10603       // Apply further optimizations for special cases
10604       // (select (x != 0), -1, 0) -> neg & sbb
10605       // (select (x == 0), 0, -1) -> neg & sbb
10606       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10607         if (YC->isNullValue() &&
10608             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10609           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10610           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10611                                     DAG.getConstant(0, CmpOp0.getValueType()),
10612                                     CmpOp0);
10613           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10614                                     DAG.getConstant(X86::COND_B, MVT::i8),
10615                                     SDValue(Neg.getNode(), 1));
10616           return Res;
10617         }
10618
10619       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10620                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10621       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10622
10623       SDValue Res =   // Res = 0 or -1.
10624         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10625                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10626
10627       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10628         Res = DAG.getNOT(DL, Res, Res.getValueType());
10629
10630       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10631       if (N2C == 0 || !N2C->isNullValue())
10632         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10633       return Res;
10634     }
10635   }
10636
10637   // Look past (and (setcc_carry (cmp ...)), 1).
10638   if (Cond.getOpcode() == ISD::AND &&
10639       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10640     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10641     if (C && C->getAPIntValue() == 1)
10642       Cond = Cond.getOperand(0);
10643   }
10644
10645   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10646   // setting operand in place of the X86ISD::SETCC.
10647   unsigned CondOpcode = Cond.getOpcode();
10648   if (CondOpcode == X86ISD::SETCC ||
10649       CondOpcode == X86ISD::SETCC_CARRY) {
10650     CC = Cond.getOperand(0);
10651
10652     SDValue Cmp = Cond.getOperand(1);
10653     unsigned Opc = Cmp.getOpcode();
10654     MVT VT = Op.getSimpleValueType();
10655
10656     bool IllegalFPCMov = false;
10657     if (VT.isFloatingPoint() && !VT.isVector() &&
10658         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10659       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10660
10661     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10662         Opc == X86ISD::BT) { // FIXME
10663       Cond = Cmp;
10664       addTest = false;
10665     }
10666   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10667              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10668              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10669               Cond.getOperand(0).getValueType() != MVT::i8)) {
10670     SDValue LHS = Cond.getOperand(0);
10671     SDValue RHS = Cond.getOperand(1);
10672     unsigned X86Opcode;
10673     unsigned X86Cond;
10674     SDVTList VTs;
10675     switch (CondOpcode) {
10676     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10677     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10678     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10679     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10680     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10681     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10682     default: llvm_unreachable("unexpected overflowing operator");
10683     }
10684     if (CondOpcode == ISD::UMULO)
10685       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10686                           MVT::i32);
10687     else
10688       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10689
10690     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10691
10692     if (CondOpcode == ISD::UMULO)
10693       Cond = X86Op.getValue(2);
10694     else
10695       Cond = X86Op.getValue(1);
10696
10697     CC = DAG.getConstant(X86Cond, MVT::i8);
10698     addTest = false;
10699   }
10700
10701   if (addTest) {
10702     // Look pass the truncate if the high bits are known zero.
10703     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10704         Cond = Cond.getOperand(0);
10705
10706     // We know the result of AND is compared against zero. Try to match
10707     // it to BT.
10708     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10709       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10710       if (NewSetCC.getNode()) {
10711         CC = NewSetCC.getOperand(0);
10712         Cond = NewSetCC.getOperand(1);
10713         addTest = false;
10714       }
10715     }
10716   }
10717
10718   if (addTest) {
10719     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10720     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10721   }
10722
10723   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10724   // a <  b ?  0 : -1 -> RES = setcc_carry
10725   // a >= b ? -1 :  0 -> RES = setcc_carry
10726   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10727   if (Cond.getOpcode() == X86ISD::SUB) {
10728     Cond = ConvertCmpIfNecessary(Cond, DAG);
10729     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10730
10731     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10732         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10733       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10734                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10735       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10736         return DAG.getNOT(DL, Res, Res.getValueType());
10737       return Res;
10738     }
10739   }
10740
10741   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10742   // widen the cmov and push the truncate through. This avoids introducing a new
10743   // branch during isel and doesn't add any extensions.
10744   if (Op.getValueType() == MVT::i8 &&
10745       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10746     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10747     if (T1.getValueType() == T2.getValueType() &&
10748         // Blacklist CopyFromReg to avoid partial register stalls.
10749         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10750       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10751       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10752       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10753     }
10754   }
10755
10756   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10757   // condition is true.
10758   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10759   SDValue Ops[] = { Op2, Op1, CC, Cond };
10760   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10761 }
10762
10763 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10764   MVT VT = Op->getSimpleValueType(0);
10765   SDValue In = Op->getOperand(0);
10766   MVT InVT = In.getSimpleValueType();
10767   SDLoc dl(Op);
10768
10769   unsigned int NumElts = VT.getVectorNumElements();
10770   if (NumElts != 8 && NumElts != 16)
10771     return SDValue();
10772
10773   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10774     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10775
10776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10777   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10778
10779   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10780   Constant *C = ConstantInt::get(*DAG.getContext(),
10781     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10782
10783   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10784   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10785   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10786                           MachinePointerInfo::getConstantPool(),
10787                           false, false, false, Alignment);
10788   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10789   if (VT.is512BitVector())
10790     return Brcst;
10791   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10792 }
10793
10794 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10795                                 SelectionDAG &DAG) {
10796   MVT VT = Op->getSimpleValueType(0);
10797   SDValue In = Op->getOperand(0);
10798   MVT InVT = In.getSimpleValueType();
10799   SDLoc dl(Op);
10800
10801   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10802     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10803
10804   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10805       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10806       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10807     return SDValue();
10808
10809   if (Subtarget->hasInt256())
10810     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10811
10812   // Optimize vectors in AVX mode
10813   // Sign extend  v8i16 to v8i32 and
10814   //              v4i32 to v4i64
10815   //
10816   // Divide input vector into two parts
10817   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10818   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10819   // concat the vectors to original VT
10820
10821   unsigned NumElems = InVT.getVectorNumElements();
10822   SDValue Undef = DAG.getUNDEF(InVT);
10823
10824   SmallVector<int,8> ShufMask1(NumElems, -1);
10825   for (unsigned i = 0; i != NumElems/2; ++i)
10826     ShufMask1[i] = i;
10827
10828   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10829
10830   SmallVector<int,8> ShufMask2(NumElems, -1);
10831   for (unsigned i = 0; i != NumElems/2; ++i)
10832     ShufMask2[i] = i + NumElems/2;
10833
10834   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10835
10836   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10837                                 VT.getVectorNumElements()/2);
10838
10839   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10840   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10841
10842   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10843 }
10844
10845 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10846 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10847 // from the AND / OR.
10848 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10849   Opc = Op.getOpcode();
10850   if (Opc != ISD::OR && Opc != ISD::AND)
10851     return false;
10852   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10853           Op.getOperand(0).hasOneUse() &&
10854           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10855           Op.getOperand(1).hasOneUse());
10856 }
10857
10858 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10859 // 1 and that the SETCC node has a single use.
10860 static bool isXor1OfSetCC(SDValue Op) {
10861   if (Op.getOpcode() != ISD::XOR)
10862     return false;
10863   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10864   if (N1C && N1C->getAPIntValue() == 1) {
10865     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10866       Op.getOperand(0).hasOneUse();
10867   }
10868   return false;
10869 }
10870
10871 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10872   bool addTest = true;
10873   SDValue Chain = Op.getOperand(0);
10874   SDValue Cond  = Op.getOperand(1);
10875   SDValue Dest  = Op.getOperand(2);
10876   SDLoc dl(Op);
10877   SDValue CC;
10878   bool Inverted = false;
10879
10880   if (Cond.getOpcode() == ISD::SETCC) {
10881     // Check for setcc([su]{add,sub,mul}o == 0).
10882     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10883         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10884         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10885         Cond.getOperand(0).getResNo() == 1 &&
10886         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10887          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10888          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10889          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10890          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10891          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10892       Inverted = true;
10893       Cond = Cond.getOperand(0);
10894     } else {
10895       SDValue NewCond = LowerSETCC(Cond, DAG);
10896       if (NewCond.getNode())
10897         Cond = NewCond;
10898     }
10899   }
10900 #if 0
10901   // FIXME: LowerXALUO doesn't handle these!!
10902   else if (Cond.getOpcode() == X86ISD::ADD  ||
10903            Cond.getOpcode() == X86ISD::SUB  ||
10904            Cond.getOpcode() == X86ISD::SMUL ||
10905            Cond.getOpcode() == X86ISD::UMUL)
10906     Cond = LowerXALUO(Cond, DAG);
10907 #endif
10908
10909   // Look pass (and (setcc_carry (cmp ...)), 1).
10910   if (Cond.getOpcode() == ISD::AND &&
10911       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10912     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10913     if (C && C->getAPIntValue() == 1)
10914       Cond = Cond.getOperand(0);
10915   }
10916
10917   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10918   // setting operand in place of the X86ISD::SETCC.
10919   unsigned CondOpcode = Cond.getOpcode();
10920   if (CondOpcode == X86ISD::SETCC ||
10921       CondOpcode == X86ISD::SETCC_CARRY) {
10922     CC = Cond.getOperand(0);
10923
10924     SDValue Cmp = Cond.getOperand(1);
10925     unsigned Opc = Cmp.getOpcode();
10926     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10927     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10928       Cond = Cmp;
10929       addTest = false;
10930     } else {
10931       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10932       default: break;
10933       case X86::COND_O:
10934       case X86::COND_B:
10935         // These can only come from an arithmetic instruction with overflow,
10936         // e.g. SADDO, UADDO.
10937         Cond = Cond.getNode()->getOperand(1);
10938         addTest = false;
10939         break;
10940       }
10941     }
10942   }
10943   CondOpcode = Cond.getOpcode();
10944   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10945       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10946       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10947        Cond.getOperand(0).getValueType() != MVT::i8)) {
10948     SDValue LHS = Cond.getOperand(0);
10949     SDValue RHS = Cond.getOperand(1);
10950     unsigned X86Opcode;
10951     unsigned X86Cond;
10952     SDVTList VTs;
10953     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10954     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10955     // X86ISD::INC).
10956     switch (CondOpcode) {
10957     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10958     case ISD::SADDO:
10959       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10960         if (C->isOne()) {
10961           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10962           break;
10963         }
10964       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10965     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10966     case ISD::SSUBO:
10967       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10968         if (C->isOne()) {
10969           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10970           break;
10971         }
10972       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10973     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10974     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10975     default: llvm_unreachable("unexpected overflowing operator");
10976     }
10977     if (Inverted)
10978       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10979     if (CondOpcode == ISD::UMULO)
10980       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10981                           MVT::i32);
10982     else
10983       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10984
10985     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10986
10987     if (CondOpcode == ISD::UMULO)
10988       Cond = X86Op.getValue(2);
10989     else
10990       Cond = X86Op.getValue(1);
10991
10992     CC = DAG.getConstant(X86Cond, MVT::i8);
10993     addTest = false;
10994   } else {
10995     unsigned CondOpc;
10996     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10997       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10998       if (CondOpc == ISD::OR) {
10999         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11000         // two branches instead of an explicit OR instruction with a
11001         // separate test.
11002         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11003             isX86LogicalCmp(Cmp)) {
11004           CC = Cond.getOperand(0).getOperand(0);
11005           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11006                               Chain, Dest, CC, Cmp);
11007           CC = Cond.getOperand(1).getOperand(0);
11008           Cond = Cmp;
11009           addTest = false;
11010         }
11011       } else { // ISD::AND
11012         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11013         // two branches instead of an explicit AND instruction with a
11014         // separate test. However, we only do this if this block doesn't
11015         // have a fall-through edge, because this requires an explicit
11016         // jmp when the condition is false.
11017         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11018             isX86LogicalCmp(Cmp) &&
11019             Op.getNode()->hasOneUse()) {
11020           X86::CondCode CCode =
11021             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11022           CCode = X86::GetOppositeBranchCondition(CCode);
11023           CC = DAG.getConstant(CCode, MVT::i8);
11024           SDNode *User = *Op.getNode()->use_begin();
11025           // Look for an unconditional branch following this conditional branch.
11026           // We need this because we need to reverse the successors in order
11027           // to implement FCMP_OEQ.
11028           if (User->getOpcode() == ISD::BR) {
11029             SDValue FalseBB = User->getOperand(1);
11030             SDNode *NewBR =
11031               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11032             assert(NewBR == User);
11033             (void)NewBR;
11034             Dest = FalseBB;
11035
11036             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11037                                 Chain, Dest, CC, Cmp);
11038             X86::CondCode CCode =
11039               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11040             CCode = X86::GetOppositeBranchCondition(CCode);
11041             CC = DAG.getConstant(CCode, MVT::i8);
11042             Cond = Cmp;
11043             addTest = false;
11044           }
11045         }
11046       }
11047     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11048       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11049       // It should be transformed during dag combiner except when the condition
11050       // is set by a arithmetics with overflow node.
11051       X86::CondCode CCode =
11052         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11053       CCode = X86::GetOppositeBranchCondition(CCode);
11054       CC = DAG.getConstant(CCode, MVT::i8);
11055       Cond = Cond.getOperand(0).getOperand(1);
11056       addTest = false;
11057     } else if (Cond.getOpcode() == ISD::SETCC &&
11058                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11059       // For FCMP_OEQ, we can emit
11060       // two branches instead of an explicit AND instruction with a
11061       // separate test. However, we only do this if this block doesn't
11062       // have a fall-through edge, because this requires an explicit
11063       // jmp when the condition is false.
11064       if (Op.getNode()->hasOneUse()) {
11065         SDNode *User = *Op.getNode()->use_begin();
11066         // Look for an unconditional branch following this conditional branch.
11067         // We need this because we need to reverse the successors in order
11068         // to implement FCMP_OEQ.
11069         if (User->getOpcode() == ISD::BR) {
11070           SDValue FalseBB = User->getOperand(1);
11071           SDNode *NewBR =
11072             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11073           assert(NewBR == User);
11074           (void)NewBR;
11075           Dest = FalseBB;
11076
11077           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11078                                     Cond.getOperand(0), Cond.getOperand(1));
11079           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11080           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11081           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11082                               Chain, Dest, CC, Cmp);
11083           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11084           Cond = Cmp;
11085           addTest = false;
11086         }
11087       }
11088     } else if (Cond.getOpcode() == ISD::SETCC &&
11089                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11090       // For FCMP_UNE, we can emit
11091       // two branches instead of an explicit AND instruction with a
11092       // separate test. However, we only do this if this block doesn't
11093       // have a fall-through edge, because this requires an explicit
11094       // jmp when the condition is false.
11095       if (Op.getNode()->hasOneUse()) {
11096         SDNode *User = *Op.getNode()->use_begin();
11097         // Look for an unconditional branch following this conditional branch.
11098         // We need this because we need to reverse the successors in order
11099         // to implement FCMP_UNE.
11100         if (User->getOpcode() == ISD::BR) {
11101           SDValue FalseBB = User->getOperand(1);
11102           SDNode *NewBR =
11103             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11104           assert(NewBR == User);
11105           (void)NewBR;
11106
11107           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11108                                     Cond.getOperand(0), Cond.getOperand(1));
11109           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11110           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11111           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11112                               Chain, Dest, CC, Cmp);
11113           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11114           Cond = Cmp;
11115           addTest = false;
11116           Dest = FalseBB;
11117         }
11118       }
11119     }
11120   }
11121
11122   if (addTest) {
11123     // Look pass the truncate if the high bits are known zero.
11124     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11125         Cond = Cond.getOperand(0);
11126
11127     // We know the result of AND is compared against zero. Try to match
11128     // it to BT.
11129     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11130       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11131       if (NewSetCC.getNode()) {
11132         CC = NewSetCC.getOperand(0);
11133         Cond = NewSetCC.getOperand(1);
11134         addTest = false;
11135       }
11136     }
11137   }
11138
11139   if (addTest) {
11140     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11141     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11142   }
11143   Cond = ConvertCmpIfNecessary(Cond, DAG);
11144   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11145                      Chain, Dest, CC, Cond);
11146 }
11147
11148 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11149 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11150 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11151 // that the guard pages used by the OS virtual memory manager are allocated in
11152 // correct sequence.
11153 SDValue
11154 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11155                                            SelectionDAG &DAG) const {
11156   MachineFunction &MF = DAG.getMachineFunction();
11157   bool SplitStack = MF.shouldSplitStack();
11158   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11159                SplitStack;
11160   SDLoc dl(Op);
11161
11162   if (!Lower) {
11163     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11164     SDNode* Node = Op.getNode();
11165
11166     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11167     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11168         " not tell us which reg is the stack pointer!");
11169     EVT VT = Node->getValueType(0);
11170     SDValue Tmp1 = SDValue(Node, 0);
11171     SDValue Tmp2 = SDValue(Node, 1);
11172     SDValue Tmp3 = Node->getOperand(2);
11173     SDValue Chain = Tmp1.getOperand(0);
11174
11175     // Chain the dynamic stack allocation so that it doesn't modify the stack
11176     // pointer when other instructions are using the stack.
11177     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11178         SDLoc(Node));
11179
11180     SDValue Size = Tmp2.getOperand(1);
11181     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11182     Chain = SP.getValue(1);
11183     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11184     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11185     unsigned StackAlign = TFI.getStackAlignment();
11186     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11187     if (Align > StackAlign)
11188       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11189           DAG.getConstant(-(uint64_t)Align, VT));
11190     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11191
11192     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11193         DAG.getIntPtrConstant(0, true), SDValue(),
11194         SDLoc(Node));
11195
11196     SDValue Ops[2] = { Tmp1, Tmp2 };
11197     return DAG.getMergeValues(Ops, 2, dl);
11198   }
11199
11200   // Get the inputs.
11201   SDValue Chain = Op.getOperand(0);
11202   SDValue Size  = Op.getOperand(1);
11203   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11204   EVT VT = Op.getNode()->getValueType(0);
11205
11206   bool Is64Bit = Subtarget->is64Bit();
11207   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11208
11209   if (SplitStack) {
11210     MachineRegisterInfo &MRI = MF.getRegInfo();
11211
11212     if (Is64Bit) {
11213       // The 64 bit implementation of segmented stacks needs to clobber both r10
11214       // r11. This makes it impossible to use it along with nested parameters.
11215       const Function *F = MF.getFunction();
11216
11217       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11218            I != E; ++I)
11219         if (I->hasNestAttr())
11220           report_fatal_error("Cannot use segmented stacks with functions that "
11221                              "have nested arguments.");
11222     }
11223
11224     const TargetRegisterClass *AddrRegClass =
11225       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11226     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11227     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11228     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11229                                 DAG.getRegister(Vreg, SPTy));
11230     SDValue Ops1[2] = { Value, Chain };
11231     return DAG.getMergeValues(Ops1, 2, dl);
11232   } else {
11233     SDValue Flag;
11234     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11235
11236     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11237     Flag = Chain.getValue(1);
11238     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11239
11240     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11241
11242     const X86RegisterInfo *RegInfo =
11243       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11244     unsigned SPReg = RegInfo->getStackRegister();
11245     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11246     Chain = SP.getValue(1);
11247
11248     if (Align) {
11249       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11250                        DAG.getConstant(-(uint64_t)Align, VT));
11251       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11252     }
11253
11254     SDValue Ops1[2] = { SP, Chain };
11255     return DAG.getMergeValues(Ops1, 2, dl);
11256   }
11257 }
11258
11259 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11260   MachineFunction &MF = DAG.getMachineFunction();
11261   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11262
11263   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11264   SDLoc DL(Op);
11265
11266   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11267     // vastart just stores the address of the VarArgsFrameIndex slot into the
11268     // memory location argument.
11269     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11270                                    getPointerTy());
11271     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11272                         MachinePointerInfo(SV), false, false, 0);
11273   }
11274
11275   // __va_list_tag:
11276   //   gp_offset         (0 - 6 * 8)
11277   //   fp_offset         (48 - 48 + 8 * 16)
11278   //   overflow_arg_area (point to parameters coming in memory).
11279   //   reg_save_area
11280   SmallVector<SDValue, 8> MemOps;
11281   SDValue FIN = Op.getOperand(1);
11282   // Store gp_offset
11283   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11284                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11285                                                MVT::i32),
11286                                FIN, MachinePointerInfo(SV), false, false, 0);
11287   MemOps.push_back(Store);
11288
11289   // Store fp_offset
11290   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11291                     FIN, DAG.getIntPtrConstant(4));
11292   Store = DAG.getStore(Op.getOperand(0), DL,
11293                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11294                                        MVT::i32),
11295                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11296   MemOps.push_back(Store);
11297
11298   // Store ptr to overflow_arg_area
11299   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11300                     FIN, DAG.getIntPtrConstant(4));
11301   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11302                                     getPointerTy());
11303   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11304                        MachinePointerInfo(SV, 8),
11305                        false, false, 0);
11306   MemOps.push_back(Store);
11307
11308   // Store ptr to reg_save_area.
11309   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11310                     FIN, DAG.getIntPtrConstant(8));
11311   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11312                                     getPointerTy());
11313   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11314                        MachinePointerInfo(SV, 16), false, false, 0);
11315   MemOps.push_back(Store);
11316   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11317                      &MemOps[0], MemOps.size());
11318 }
11319
11320 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11321   assert(Subtarget->is64Bit() &&
11322          "LowerVAARG only handles 64-bit va_arg!");
11323   assert((Subtarget->isTargetLinux() ||
11324           Subtarget->isTargetDarwin()) &&
11325           "Unhandled target in LowerVAARG");
11326   assert(Op.getNode()->getNumOperands() == 4);
11327   SDValue Chain = Op.getOperand(0);
11328   SDValue SrcPtr = Op.getOperand(1);
11329   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11330   unsigned Align = Op.getConstantOperandVal(3);
11331   SDLoc dl(Op);
11332
11333   EVT ArgVT = Op.getNode()->getValueType(0);
11334   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11335   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11336   uint8_t ArgMode;
11337
11338   // Decide which area this value should be read from.
11339   // TODO: Implement the AMD64 ABI in its entirety. This simple
11340   // selection mechanism works only for the basic types.
11341   if (ArgVT == MVT::f80) {
11342     llvm_unreachable("va_arg for f80 not yet implemented");
11343   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11344     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11345   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11346     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11347   } else {
11348     llvm_unreachable("Unhandled argument type in LowerVAARG");
11349   }
11350
11351   if (ArgMode == 2) {
11352     // Sanity Check: Make sure using fp_offset makes sense.
11353     assert(!getTargetMachine().Options.UseSoftFloat &&
11354            !(DAG.getMachineFunction()
11355                 .getFunction()->getAttributes()
11356                 .hasAttribute(AttributeSet::FunctionIndex,
11357                               Attribute::NoImplicitFloat)) &&
11358            Subtarget->hasSSE1());
11359   }
11360
11361   // Insert VAARG_64 node into the DAG
11362   // VAARG_64 returns two values: Variable Argument Address, Chain
11363   SmallVector<SDValue, 11> InstOps;
11364   InstOps.push_back(Chain);
11365   InstOps.push_back(SrcPtr);
11366   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11367   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11368   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11369   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11370   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11371                                           VTs, &InstOps[0], InstOps.size(),
11372                                           MVT::i64,
11373                                           MachinePointerInfo(SV),
11374                                           /*Align=*/0,
11375                                           /*Volatile=*/false,
11376                                           /*ReadMem=*/true,
11377                                           /*WriteMem=*/true);
11378   Chain = VAARG.getValue(1);
11379
11380   // Load the next argument and return it
11381   return DAG.getLoad(ArgVT, dl,
11382                      Chain,
11383                      VAARG,
11384                      MachinePointerInfo(),
11385                      false, false, false, 0);
11386 }
11387
11388 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11389                            SelectionDAG &DAG) {
11390   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11391   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11392   SDValue Chain = Op.getOperand(0);
11393   SDValue DstPtr = Op.getOperand(1);
11394   SDValue SrcPtr = Op.getOperand(2);
11395   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11396   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11397   SDLoc DL(Op);
11398
11399   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11400                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11401                        false,
11402                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11403 }
11404
11405 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11406 // amount is a constant. Takes immediate version of shift as input.
11407 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11408                                           SDValue SrcOp, uint64_t ShiftAmt,
11409                                           SelectionDAG &DAG) {
11410   MVT ElementType = VT.getVectorElementType();
11411
11412   // Check for ShiftAmt >= element width
11413   if (ShiftAmt >= ElementType.getSizeInBits()) {
11414     if (Opc == X86ISD::VSRAI)
11415       ShiftAmt = ElementType.getSizeInBits() - 1;
11416     else
11417       return DAG.getConstant(0, VT);
11418   }
11419
11420   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11421          && "Unknown target vector shift-by-constant node");
11422
11423   // Fold this packed vector shift into a build vector if SrcOp is a
11424   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11425   if (VT == SrcOp.getSimpleValueType() &&
11426       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11427     SmallVector<SDValue, 8> Elts;
11428     unsigned NumElts = SrcOp->getNumOperands();
11429     ConstantSDNode *ND;
11430
11431     switch(Opc) {
11432     default: llvm_unreachable(0);
11433     case X86ISD::VSHLI:
11434       for (unsigned i=0; i!=NumElts; ++i) {
11435         SDValue CurrentOp = SrcOp->getOperand(i);
11436         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11437           Elts.push_back(CurrentOp);
11438           continue;
11439         }
11440         ND = cast<ConstantSDNode>(CurrentOp);
11441         const APInt &C = ND->getAPIntValue();
11442         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11443       }
11444       break;
11445     case X86ISD::VSRLI:
11446       for (unsigned i=0; i!=NumElts; ++i) {
11447         SDValue CurrentOp = SrcOp->getOperand(i);
11448         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11449           Elts.push_back(CurrentOp);
11450           continue;
11451         }
11452         ND = cast<ConstantSDNode>(CurrentOp);
11453         const APInt &C = ND->getAPIntValue();
11454         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11455       }
11456       break;
11457     case X86ISD::VSRAI:
11458       for (unsigned i=0; i!=NumElts; ++i) {
11459         SDValue CurrentOp = SrcOp->getOperand(i);
11460         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11461           Elts.push_back(CurrentOp);
11462           continue;
11463         }
11464         ND = cast<ConstantSDNode>(CurrentOp);
11465         const APInt &C = ND->getAPIntValue();
11466         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11467       }
11468       break;
11469     }
11470
11471     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11472   }
11473
11474   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11475 }
11476
11477 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11478 // may or may not be a constant. Takes immediate version of shift as input.
11479 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11480                                    SDValue SrcOp, SDValue ShAmt,
11481                                    SelectionDAG &DAG) {
11482   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11483
11484   // Catch shift-by-constant.
11485   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11486     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11487                                       CShAmt->getZExtValue(), DAG);
11488
11489   // Change opcode to non-immediate version
11490   switch (Opc) {
11491     default: llvm_unreachable("Unknown target vector shift node");
11492     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11493     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11494     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11495   }
11496
11497   // Need to build a vector containing shift amount
11498   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11499   SDValue ShOps[4];
11500   ShOps[0] = ShAmt;
11501   ShOps[1] = DAG.getConstant(0, MVT::i32);
11502   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11503   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11504
11505   // The return type has to be a 128-bit type with the same element
11506   // type as the input type.
11507   MVT EltVT = VT.getVectorElementType();
11508   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11509
11510   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11511   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11512 }
11513
11514 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11515   SDLoc dl(Op);
11516   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11517   switch (IntNo) {
11518   default: return SDValue();    // Don't custom lower most intrinsics.
11519   // Comparison intrinsics.
11520   case Intrinsic::x86_sse_comieq_ss:
11521   case Intrinsic::x86_sse_comilt_ss:
11522   case Intrinsic::x86_sse_comile_ss:
11523   case Intrinsic::x86_sse_comigt_ss:
11524   case Intrinsic::x86_sse_comige_ss:
11525   case Intrinsic::x86_sse_comineq_ss:
11526   case Intrinsic::x86_sse_ucomieq_ss:
11527   case Intrinsic::x86_sse_ucomilt_ss:
11528   case Intrinsic::x86_sse_ucomile_ss:
11529   case Intrinsic::x86_sse_ucomigt_ss:
11530   case Intrinsic::x86_sse_ucomige_ss:
11531   case Intrinsic::x86_sse_ucomineq_ss:
11532   case Intrinsic::x86_sse2_comieq_sd:
11533   case Intrinsic::x86_sse2_comilt_sd:
11534   case Intrinsic::x86_sse2_comile_sd:
11535   case Intrinsic::x86_sse2_comigt_sd:
11536   case Intrinsic::x86_sse2_comige_sd:
11537   case Intrinsic::x86_sse2_comineq_sd:
11538   case Intrinsic::x86_sse2_ucomieq_sd:
11539   case Intrinsic::x86_sse2_ucomilt_sd:
11540   case Intrinsic::x86_sse2_ucomile_sd:
11541   case Intrinsic::x86_sse2_ucomigt_sd:
11542   case Intrinsic::x86_sse2_ucomige_sd:
11543   case Intrinsic::x86_sse2_ucomineq_sd: {
11544     unsigned Opc;
11545     ISD::CondCode CC;
11546     switch (IntNo) {
11547     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11548     case Intrinsic::x86_sse_comieq_ss:
11549     case Intrinsic::x86_sse2_comieq_sd:
11550       Opc = X86ISD::COMI;
11551       CC = ISD::SETEQ;
11552       break;
11553     case Intrinsic::x86_sse_comilt_ss:
11554     case Intrinsic::x86_sse2_comilt_sd:
11555       Opc = X86ISD::COMI;
11556       CC = ISD::SETLT;
11557       break;
11558     case Intrinsic::x86_sse_comile_ss:
11559     case Intrinsic::x86_sse2_comile_sd:
11560       Opc = X86ISD::COMI;
11561       CC = ISD::SETLE;
11562       break;
11563     case Intrinsic::x86_sse_comigt_ss:
11564     case Intrinsic::x86_sse2_comigt_sd:
11565       Opc = X86ISD::COMI;
11566       CC = ISD::SETGT;
11567       break;
11568     case Intrinsic::x86_sse_comige_ss:
11569     case Intrinsic::x86_sse2_comige_sd:
11570       Opc = X86ISD::COMI;
11571       CC = ISD::SETGE;
11572       break;
11573     case Intrinsic::x86_sse_comineq_ss:
11574     case Intrinsic::x86_sse2_comineq_sd:
11575       Opc = X86ISD::COMI;
11576       CC = ISD::SETNE;
11577       break;
11578     case Intrinsic::x86_sse_ucomieq_ss:
11579     case Intrinsic::x86_sse2_ucomieq_sd:
11580       Opc = X86ISD::UCOMI;
11581       CC = ISD::SETEQ;
11582       break;
11583     case Intrinsic::x86_sse_ucomilt_ss:
11584     case Intrinsic::x86_sse2_ucomilt_sd:
11585       Opc = X86ISD::UCOMI;
11586       CC = ISD::SETLT;
11587       break;
11588     case Intrinsic::x86_sse_ucomile_ss:
11589     case Intrinsic::x86_sse2_ucomile_sd:
11590       Opc = X86ISD::UCOMI;
11591       CC = ISD::SETLE;
11592       break;
11593     case Intrinsic::x86_sse_ucomigt_ss:
11594     case Intrinsic::x86_sse2_ucomigt_sd:
11595       Opc = X86ISD::UCOMI;
11596       CC = ISD::SETGT;
11597       break;
11598     case Intrinsic::x86_sse_ucomige_ss:
11599     case Intrinsic::x86_sse2_ucomige_sd:
11600       Opc = X86ISD::UCOMI;
11601       CC = ISD::SETGE;
11602       break;
11603     case Intrinsic::x86_sse_ucomineq_ss:
11604     case Intrinsic::x86_sse2_ucomineq_sd:
11605       Opc = X86ISD::UCOMI;
11606       CC = ISD::SETNE;
11607       break;
11608     }
11609
11610     SDValue LHS = Op.getOperand(1);
11611     SDValue RHS = Op.getOperand(2);
11612     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11613     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11614     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11615     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11616                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11617     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11618   }
11619
11620   // Arithmetic intrinsics.
11621   case Intrinsic::x86_sse2_pmulu_dq:
11622   case Intrinsic::x86_avx2_pmulu_dq:
11623     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11624                        Op.getOperand(1), Op.getOperand(2));
11625
11626   // SSE2/AVX2 sub with unsigned saturation intrinsics
11627   case Intrinsic::x86_sse2_psubus_b:
11628   case Intrinsic::x86_sse2_psubus_w:
11629   case Intrinsic::x86_avx2_psubus_b:
11630   case Intrinsic::x86_avx2_psubus_w:
11631     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11632                        Op.getOperand(1), Op.getOperand(2));
11633
11634   // SSE3/AVX horizontal add/sub intrinsics
11635   case Intrinsic::x86_sse3_hadd_ps:
11636   case Intrinsic::x86_sse3_hadd_pd:
11637   case Intrinsic::x86_avx_hadd_ps_256:
11638   case Intrinsic::x86_avx_hadd_pd_256:
11639   case Intrinsic::x86_sse3_hsub_ps:
11640   case Intrinsic::x86_sse3_hsub_pd:
11641   case Intrinsic::x86_avx_hsub_ps_256:
11642   case Intrinsic::x86_avx_hsub_pd_256:
11643   case Intrinsic::x86_ssse3_phadd_w_128:
11644   case Intrinsic::x86_ssse3_phadd_d_128:
11645   case Intrinsic::x86_avx2_phadd_w:
11646   case Intrinsic::x86_avx2_phadd_d:
11647   case Intrinsic::x86_ssse3_phsub_w_128:
11648   case Intrinsic::x86_ssse3_phsub_d_128:
11649   case Intrinsic::x86_avx2_phsub_w:
11650   case Intrinsic::x86_avx2_phsub_d: {
11651     unsigned Opcode;
11652     switch (IntNo) {
11653     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11654     case Intrinsic::x86_sse3_hadd_ps:
11655     case Intrinsic::x86_sse3_hadd_pd:
11656     case Intrinsic::x86_avx_hadd_ps_256:
11657     case Intrinsic::x86_avx_hadd_pd_256:
11658       Opcode = X86ISD::FHADD;
11659       break;
11660     case Intrinsic::x86_sse3_hsub_ps:
11661     case Intrinsic::x86_sse3_hsub_pd:
11662     case Intrinsic::x86_avx_hsub_ps_256:
11663     case Intrinsic::x86_avx_hsub_pd_256:
11664       Opcode = X86ISD::FHSUB;
11665       break;
11666     case Intrinsic::x86_ssse3_phadd_w_128:
11667     case Intrinsic::x86_ssse3_phadd_d_128:
11668     case Intrinsic::x86_avx2_phadd_w:
11669     case Intrinsic::x86_avx2_phadd_d:
11670       Opcode = X86ISD::HADD;
11671       break;
11672     case Intrinsic::x86_ssse3_phsub_w_128:
11673     case Intrinsic::x86_ssse3_phsub_d_128:
11674     case Intrinsic::x86_avx2_phsub_w:
11675     case Intrinsic::x86_avx2_phsub_d:
11676       Opcode = X86ISD::HSUB;
11677       break;
11678     }
11679     return DAG.getNode(Opcode, dl, Op.getValueType(),
11680                        Op.getOperand(1), Op.getOperand(2));
11681   }
11682
11683   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11684   case Intrinsic::x86_sse2_pmaxu_b:
11685   case Intrinsic::x86_sse41_pmaxuw:
11686   case Intrinsic::x86_sse41_pmaxud:
11687   case Intrinsic::x86_avx2_pmaxu_b:
11688   case Intrinsic::x86_avx2_pmaxu_w:
11689   case Intrinsic::x86_avx2_pmaxu_d:
11690   case Intrinsic::x86_sse2_pminu_b:
11691   case Intrinsic::x86_sse41_pminuw:
11692   case Intrinsic::x86_sse41_pminud:
11693   case Intrinsic::x86_avx2_pminu_b:
11694   case Intrinsic::x86_avx2_pminu_w:
11695   case Intrinsic::x86_avx2_pminu_d:
11696   case Intrinsic::x86_sse41_pmaxsb:
11697   case Intrinsic::x86_sse2_pmaxs_w:
11698   case Intrinsic::x86_sse41_pmaxsd:
11699   case Intrinsic::x86_avx2_pmaxs_b:
11700   case Intrinsic::x86_avx2_pmaxs_w:
11701   case Intrinsic::x86_avx2_pmaxs_d:
11702   case Intrinsic::x86_sse41_pminsb:
11703   case Intrinsic::x86_sse2_pmins_w:
11704   case Intrinsic::x86_sse41_pminsd:
11705   case Intrinsic::x86_avx2_pmins_b:
11706   case Intrinsic::x86_avx2_pmins_w:
11707   case Intrinsic::x86_avx2_pmins_d: {
11708     unsigned Opcode;
11709     switch (IntNo) {
11710     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11711     case Intrinsic::x86_sse2_pmaxu_b:
11712     case Intrinsic::x86_sse41_pmaxuw:
11713     case Intrinsic::x86_sse41_pmaxud:
11714     case Intrinsic::x86_avx2_pmaxu_b:
11715     case Intrinsic::x86_avx2_pmaxu_w:
11716     case Intrinsic::x86_avx2_pmaxu_d:
11717       Opcode = X86ISD::UMAX;
11718       break;
11719     case Intrinsic::x86_sse2_pminu_b:
11720     case Intrinsic::x86_sse41_pminuw:
11721     case Intrinsic::x86_sse41_pminud:
11722     case Intrinsic::x86_avx2_pminu_b:
11723     case Intrinsic::x86_avx2_pminu_w:
11724     case Intrinsic::x86_avx2_pminu_d:
11725       Opcode = X86ISD::UMIN;
11726       break;
11727     case Intrinsic::x86_sse41_pmaxsb:
11728     case Intrinsic::x86_sse2_pmaxs_w:
11729     case Intrinsic::x86_sse41_pmaxsd:
11730     case Intrinsic::x86_avx2_pmaxs_b:
11731     case Intrinsic::x86_avx2_pmaxs_w:
11732     case Intrinsic::x86_avx2_pmaxs_d:
11733       Opcode = X86ISD::SMAX;
11734       break;
11735     case Intrinsic::x86_sse41_pminsb:
11736     case Intrinsic::x86_sse2_pmins_w:
11737     case Intrinsic::x86_sse41_pminsd:
11738     case Intrinsic::x86_avx2_pmins_b:
11739     case Intrinsic::x86_avx2_pmins_w:
11740     case Intrinsic::x86_avx2_pmins_d:
11741       Opcode = X86ISD::SMIN;
11742       break;
11743     }
11744     return DAG.getNode(Opcode, dl, Op.getValueType(),
11745                        Op.getOperand(1), Op.getOperand(2));
11746   }
11747
11748   // SSE/SSE2/AVX floating point max/min intrinsics.
11749   case Intrinsic::x86_sse_max_ps:
11750   case Intrinsic::x86_sse2_max_pd:
11751   case Intrinsic::x86_avx_max_ps_256:
11752   case Intrinsic::x86_avx_max_pd_256:
11753   case Intrinsic::x86_sse_min_ps:
11754   case Intrinsic::x86_sse2_min_pd:
11755   case Intrinsic::x86_avx_min_ps_256:
11756   case Intrinsic::x86_avx_min_pd_256: {
11757     unsigned Opcode;
11758     switch (IntNo) {
11759     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11760     case Intrinsic::x86_sse_max_ps:
11761     case Intrinsic::x86_sse2_max_pd:
11762     case Intrinsic::x86_avx_max_ps_256:
11763     case Intrinsic::x86_avx_max_pd_256:
11764       Opcode = X86ISD::FMAX;
11765       break;
11766     case Intrinsic::x86_sse_min_ps:
11767     case Intrinsic::x86_sse2_min_pd:
11768     case Intrinsic::x86_avx_min_ps_256:
11769     case Intrinsic::x86_avx_min_pd_256:
11770       Opcode = X86ISD::FMIN;
11771       break;
11772     }
11773     return DAG.getNode(Opcode, dl, Op.getValueType(),
11774                        Op.getOperand(1), Op.getOperand(2));
11775   }
11776
11777   // AVX2 variable shift intrinsics
11778   case Intrinsic::x86_avx2_psllv_d:
11779   case Intrinsic::x86_avx2_psllv_q:
11780   case Intrinsic::x86_avx2_psllv_d_256:
11781   case Intrinsic::x86_avx2_psllv_q_256:
11782   case Intrinsic::x86_avx2_psrlv_d:
11783   case Intrinsic::x86_avx2_psrlv_q:
11784   case Intrinsic::x86_avx2_psrlv_d_256:
11785   case Intrinsic::x86_avx2_psrlv_q_256:
11786   case Intrinsic::x86_avx2_psrav_d:
11787   case Intrinsic::x86_avx2_psrav_d_256: {
11788     unsigned Opcode;
11789     switch (IntNo) {
11790     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11791     case Intrinsic::x86_avx2_psllv_d:
11792     case Intrinsic::x86_avx2_psllv_q:
11793     case Intrinsic::x86_avx2_psllv_d_256:
11794     case Intrinsic::x86_avx2_psllv_q_256:
11795       Opcode = ISD::SHL;
11796       break;
11797     case Intrinsic::x86_avx2_psrlv_d:
11798     case Intrinsic::x86_avx2_psrlv_q:
11799     case Intrinsic::x86_avx2_psrlv_d_256:
11800     case Intrinsic::x86_avx2_psrlv_q_256:
11801       Opcode = ISD::SRL;
11802       break;
11803     case Intrinsic::x86_avx2_psrav_d:
11804     case Intrinsic::x86_avx2_psrav_d_256:
11805       Opcode = ISD::SRA;
11806       break;
11807     }
11808     return DAG.getNode(Opcode, dl, Op.getValueType(),
11809                        Op.getOperand(1), Op.getOperand(2));
11810   }
11811
11812   case Intrinsic::x86_ssse3_pshuf_b_128:
11813   case Intrinsic::x86_avx2_pshuf_b:
11814     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11815                        Op.getOperand(1), Op.getOperand(2));
11816
11817   case Intrinsic::x86_ssse3_psign_b_128:
11818   case Intrinsic::x86_ssse3_psign_w_128:
11819   case Intrinsic::x86_ssse3_psign_d_128:
11820   case Intrinsic::x86_avx2_psign_b:
11821   case Intrinsic::x86_avx2_psign_w:
11822   case Intrinsic::x86_avx2_psign_d:
11823     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11824                        Op.getOperand(1), Op.getOperand(2));
11825
11826   case Intrinsic::x86_sse41_insertps:
11827     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11828                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11829
11830   case Intrinsic::x86_avx_vperm2f128_ps_256:
11831   case Intrinsic::x86_avx_vperm2f128_pd_256:
11832   case Intrinsic::x86_avx_vperm2f128_si_256:
11833   case Intrinsic::x86_avx2_vperm2i128:
11834     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11835                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11836
11837   case Intrinsic::x86_avx2_permd:
11838   case Intrinsic::x86_avx2_permps:
11839     // Operands intentionally swapped. Mask is last operand to intrinsic,
11840     // but second operand for node/instruction.
11841     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11842                        Op.getOperand(2), Op.getOperand(1));
11843
11844   case Intrinsic::x86_sse_sqrt_ps:
11845   case Intrinsic::x86_sse2_sqrt_pd:
11846   case Intrinsic::x86_avx_sqrt_ps_256:
11847   case Intrinsic::x86_avx_sqrt_pd_256:
11848     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11849
11850   // ptest and testp intrinsics. The intrinsic these come from are designed to
11851   // return an integer value, not just an instruction so lower it to the ptest
11852   // or testp pattern and a setcc for the result.
11853   case Intrinsic::x86_sse41_ptestz:
11854   case Intrinsic::x86_sse41_ptestc:
11855   case Intrinsic::x86_sse41_ptestnzc:
11856   case Intrinsic::x86_avx_ptestz_256:
11857   case Intrinsic::x86_avx_ptestc_256:
11858   case Intrinsic::x86_avx_ptestnzc_256:
11859   case Intrinsic::x86_avx_vtestz_ps:
11860   case Intrinsic::x86_avx_vtestc_ps:
11861   case Intrinsic::x86_avx_vtestnzc_ps:
11862   case Intrinsic::x86_avx_vtestz_pd:
11863   case Intrinsic::x86_avx_vtestc_pd:
11864   case Intrinsic::x86_avx_vtestnzc_pd:
11865   case Intrinsic::x86_avx_vtestz_ps_256:
11866   case Intrinsic::x86_avx_vtestc_ps_256:
11867   case Intrinsic::x86_avx_vtestnzc_ps_256:
11868   case Intrinsic::x86_avx_vtestz_pd_256:
11869   case Intrinsic::x86_avx_vtestc_pd_256:
11870   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11871     bool IsTestPacked = false;
11872     unsigned X86CC;
11873     switch (IntNo) {
11874     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11875     case Intrinsic::x86_avx_vtestz_ps:
11876     case Intrinsic::x86_avx_vtestz_pd:
11877     case Intrinsic::x86_avx_vtestz_ps_256:
11878     case Intrinsic::x86_avx_vtestz_pd_256:
11879       IsTestPacked = true; // Fallthrough
11880     case Intrinsic::x86_sse41_ptestz:
11881     case Intrinsic::x86_avx_ptestz_256:
11882       // ZF = 1
11883       X86CC = X86::COND_E;
11884       break;
11885     case Intrinsic::x86_avx_vtestc_ps:
11886     case Intrinsic::x86_avx_vtestc_pd:
11887     case Intrinsic::x86_avx_vtestc_ps_256:
11888     case Intrinsic::x86_avx_vtestc_pd_256:
11889       IsTestPacked = true; // Fallthrough
11890     case Intrinsic::x86_sse41_ptestc:
11891     case Intrinsic::x86_avx_ptestc_256:
11892       // CF = 1
11893       X86CC = X86::COND_B;
11894       break;
11895     case Intrinsic::x86_avx_vtestnzc_ps:
11896     case Intrinsic::x86_avx_vtestnzc_pd:
11897     case Intrinsic::x86_avx_vtestnzc_ps_256:
11898     case Intrinsic::x86_avx_vtestnzc_pd_256:
11899       IsTestPacked = true; // Fallthrough
11900     case Intrinsic::x86_sse41_ptestnzc:
11901     case Intrinsic::x86_avx_ptestnzc_256:
11902       // ZF and CF = 0
11903       X86CC = X86::COND_A;
11904       break;
11905     }
11906
11907     SDValue LHS = Op.getOperand(1);
11908     SDValue RHS = Op.getOperand(2);
11909     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11910     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11911     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11912     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11913     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11914   }
11915   case Intrinsic::x86_avx512_kortestz_w:
11916   case Intrinsic::x86_avx512_kortestc_w: {
11917     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11918     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11919     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11920     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11921     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11922     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11923     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11924   }
11925
11926   // SSE/AVX shift intrinsics
11927   case Intrinsic::x86_sse2_psll_w:
11928   case Intrinsic::x86_sse2_psll_d:
11929   case Intrinsic::x86_sse2_psll_q:
11930   case Intrinsic::x86_avx2_psll_w:
11931   case Intrinsic::x86_avx2_psll_d:
11932   case Intrinsic::x86_avx2_psll_q:
11933   case Intrinsic::x86_sse2_psrl_w:
11934   case Intrinsic::x86_sse2_psrl_d:
11935   case Intrinsic::x86_sse2_psrl_q:
11936   case Intrinsic::x86_avx2_psrl_w:
11937   case Intrinsic::x86_avx2_psrl_d:
11938   case Intrinsic::x86_avx2_psrl_q:
11939   case Intrinsic::x86_sse2_psra_w:
11940   case Intrinsic::x86_sse2_psra_d:
11941   case Intrinsic::x86_avx2_psra_w:
11942   case Intrinsic::x86_avx2_psra_d: {
11943     unsigned Opcode;
11944     switch (IntNo) {
11945     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11946     case Intrinsic::x86_sse2_psll_w:
11947     case Intrinsic::x86_sse2_psll_d:
11948     case Intrinsic::x86_sse2_psll_q:
11949     case Intrinsic::x86_avx2_psll_w:
11950     case Intrinsic::x86_avx2_psll_d:
11951     case Intrinsic::x86_avx2_psll_q:
11952       Opcode = X86ISD::VSHL;
11953       break;
11954     case Intrinsic::x86_sse2_psrl_w:
11955     case Intrinsic::x86_sse2_psrl_d:
11956     case Intrinsic::x86_sse2_psrl_q:
11957     case Intrinsic::x86_avx2_psrl_w:
11958     case Intrinsic::x86_avx2_psrl_d:
11959     case Intrinsic::x86_avx2_psrl_q:
11960       Opcode = X86ISD::VSRL;
11961       break;
11962     case Intrinsic::x86_sse2_psra_w:
11963     case Intrinsic::x86_sse2_psra_d:
11964     case Intrinsic::x86_avx2_psra_w:
11965     case Intrinsic::x86_avx2_psra_d:
11966       Opcode = X86ISD::VSRA;
11967       break;
11968     }
11969     return DAG.getNode(Opcode, dl, Op.getValueType(),
11970                        Op.getOperand(1), Op.getOperand(2));
11971   }
11972
11973   // SSE/AVX immediate shift intrinsics
11974   case Intrinsic::x86_sse2_pslli_w:
11975   case Intrinsic::x86_sse2_pslli_d:
11976   case Intrinsic::x86_sse2_pslli_q:
11977   case Intrinsic::x86_avx2_pslli_w:
11978   case Intrinsic::x86_avx2_pslli_d:
11979   case Intrinsic::x86_avx2_pslli_q:
11980   case Intrinsic::x86_sse2_psrli_w:
11981   case Intrinsic::x86_sse2_psrli_d:
11982   case Intrinsic::x86_sse2_psrli_q:
11983   case Intrinsic::x86_avx2_psrli_w:
11984   case Intrinsic::x86_avx2_psrli_d:
11985   case Intrinsic::x86_avx2_psrli_q:
11986   case Intrinsic::x86_sse2_psrai_w:
11987   case Intrinsic::x86_sse2_psrai_d:
11988   case Intrinsic::x86_avx2_psrai_w:
11989   case Intrinsic::x86_avx2_psrai_d: {
11990     unsigned Opcode;
11991     switch (IntNo) {
11992     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11993     case Intrinsic::x86_sse2_pslli_w:
11994     case Intrinsic::x86_sse2_pslli_d:
11995     case Intrinsic::x86_sse2_pslli_q:
11996     case Intrinsic::x86_avx2_pslli_w:
11997     case Intrinsic::x86_avx2_pslli_d:
11998     case Intrinsic::x86_avx2_pslli_q:
11999       Opcode = X86ISD::VSHLI;
12000       break;
12001     case Intrinsic::x86_sse2_psrli_w:
12002     case Intrinsic::x86_sse2_psrli_d:
12003     case Intrinsic::x86_sse2_psrli_q:
12004     case Intrinsic::x86_avx2_psrli_w:
12005     case Intrinsic::x86_avx2_psrli_d:
12006     case Intrinsic::x86_avx2_psrli_q:
12007       Opcode = X86ISD::VSRLI;
12008       break;
12009     case Intrinsic::x86_sse2_psrai_w:
12010     case Intrinsic::x86_sse2_psrai_d:
12011     case Intrinsic::x86_avx2_psrai_w:
12012     case Intrinsic::x86_avx2_psrai_d:
12013       Opcode = X86ISD::VSRAI;
12014       break;
12015     }
12016     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12017                                Op.getOperand(1), Op.getOperand(2), DAG);
12018   }
12019
12020   case Intrinsic::x86_sse42_pcmpistria128:
12021   case Intrinsic::x86_sse42_pcmpestria128:
12022   case Intrinsic::x86_sse42_pcmpistric128:
12023   case Intrinsic::x86_sse42_pcmpestric128:
12024   case Intrinsic::x86_sse42_pcmpistrio128:
12025   case Intrinsic::x86_sse42_pcmpestrio128:
12026   case Intrinsic::x86_sse42_pcmpistris128:
12027   case Intrinsic::x86_sse42_pcmpestris128:
12028   case Intrinsic::x86_sse42_pcmpistriz128:
12029   case Intrinsic::x86_sse42_pcmpestriz128: {
12030     unsigned Opcode;
12031     unsigned X86CC;
12032     switch (IntNo) {
12033     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12034     case Intrinsic::x86_sse42_pcmpistria128:
12035       Opcode = X86ISD::PCMPISTRI;
12036       X86CC = X86::COND_A;
12037       break;
12038     case Intrinsic::x86_sse42_pcmpestria128:
12039       Opcode = X86ISD::PCMPESTRI;
12040       X86CC = X86::COND_A;
12041       break;
12042     case Intrinsic::x86_sse42_pcmpistric128:
12043       Opcode = X86ISD::PCMPISTRI;
12044       X86CC = X86::COND_B;
12045       break;
12046     case Intrinsic::x86_sse42_pcmpestric128:
12047       Opcode = X86ISD::PCMPESTRI;
12048       X86CC = X86::COND_B;
12049       break;
12050     case Intrinsic::x86_sse42_pcmpistrio128:
12051       Opcode = X86ISD::PCMPISTRI;
12052       X86CC = X86::COND_O;
12053       break;
12054     case Intrinsic::x86_sse42_pcmpestrio128:
12055       Opcode = X86ISD::PCMPESTRI;
12056       X86CC = X86::COND_O;
12057       break;
12058     case Intrinsic::x86_sse42_pcmpistris128:
12059       Opcode = X86ISD::PCMPISTRI;
12060       X86CC = X86::COND_S;
12061       break;
12062     case Intrinsic::x86_sse42_pcmpestris128:
12063       Opcode = X86ISD::PCMPESTRI;
12064       X86CC = X86::COND_S;
12065       break;
12066     case Intrinsic::x86_sse42_pcmpistriz128:
12067       Opcode = X86ISD::PCMPISTRI;
12068       X86CC = X86::COND_E;
12069       break;
12070     case Intrinsic::x86_sse42_pcmpestriz128:
12071       Opcode = X86ISD::PCMPESTRI;
12072       X86CC = X86::COND_E;
12073       break;
12074     }
12075     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12076     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12077     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12078     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12079                                 DAG.getConstant(X86CC, MVT::i8),
12080                                 SDValue(PCMP.getNode(), 1));
12081     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12082   }
12083
12084   case Intrinsic::x86_sse42_pcmpistri128:
12085   case Intrinsic::x86_sse42_pcmpestri128: {
12086     unsigned Opcode;
12087     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12088       Opcode = X86ISD::PCMPISTRI;
12089     else
12090       Opcode = X86ISD::PCMPESTRI;
12091
12092     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12093     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12094     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12095   }
12096   case Intrinsic::x86_fma_vfmadd_ps:
12097   case Intrinsic::x86_fma_vfmadd_pd:
12098   case Intrinsic::x86_fma_vfmsub_ps:
12099   case Intrinsic::x86_fma_vfmsub_pd:
12100   case Intrinsic::x86_fma_vfnmadd_ps:
12101   case Intrinsic::x86_fma_vfnmadd_pd:
12102   case Intrinsic::x86_fma_vfnmsub_ps:
12103   case Intrinsic::x86_fma_vfnmsub_pd:
12104   case Intrinsic::x86_fma_vfmaddsub_ps:
12105   case Intrinsic::x86_fma_vfmaddsub_pd:
12106   case Intrinsic::x86_fma_vfmsubadd_ps:
12107   case Intrinsic::x86_fma_vfmsubadd_pd:
12108   case Intrinsic::x86_fma_vfmadd_ps_256:
12109   case Intrinsic::x86_fma_vfmadd_pd_256:
12110   case Intrinsic::x86_fma_vfmsub_ps_256:
12111   case Intrinsic::x86_fma_vfmsub_pd_256:
12112   case Intrinsic::x86_fma_vfnmadd_ps_256:
12113   case Intrinsic::x86_fma_vfnmadd_pd_256:
12114   case Intrinsic::x86_fma_vfnmsub_ps_256:
12115   case Intrinsic::x86_fma_vfnmsub_pd_256:
12116   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12117   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12118   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12119   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12120   case Intrinsic::x86_fma_vfmadd_ps_512:
12121   case Intrinsic::x86_fma_vfmadd_pd_512:
12122   case Intrinsic::x86_fma_vfmsub_ps_512:
12123   case Intrinsic::x86_fma_vfmsub_pd_512:
12124   case Intrinsic::x86_fma_vfnmadd_ps_512:
12125   case Intrinsic::x86_fma_vfnmadd_pd_512:
12126   case Intrinsic::x86_fma_vfnmsub_ps_512:
12127   case Intrinsic::x86_fma_vfnmsub_pd_512:
12128   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12129   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12130   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12131   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12132     unsigned Opc;
12133     switch (IntNo) {
12134     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12135     case Intrinsic::x86_fma_vfmadd_ps:
12136     case Intrinsic::x86_fma_vfmadd_pd:
12137     case Intrinsic::x86_fma_vfmadd_ps_256:
12138     case Intrinsic::x86_fma_vfmadd_pd_256:
12139     case Intrinsic::x86_fma_vfmadd_ps_512:
12140     case Intrinsic::x86_fma_vfmadd_pd_512:
12141       Opc = X86ISD::FMADD;
12142       break;
12143     case Intrinsic::x86_fma_vfmsub_ps:
12144     case Intrinsic::x86_fma_vfmsub_pd:
12145     case Intrinsic::x86_fma_vfmsub_ps_256:
12146     case Intrinsic::x86_fma_vfmsub_pd_256:
12147     case Intrinsic::x86_fma_vfmsub_ps_512:
12148     case Intrinsic::x86_fma_vfmsub_pd_512:
12149       Opc = X86ISD::FMSUB;
12150       break;
12151     case Intrinsic::x86_fma_vfnmadd_ps:
12152     case Intrinsic::x86_fma_vfnmadd_pd:
12153     case Intrinsic::x86_fma_vfnmadd_ps_256:
12154     case Intrinsic::x86_fma_vfnmadd_pd_256:
12155     case Intrinsic::x86_fma_vfnmadd_ps_512:
12156     case Intrinsic::x86_fma_vfnmadd_pd_512:
12157       Opc = X86ISD::FNMADD;
12158       break;
12159     case Intrinsic::x86_fma_vfnmsub_ps:
12160     case Intrinsic::x86_fma_vfnmsub_pd:
12161     case Intrinsic::x86_fma_vfnmsub_ps_256:
12162     case Intrinsic::x86_fma_vfnmsub_pd_256:
12163     case Intrinsic::x86_fma_vfnmsub_ps_512:
12164     case Intrinsic::x86_fma_vfnmsub_pd_512:
12165       Opc = X86ISD::FNMSUB;
12166       break;
12167     case Intrinsic::x86_fma_vfmaddsub_ps:
12168     case Intrinsic::x86_fma_vfmaddsub_pd:
12169     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12170     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12171     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12172     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12173       Opc = X86ISD::FMADDSUB;
12174       break;
12175     case Intrinsic::x86_fma_vfmsubadd_ps:
12176     case Intrinsic::x86_fma_vfmsubadd_pd:
12177     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12178     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12179     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12180     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12181       Opc = X86ISD::FMSUBADD;
12182       break;
12183     }
12184
12185     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12186                        Op.getOperand(2), Op.getOperand(3));
12187   }
12188   }
12189 }
12190
12191 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12192                              SDValue Base, SDValue Index,
12193                              SDValue ScaleOp, SDValue Chain,
12194                              const X86Subtarget * Subtarget) {
12195   SDLoc dl(Op);
12196   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12197   assert(C && "Invalid scale type");
12198   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12199   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12200   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12201                              Index.getSimpleValueType().getVectorNumElements());
12202   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12203   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12204   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12205   SDValue Segment = DAG.getRegister(0, MVT::i32);
12206   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12207   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12208   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12209   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12210 }
12211
12212 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12213                               SDValue Src, SDValue Mask, SDValue Base,
12214                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12215                               const X86Subtarget * Subtarget) {
12216   SDLoc dl(Op);
12217   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12218   assert(C && "Invalid scale type");
12219   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12220   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12221                              Index.getSimpleValueType().getVectorNumElements());
12222   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12223   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12224   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12225   SDValue Segment = DAG.getRegister(0, MVT::i32);
12226   if (Src.getOpcode() == ISD::UNDEF)
12227     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12228   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12229   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12230   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12231   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12232 }
12233
12234 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12235                               SDValue Src, SDValue Base, SDValue Index,
12236                               SDValue ScaleOp, SDValue Chain) {
12237   SDLoc dl(Op);
12238   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12239   assert(C && "Invalid scale type");
12240   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12241   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12242   SDValue Segment = DAG.getRegister(0, MVT::i32);
12243   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12244                              Index.getSimpleValueType().getVectorNumElements());
12245   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12246   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12247   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12248   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12249   return SDValue(Res, 1);
12250 }
12251
12252 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12253                                SDValue Src, SDValue Mask, SDValue Base,
12254                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12255   SDLoc dl(Op);
12256   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12257   assert(C && "Invalid scale type");
12258   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12259   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12260   SDValue Segment = DAG.getRegister(0, MVT::i32);
12261   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12262                              Index.getSimpleValueType().getVectorNumElements());
12263   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12264   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12265   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12266   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12267   return SDValue(Res, 1);
12268 }
12269
12270 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12271 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12272 // also used to custom lower READCYCLECOUNTER nodes.
12273 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12274                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12275                               SmallVectorImpl<SDValue> &Results) {
12276   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12277   SDValue TheChain = N->getOperand(0);
12278   SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12279   SDValue LO, HI;
12280
12281   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12282   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12283   // and the EAX register is loaded with the low-order 32 bits.
12284   if (Subtarget->is64Bit()) {
12285     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12286     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12287                             LO.getValue(2));
12288   } else {
12289     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12290     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12291                             LO.getValue(2));
12292   }
12293   SDValue Chain = HI.getValue(1);
12294
12295   if (Opcode == X86ISD::RDTSCP_DAG) {
12296     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12297
12298     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12299     // the ECX register. Add 'ecx' explicitly to the chain.
12300     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12301                                      HI.getValue(2));
12302     // Explicitly store the content of ECX at the location passed in input
12303     // to the 'rdtscp' intrinsic.
12304     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12305                          MachinePointerInfo(), false, false, 0);
12306   }
12307
12308   if (Subtarget->is64Bit()) {
12309     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12310     // the EAX register is loaded with the low-order 32 bits.
12311     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12312                               DAG.getConstant(32, MVT::i8));
12313     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12314     Results.push_back(Chain);
12315     return;
12316   }
12317
12318   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12319   SDValue Ops[] = { LO, HI };
12320   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12321                              array_lengthof(Ops));
12322   Results.push_back(Pair);
12323   Results.push_back(Chain);
12324 }
12325
12326 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12327                                      SelectionDAG &DAG) {
12328   SmallVector<SDValue, 2> Results;
12329   SDLoc DL(Op);
12330   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12331                           Results);
12332   return DAG.getMergeValues(&Results[0], Results.size(), DL);
12333 }
12334
12335 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12336                                       SelectionDAG &DAG) {
12337   SDLoc dl(Op);
12338   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12339   switch (IntNo) {
12340   default: return SDValue();    // Don't custom lower most intrinsics.
12341
12342   // RDRAND/RDSEED intrinsics.
12343   case Intrinsic::x86_rdrand_16:
12344   case Intrinsic::x86_rdrand_32:
12345   case Intrinsic::x86_rdrand_64:
12346   case Intrinsic::x86_rdseed_16:
12347   case Intrinsic::x86_rdseed_32:
12348   case Intrinsic::x86_rdseed_64: {
12349     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12350                        IntNo == Intrinsic::x86_rdseed_32 ||
12351                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12352                                                             X86ISD::RDRAND;
12353     // Emit the node with the right value type.
12354     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12355     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12356
12357     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12358     // Otherwise return the value from Rand, which is always 0, casted to i32.
12359     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12360                       DAG.getConstant(1, Op->getValueType(1)),
12361                       DAG.getConstant(X86::COND_B, MVT::i32),
12362                       SDValue(Result.getNode(), 1) };
12363     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12364                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12365                                   Ops, array_lengthof(Ops));
12366
12367     // Return { result, isValid, chain }.
12368     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12369                        SDValue(Result.getNode(), 2));
12370   }
12371   //int_gather(index, base, scale);
12372   case Intrinsic::x86_avx512_gather_qpd_512:
12373   case Intrinsic::x86_avx512_gather_qps_512:
12374   case Intrinsic::x86_avx512_gather_dpd_512:
12375   case Intrinsic::x86_avx512_gather_qpi_512:
12376   case Intrinsic::x86_avx512_gather_qpq_512:
12377   case Intrinsic::x86_avx512_gather_dpq_512:
12378   case Intrinsic::x86_avx512_gather_dps_512:
12379   case Intrinsic::x86_avx512_gather_dpi_512: {
12380     unsigned Opc;
12381     switch (IntNo) {
12382     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12383     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12384     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12385     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12386     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12387     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12388     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12389     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12390     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12391     }
12392     SDValue Chain = Op.getOperand(0);
12393     SDValue Index = Op.getOperand(2);
12394     SDValue Base  = Op.getOperand(3);
12395     SDValue Scale = Op.getOperand(4);
12396     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12397   }
12398   //int_gather_mask(v1, mask, index, base, scale);
12399   case Intrinsic::x86_avx512_gather_qps_mask_512:
12400   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12401   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12402   case Intrinsic::x86_avx512_gather_dps_mask_512:
12403   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12404   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12405   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12406   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12407     unsigned Opc;
12408     switch (IntNo) {
12409     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12410     case Intrinsic::x86_avx512_gather_qps_mask_512:
12411       Opc = X86::VGATHERQPSZrm; break;
12412     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12413       Opc = X86::VGATHERQPDZrm; break;
12414     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12415       Opc = X86::VGATHERDPDZrm; break;
12416     case Intrinsic::x86_avx512_gather_dps_mask_512:
12417       Opc = X86::VGATHERDPSZrm; break;
12418     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12419       Opc = X86::VPGATHERQDZrm; break;
12420     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12421       Opc = X86::VPGATHERQQZrm; break;
12422     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12423       Opc = X86::VPGATHERDDZrm; break;
12424     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12425       Opc = X86::VPGATHERDQZrm; break;
12426     }
12427     SDValue Chain = Op.getOperand(0);
12428     SDValue Src   = Op.getOperand(2);
12429     SDValue Mask  = Op.getOperand(3);
12430     SDValue Index = Op.getOperand(4);
12431     SDValue Base  = Op.getOperand(5);
12432     SDValue Scale = Op.getOperand(6);
12433     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12434                           Subtarget);
12435   }
12436   //int_scatter(base, index, v1, scale);
12437   case Intrinsic::x86_avx512_scatter_qpd_512:
12438   case Intrinsic::x86_avx512_scatter_qps_512:
12439   case Intrinsic::x86_avx512_scatter_dpd_512:
12440   case Intrinsic::x86_avx512_scatter_qpi_512:
12441   case Intrinsic::x86_avx512_scatter_qpq_512:
12442   case Intrinsic::x86_avx512_scatter_dpq_512:
12443   case Intrinsic::x86_avx512_scatter_dps_512:
12444   case Intrinsic::x86_avx512_scatter_dpi_512: {
12445     unsigned Opc;
12446     switch (IntNo) {
12447     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12448     case Intrinsic::x86_avx512_scatter_qpd_512:
12449       Opc = X86::VSCATTERQPDZmr; break;
12450     case Intrinsic::x86_avx512_scatter_qps_512:
12451       Opc = X86::VSCATTERQPSZmr; break;
12452     case Intrinsic::x86_avx512_scatter_dpd_512:
12453       Opc = X86::VSCATTERDPDZmr; break;
12454     case Intrinsic::x86_avx512_scatter_dps_512:
12455       Opc = X86::VSCATTERDPSZmr; break;
12456     case Intrinsic::x86_avx512_scatter_qpi_512:
12457       Opc = X86::VPSCATTERQDZmr; break;
12458     case Intrinsic::x86_avx512_scatter_qpq_512:
12459       Opc = X86::VPSCATTERQQZmr; break;
12460     case Intrinsic::x86_avx512_scatter_dpq_512:
12461       Opc = X86::VPSCATTERDQZmr; break;
12462     case Intrinsic::x86_avx512_scatter_dpi_512:
12463       Opc = X86::VPSCATTERDDZmr; break;
12464     }
12465     SDValue Chain = Op.getOperand(0);
12466     SDValue Base  = Op.getOperand(2);
12467     SDValue Index = Op.getOperand(3);
12468     SDValue Src   = Op.getOperand(4);
12469     SDValue Scale = Op.getOperand(5);
12470     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12471   }
12472   //int_scatter_mask(base, mask, index, v1, scale);
12473   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12474   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12475   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12476   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12477   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12478   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12479   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12480   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12481     unsigned Opc;
12482     switch (IntNo) {
12483     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12484     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12485       Opc = X86::VSCATTERQPDZmr; break;
12486     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12487       Opc = X86::VSCATTERQPSZmr; break;
12488     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12489       Opc = X86::VSCATTERDPDZmr; break;
12490     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12491       Opc = X86::VSCATTERDPSZmr; break;
12492     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12493       Opc = X86::VPSCATTERQDZmr; break;
12494     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12495       Opc = X86::VPSCATTERQQZmr; break;
12496     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12497       Opc = X86::VPSCATTERDQZmr; break;
12498     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12499       Opc = X86::VPSCATTERDDZmr; break;
12500     }
12501     SDValue Chain = Op.getOperand(0);
12502     SDValue Base  = Op.getOperand(2);
12503     SDValue Mask  = Op.getOperand(3);
12504     SDValue Index = Op.getOperand(4);
12505     SDValue Src   = Op.getOperand(5);
12506     SDValue Scale = Op.getOperand(6);
12507     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12508   }
12509   // Read Time Stamp Counter (RDTSC).
12510   case Intrinsic::x86_rdtsc:
12511   // Read Time Stamp Counter and Processor ID (RDTSCP).
12512   case Intrinsic::x86_rdtscp: {
12513     unsigned Opc;
12514     switch (IntNo) {
12515     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12516     case Intrinsic::x86_rdtsc:
12517       Opc = X86ISD::RDTSC_DAG; break;
12518     case Intrinsic::x86_rdtscp:
12519       Opc = X86ISD::RDTSCP_DAG; break;
12520     }
12521     SmallVector<SDValue, 2> Results;
12522     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12523     return DAG.getMergeValues(&Results[0], Results.size(), dl);
12524   }
12525   // XTEST intrinsics.
12526   case Intrinsic::x86_xtest: {
12527     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12528     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12529     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12530                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12531                                 InTrans);
12532     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12533     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12534                        Ret, SDValue(InTrans.getNode(), 1));
12535   }
12536   }
12537 }
12538
12539 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12540                                            SelectionDAG &DAG) const {
12541   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12542   MFI->setReturnAddressIsTaken(true);
12543
12544   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12545     return SDValue();
12546
12547   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12548   SDLoc dl(Op);
12549   EVT PtrVT = getPointerTy();
12550
12551   if (Depth > 0) {
12552     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12553     const X86RegisterInfo *RegInfo =
12554       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12555     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12556     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12557                        DAG.getNode(ISD::ADD, dl, PtrVT,
12558                                    FrameAddr, Offset),
12559                        MachinePointerInfo(), false, false, false, 0);
12560   }
12561
12562   // Just load the return address.
12563   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12564   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12565                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12566 }
12567
12568 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12569   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12570   MFI->setFrameAddressIsTaken(true);
12571
12572   EVT VT = Op.getValueType();
12573   SDLoc dl(Op);  // FIXME probably not meaningful
12574   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12575   const X86RegisterInfo *RegInfo =
12576     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12577   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12578   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12579           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12580          "Invalid Frame Register!");
12581   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12582   while (Depth--)
12583     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12584                             MachinePointerInfo(),
12585                             false, false, false, 0);
12586   return FrameAddr;
12587 }
12588
12589 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12590                                                      SelectionDAG &DAG) const {
12591   const X86RegisterInfo *RegInfo =
12592     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12593   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12594 }
12595
12596 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12597   SDValue Chain     = Op.getOperand(0);
12598   SDValue Offset    = Op.getOperand(1);
12599   SDValue Handler   = Op.getOperand(2);
12600   SDLoc dl      (Op);
12601
12602   EVT PtrVT = getPointerTy();
12603   const X86RegisterInfo *RegInfo =
12604     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12605   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12606   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12607           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12608          "Invalid Frame Register!");
12609   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12610   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12611
12612   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12613                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12614   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12615   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12616                        false, false, 0);
12617   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12618
12619   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12620                      DAG.getRegister(StoreAddrReg, PtrVT));
12621 }
12622
12623 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12624                                                SelectionDAG &DAG) const {
12625   SDLoc DL(Op);
12626   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12627                      DAG.getVTList(MVT::i32, MVT::Other),
12628                      Op.getOperand(0), Op.getOperand(1));
12629 }
12630
12631 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12632                                                 SelectionDAG &DAG) const {
12633   SDLoc DL(Op);
12634   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12635                      Op.getOperand(0), Op.getOperand(1));
12636 }
12637
12638 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12639   return Op.getOperand(0);
12640 }
12641
12642 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12643                                                 SelectionDAG &DAG) const {
12644   SDValue Root = Op.getOperand(0);
12645   SDValue Trmp = Op.getOperand(1); // trampoline
12646   SDValue FPtr = Op.getOperand(2); // nested function
12647   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12648   SDLoc dl (Op);
12649
12650   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12651   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12652
12653   if (Subtarget->is64Bit()) {
12654     SDValue OutChains[6];
12655
12656     // Large code-model.
12657     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12658     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12659
12660     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12661     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12662
12663     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12664
12665     // Load the pointer to the nested function into R11.
12666     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12667     SDValue Addr = Trmp;
12668     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12669                                 Addr, MachinePointerInfo(TrmpAddr),
12670                                 false, false, 0);
12671
12672     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12673                        DAG.getConstant(2, MVT::i64));
12674     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12675                                 MachinePointerInfo(TrmpAddr, 2),
12676                                 false, false, 2);
12677
12678     // Load the 'nest' parameter value into R10.
12679     // R10 is specified in X86CallingConv.td
12680     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12681     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12682                        DAG.getConstant(10, MVT::i64));
12683     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12684                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12685                                 false, false, 0);
12686
12687     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12688                        DAG.getConstant(12, MVT::i64));
12689     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12690                                 MachinePointerInfo(TrmpAddr, 12),
12691                                 false, false, 2);
12692
12693     // Jump to the nested function.
12694     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12695     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12696                        DAG.getConstant(20, MVT::i64));
12697     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12698                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12699                                 false, false, 0);
12700
12701     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12702     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12703                        DAG.getConstant(22, MVT::i64));
12704     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12705                                 MachinePointerInfo(TrmpAddr, 22),
12706                                 false, false, 0);
12707
12708     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12709   } else {
12710     const Function *Func =
12711       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12712     CallingConv::ID CC = Func->getCallingConv();
12713     unsigned NestReg;
12714
12715     switch (CC) {
12716     default:
12717       llvm_unreachable("Unsupported calling convention");
12718     case CallingConv::C:
12719     case CallingConv::X86_StdCall: {
12720       // Pass 'nest' parameter in ECX.
12721       // Must be kept in sync with X86CallingConv.td
12722       NestReg = X86::ECX;
12723
12724       // Check that ECX wasn't needed by an 'inreg' parameter.
12725       FunctionType *FTy = Func->getFunctionType();
12726       const AttributeSet &Attrs = Func->getAttributes();
12727
12728       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12729         unsigned InRegCount = 0;
12730         unsigned Idx = 1;
12731
12732         for (FunctionType::param_iterator I = FTy->param_begin(),
12733              E = FTy->param_end(); I != E; ++I, ++Idx)
12734           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12735             // FIXME: should only count parameters that are lowered to integers.
12736             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12737
12738         if (InRegCount > 2) {
12739           report_fatal_error("Nest register in use - reduce number of inreg"
12740                              " parameters!");
12741         }
12742       }
12743       break;
12744     }
12745     case CallingConv::X86_FastCall:
12746     case CallingConv::X86_ThisCall:
12747     case CallingConv::Fast:
12748       // Pass 'nest' parameter in EAX.
12749       // Must be kept in sync with X86CallingConv.td
12750       NestReg = X86::EAX;
12751       break;
12752     }
12753
12754     SDValue OutChains[4];
12755     SDValue Addr, Disp;
12756
12757     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12758                        DAG.getConstant(10, MVT::i32));
12759     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12760
12761     // This is storing the opcode for MOV32ri.
12762     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12763     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12764     OutChains[0] = DAG.getStore(Root, dl,
12765                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12766                                 Trmp, MachinePointerInfo(TrmpAddr),
12767                                 false, false, 0);
12768
12769     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12770                        DAG.getConstant(1, MVT::i32));
12771     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12772                                 MachinePointerInfo(TrmpAddr, 1),
12773                                 false, false, 1);
12774
12775     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12776     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12777                        DAG.getConstant(5, MVT::i32));
12778     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12779                                 MachinePointerInfo(TrmpAddr, 5),
12780                                 false, false, 1);
12781
12782     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12783                        DAG.getConstant(6, MVT::i32));
12784     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12785                                 MachinePointerInfo(TrmpAddr, 6),
12786                                 false, false, 1);
12787
12788     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12789   }
12790 }
12791
12792 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12793                                             SelectionDAG &DAG) const {
12794   /*
12795    The rounding mode is in bits 11:10 of FPSR, and has the following
12796    settings:
12797      00 Round to nearest
12798      01 Round to -inf
12799      10 Round to +inf
12800      11 Round to 0
12801
12802   FLT_ROUNDS, on the other hand, expects the following:
12803     -1 Undefined
12804      0 Round to 0
12805      1 Round to nearest
12806      2 Round to +inf
12807      3 Round to -inf
12808
12809   To perform the conversion, we do:
12810     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12811   */
12812
12813   MachineFunction &MF = DAG.getMachineFunction();
12814   const TargetMachine &TM = MF.getTarget();
12815   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12816   unsigned StackAlignment = TFI.getStackAlignment();
12817   MVT VT = Op.getSimpleValueType();
12818   SDLoc DL(Op);
12819
12820   // Save FP Control Word to stack slot
12821   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12822   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12823
12824   MachineMemOperand *MMO =
12825    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12826                            MachineMemOperand::MOStore, 2, 2);
12827
12828   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12829   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12830                                           DAG.getVTList(MVT::Other),
12831                                           Ops, array_lengthof(Ops), MVT::i16,
12832                                           MMO);
12833
12834   // Load FP Control Word from stack slot
12835   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12836                             MachinePointerInfo(), false, false, false, 0);
12837
12838   // Transform as necessary
12839   SDValue CWD1 =
12840     DAG.getNode(ISD::SRL, DL, MVT::i16,
12841                 DAG.getNode(ISD::AND, DL, MVT::i16,
12842                             CWD, DAG.getConstant(0x800, MVT::i16)),
12843                 DAG.getConstant(11, MVT::i8));
12844   SDValue CWD2 =
12845     DAG.getNode(ISD::SRL, DL, MVT::i16,
12846                 DAG.getNode(ISD::AND, DL, MVT::i16,
12847                             CWD, DAG.getConstant(0x400, MVT::i16)),
12848                 DAG.getConstant(9, MVT::i8));
12849
12850   SDValue RetVal =
12851     DAG.getNode(ISD::AND, DL, MVT::i16,
12852                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12853                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12854                             DAG.getConstant(1, MVT::i16)),
12855                 DAG.getConstant(3, MVT::i16));
12856
12857   return DAG.getNode((VT.getSizeInBits() < 16 ?
12858                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12859 }
12860
12861 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12862   MVT VT = Op.getSimpleValueType();
12863   EVT OpVT = VT;
12864   unsigned NumBits = VT.getSizeInBits();
12865   SDLoc dl(Op);
12866
12867   Op = Op.getOperand(0);
12868   if (VT == MVT::i8) {
12869     // Zero extend to i32 since there is not an i8 bsr.
12870     OpVT = MVT::i32;
12871     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12872   }
12873
12874   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12875   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12876   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12877
12878   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12879   SDValue Ops[] = {
12880     Op,
12881     DAG.getConstant(NumBits+NumBits-1, OpVT),
12882     DAG.getConstant(X86::COND_E, MVT::i8),
12883     Op.getValue(1)
12884   };
12885   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12886
12887   // Finally xor with NumBits-1.
12888   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12889
12890   if (VT == MVT::i8)
12891     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12892   return Op;
12893 }
12894
12895 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12896   MVT VT = Op.getSimpleValueType();
12897   EVT OpVT = VT;
12898   unsigned NumBits = VT.getSizeInBits();
12899   SDLoc dl(Op);
12900
12901   Op = Op.getOperand(0);
12902   if (VT == MVT::i8) {
12903     // Zero extend to i32 since there is not an i8 bsr.
12904     OpVT = MVT::i32;
12905     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12906   }
12907
12908   // Issue a bsr (scan bits in reverse).
12909   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12910   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12911
12912   // And xor with NumBits-1.
12913   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12914
12915   if (VT == MVT::i8)
12916     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12917   return Op;
12918 }
12919
12920 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12921   MVT VT = Op.getSimpleValueType();
12922   unsigned NumBits = VT.getSizeInBits();
12923   SDLoc dl(Op);
12924   Op = Op.getOperand(0);
12925
12926   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12927   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12928   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12929
12930   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12931   SDValue Ops[] = {
12932     Op,
12933     DAG.getConstant(NumBits, VT),
12934     DAG.getConstant(X86::COND_E, MVT::i8),
12935     Op.getValue(1)
12936   };
12937   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12938 }
12939
12940 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12941 // ones, and then concatenate the result back.
12942 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12943   MVT VT = Op.getSimpleValueType();
12944
12945   assert(VT.is256BitVector() && VT.isInteger() &&
12946          "Unsupported value type for operation");
12947
12948   unsigned NumElems = VT.getVectorNumElements();
12949   SDLoc dl(Op);
12950
12951   // Extract the LHS vectors
12952   SDValue LHS = Op.getOperand(0);
12953   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12954   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12955
12956   // Extract the RHS vectors
12957   SDValue RHS = Op.getOperand(1);
12958   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12959   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12960
12961   MVT EltVT = VT.getVectorElementType();
12962   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12963
12964   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12965                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12966                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12967 }
12968
12969 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12970   assert(Op.getSimpleValueType().is256BitVector() &&
12971          Op.getSimpleValueType().isInteger() &&
12972          "Only handle AVX 256-bit vector integer operation");
12973   return Lower256IntArith(Op, DAG);
12974 }
12975
12976 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12977   assert(Op.getSimpleValueType().is256BitVector() &&
12978          Op.getSimpleValueType().isInteger() &&
12979          "Only handle AVX 256-bit vector integer operation");
12980   return Lower256IntArith(Op, DAG);
12981 }
12982
12983 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12984                         SelectionDAG &DAG) {
12985   SDLoc dl(Op);
12986   MVT VT = Op.getSimpleValueType();
12987
12988   // Decompose 256-bit ops into smaller 128-bit ops.
12989   if (VT.is256BitVector() && !Subtarget->hasInt256())
12990     return Lower256IntArith(Op, DAG);
12991
12992   SDValue A = Op.getOperand(0);
12993   SDValue B = Op.getOperand(1);
12994
12995   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12996   if (VT == MVT::v4i32) {
12997     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12998            "Should not custom lower when pmuldq is available!");
12999
13000     // Extract the odd parts.
13001     static const int UnpackMask[] = { 1, -1, 3, -1 };
13002     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13003     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13004
13005     // Multiply the even parts.
13006     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13007     // Now multiply odd parts.
13008     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13009
13010     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13011     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13012
13013     // Merge the two vectors back together with a shuffle. This expands into 2
13014     // shuffles.
13015     static const int ShufMask[] = { 0, 4, 2, 6 };
13016     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13017   }
13018
13019   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13020          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13021
13022   //  Ahi = psrlqi(a, 32);
13023   //  Bhi = psrlqi(b, 32);
13024   //
13025   //  AloBlo = pmuludq(a, b);
13026   //  AloBhi = pmuludq(a, Bhi);
13027   //  AhiBlo = pmuludq(Ahi, b);
13028
13029   //  AloBhi = psllqi(AloBhi, 32);
13030   //  AhiBlo = psllqi(AhiBlo, 32);
13031   //  return AloBlo + AloBhi + AhiBlo;
13032
13033   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13034   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13035
13036   // Bit cast to 32-bit vectors for MULUDQ
13037   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13038                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13039   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13040   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13041   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13042   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13043
13044   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13045   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13046   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13047
13048   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13049   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13050
13051   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13052   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13053 }
13054
13055 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
13056   MVT VT = Op.getSimpleValueType();
13057   MVT EltTy = VT.getVectorElementType();
13058   unsigned NumElts = VT.getVectorNumElements();
13059   SDValue N0 = Op.getOperand(0);
13060   SDLoc dl(Op);
13061
13062   // Lower sdiv X, pow2-const.
13063   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
13064   if (!C)
13065     return SDValue();
13066
13067   APInt SplatValue, SplatUndef;
13068   unsigned SplatBitSize;
13069   bool HasAnyUndefs;
13070   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
13071                           HasAnyUndefs) ||
13072       EltTy.getSizeInBits() < SplatBitSize)
13073     return SDValue();
13074
13075   if ((SplatValue != 0) &&
13076       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
13077     unsigned Lg2 = SplatValue.countTrailingZeros();
13078     // Splat the sign bit.
13079     SmallVector<SDValue, 16> Sz(NumElts,
13080                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
13081                                                 EltTy));
13082     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
13083                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
13084                                           NumElts));
13085     // Add (N0 < 0) ? abs2 - 1 : 0;
13086     SmallVector<SDValue, 16> Amt(NumElts,
13087                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
13088                                                  EltTy));
13089     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
13090                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
13091                                           NumElts));
13092     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
13093     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
13094     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
13095                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
13096                                           NumElts));
13097
13098     // If we're dividing by a positive value, we're done.  Otherwise, we must
13099     // negate the result.
13100     if (SplatValue.isNonNegative())
13101       return SRA;
13102
13103     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
13104     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
13105     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13106   }
13107   return SDValue();
13108 }
13109
13110 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13111                                          const X86Subtarget *Subtarget) {
13112   MVT VT = Op.getSimpleValueType();
13113   SDLoc dl(Op);
13114   SDValue R = Op.getOperand(0);
13115   SDValue Amt = Op.getOperand(1);
13116
13117   // Optimize shl/srl/sra with constant shift amount.
13118   if (isSplatVector(Amt.getNode())) {
13119     SDValue SclrAmt = Amt->getOperand(0);
13120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13121       uint64_t ShiftAmt = C->getZExtValue();
13122
13123       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13124           (Subtarget->hasInt256() &&
13125            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13126           (Subtarget->hasAVX512() &&
13127            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13128         if (Op.getOpcode() == ISD::SHL)
13129           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13130                                             DAG);
13131         if (Op.getOpcode() == ISD::SRL)
13132           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13133                                             DAG);
13134         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13135           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13136                                             DAG);
13137       }
13138
13139       if (VT == MVT::v16i8) {
13140         if (Op.getOpcode() == ISD::SHL) {
13141           // Make a large shift.
13142           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13143                                                    MVT::v8i16, R, ShiftAmt,
13144                                                    DAG);
13145           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13146           // Zero out the rightmost bits.
13147           SmallVector<SDValue, 16> V(16,
13148                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13149                                                      MVT::i8));
13150           return DAG.getNode(ISD::AND, dl, VT, SHL,
13151                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13152         }
13153         if (Op.getOpcode() == ISD::SRL) {
13154           // Make a large shift.
13155           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13156                                                    MVT::v8i16, R, ShiftAmt,
13157                                                    DAG);
13158           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13159           // Zero out the leftmost bits.
13160           SmallVector<SDValue, 16> V(16,
13161                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13162                                                      MVT::i8));
13163           return DAG.getNode(ISD::AND, dl, VT, SRL,
13164                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13165         }
13166         if (Op.getOpcode() == ISD::SRA) {
13167           if (ShiftAmt == 7) {
13168             // R s>> 7  ===  R s< 0
13169             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13170             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13171           }
13172
13173           // R s>> a === ((R u>> a) ^ m) - m
13174           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13175           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13176                                                          MVT::i8));
13177           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13178           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13179           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13180           return Res;
13181         }
13182         llvm_unreachable("Unknown shift opcode.");
13183       }
13184
13185       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13186         if (Op.getOpcode() == ISD::SHL) {
13187           // Make a large shift.
13188           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13189                                                    MVT::v16i16, R, ShiftAmt,
13190                                                    DAG);
13191           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13192           // Zero out the rightmost bits.
13193           SmallVector<SDValue, 32> V(32,
13194                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13195                                                      MVT::i8));
13196           return DAG.getNode(ISD::AND, dl, VT, SHL,
13197                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13198         }
13199         if (Op.getOpcode() == ISD::SRL) {
13200           // Make a large shift.
13201           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13202                                                    MVT::v16i16, R, ShiftAmt,
13203                                                    DAG);
13204           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13205           // Zero out the leftmost bits.
13206           SmallVector<SDValue, 32> V(32,
13207                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13208                                                      MVT::i8));
13209           return DAG.getNode(ISD::AND, dl, VT, SRL,
13210                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13211         }
13212         if (Op.getOpcode() == ISD::SRA) {
13213           if (ShiftAmt == 7) {
13214             // R s>> 7  ===  R s< 0
13215             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13216             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13217           }
13218
13219           // R s>> a === ((R u>> a) ^ m) - m
13220           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13221           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13222                                                          MVT::i8));
13223           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13224           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13225           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13226           return Res;
13227         }
13228         llvm_unreachable("Unknown shift opcode.");
13229       }
13230     }
13231   }
13232
13233   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13234   if (!Subtarget->is64Bit() &&
13235       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13236       Amt.getOpcode() == ISD::BITCAST &&
13237       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13238     Amt = Amt.getOperand(0);
13239     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13240                      VT.getVectorNumElements();
13241     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13242     uint64_t ShiftAmt = 0;
13243     for (unsigned i = 0; i != Ratio; ++i) {
13244       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13245       if (C == 0)
13246         return SDValue();
13247       // 6 == Log2(64)
13248       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13249     }
13250     // Check remaining shift amounts.
13251     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13252       uint64_t ShAmt = 0;
13253       for (unsigned j = 0; j != Ratio; ++j) {
13254         ConstantSDNode *C =
13255           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13256         if (C == 0)
13257           return SDValue();
13258         // 6 == Log2(64)
13259         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13260       }
13261       if (ShAmt != ShiftAmt)
13262         return SDValue();
13263     }
13264     switch (Op.getOpcode()) {
13265     default:
13266       llvm_unreachable("Unknown shift opcode!");
13267     case ISD::SHL:
13268       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13269                                         DAG);
13270     case ISD::SRL:
13271       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13272                                         DAG);
13273     case ISD::SRA:
13274       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13275                                         DAG);
13276     }
13277   }
13278
13279   return SDValue();
13280 }
13281
13282 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13283                                         const X86Subtarget* Subtarget) {
13284   MVT VT = Op.getSimpleValueType();
13285   SDLoc dl(Op);
13286   SDValue R = Op.getOperand(0);
13287   SDValue Amt = Op.getOperand(1);
13288
13289   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13290       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13291       (Subtarget->hasInt256() &&
13292        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13293         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13294        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13295     SDValue BaseShAmt;
13296     EVT EltVT = VT.getVectorElementType();
13297
13298     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13299       unsigned NumElts = VT.getVectorNumElements();
13300       unsigned i, j;
13301       for (i = 0; i != NumElts; ++i) {
13302         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13303           continue;
13304         break;
13305       }
13306       for (j = i; j != NumElts; ++j) {
13307         SDValue Arg = Amt.getOperand(j);
13308         if (Arg.getOpcode() == ISD::UNDEF) continue;
13309         if (Arg != Amt.getOperand(i))
13310           break;
13311       }
13312       if (i != NumElts && j == NumElts)
13313         BaseShAmt = Amt.getOperand(i);
13314     } else {
13315       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13316         Amt = Amt.getOperand(0);
13317       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13318                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13319         SDValue InVec = Amt.getOperand(0);
13320         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13321           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13322           unsigned i = 0;
13323           for (; i != NumElts; ++i) {
13324             SDValue Arg = InVec.getOperand(i);
13325             if (Arg.getOpcode() == ISD::UNDEF) continue;
13326             BaseShAmt = Arg;
13327             break;
13328           }
13329         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13330            if (ConstantSDNode *C =
13331                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13332              unsigned SplatIdx =
13333                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13334              if (C->getZExtValue() == SplatIdx)
13335                BaseShAmt = InVec.getOperand(1);
13336            }
13337         }
13338         if (BaseShAmt.getNode() == 0)
13339           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13340                                   DAG.getIntPtrConstant(0));
13341       }
13342     }
13343
13344     if (BaseShAmt.getNode()) {
13345       if (EltVT.bitsGT(MVT::i32))
13346         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13347       else if (EltVT.bitsLT(MVT::i32))
13348         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13349
13350       switch (Op.getOpcode()) {
13351       default:
13352         llvm_unreachable("Unknown shift opcode!");
13353       case ISD::SHL:
13354         switch (VT.SimpleTy) {
13355         default: return SDValue();
13356         case MVT::v2i64:
13357         case MVT::v4i32:
13358         case MVT::v8i16:
13359         case MVT::v4i64:
13360         case MVT::v8i32:
13361         case MVT::v16i16:
13362         case MVT::v16i32:
13363         case MVT::v8i64:
13364           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13365         }
13366       case ISD::SRA:
13367         switch (VT.SimpleTy) {
13368         default: return SDValue();
13369         case MVT::v4i32:
13370         case MVT::v8i16:
13371         case MVT::v8i32:
13372         case MVT::v16i16:
13373         case MVT::v16i32:
13374         case MVT::v8i64:
13375           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13376         }
13377       case ISD::SRL:
13378         switch (VT.SimpleTy) {
13379         default: return SDValue();
13380         case MVT::v2i64:
13381         case MVT::v4i32:
13382         case MVT::v8i16:
13383         case MVT::v4i64:
13384         case MVT::v8i32:
13385         case MVT::v16i16:
13386         case MVT::v16i32:
13387         case MVT::v8i64:
13388           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13389         }
13390       }
13391     }
13392   }
13393
13394   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13395   if (!Subtarget->is64Bit() &&
13396       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13397       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13398       Amt.getOpcode() == ISD::BITCAST &&
13399       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13400     Amt = Amt.getOperand(0);
13401     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13402                      VT.getVectorNumElements();
13403     std::vector<SDValue> Vals(Ratio);
13404     for (unsigned i = 0; i != Ratio; ++i)
13405       Vals[i] = Amt.getOperand(i);
13406     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13407       for (unsigned j = 0; j != Ratio; ++j)
13408         if (Vals[j] != Amt.getOperand(i + j))
13409           return SDValue();
13410     }
13411     switch (Op.getOpcode()) {
13412     default:
13413       llvm_unreachable("Unknown shift opcode!");
13414     case ISD::SHL:
13415       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13416     case ISD::SRL:
13417       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13418     case ISD::SRA:
13419       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13420     }
13421   }
13422
13423   return SDValue();
13424 }
13425
13426 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13427                           SelectionDAG &DAG) {
13428
13429   MVT VT = Op.getSimpleValueType();
13430   SDLoc dl(Op);
13431   SDValue R = Op.getOperand(0);
13432   SDValue Amt = Op.getOperand(1);
13433   SDValue V;
13434
13435   if (!Subtarget->hasSSE2())
13436     return SDValue();
13437
13438   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13439   if (V.getNode())
13440     return V;
13441
13442   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13443   if (V.getNode())
13444       return V;
13445
13446   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13447     return Op;
13448   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13449   if (Subtarget->hasInt256()) {
13450     if (Op.getOpcode() == ISD::SRL &&
13451         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13452          VT == MVT::v4i64 || VT == MVT::v8i32))
13453       return Op;
13454     if (Op.getOpcode() == ISD::SHL &&
13455         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13456          VT == MVT::v4i64 || VT == MVT::v8i32))
13457       return Op;
13458     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13459       return Op;
13460   }
13461
13462   // If possible, lower this packed shift into a vector multiply instead of
13463   // expanding it into a sequence of scalar shifts.
13464   // Do this only if the vector shift count is a constant build_vector.
13465   if (Op.getOpcode() == ISD::SHL && 
13466       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13467        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13468       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13469     SmallVector<SDValue, 8> Elts;
13470     EVT SVT = VT.getScalarType();
13471     unsigned SVTBits = SVT.getSizeInBits();
13472     const APInt &One = APInt(SVTBits, 1);
13473     unsigned NumElems = VT.getVectorNumElements();
13474
13475     for (unsigned i=0; i !=NumElems; ++i) {
13476       SDValue Op = Amt->getOperand(i);
13477       if (Op->getOpcode() == ISD::UNDEF) {
13478         Elts.push_back(Op);
13479         continue;
13480       }
13481
13482       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13483       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13484       uint64_t ShAmt = C.getZExtValue();
13485       if (ShAmt >= SVTBits) {
13486         Elts.push_back(DAG.getUNDEF(SVT));
13487         continue;
13488       }
13489       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13490     }
13491     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13492     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13493   }
13494
13495   // Lower SHL with variable shift amount.
13496   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13497     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13498
13499     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13500     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13501     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13502     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13503   }
13504
13505   // If possible, lower this shift as a sequence of two shifts by
13506   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13507   // Example:
13508   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13509   //
13510   // Could be rewritten as:
13511   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13512   //
13513   // The advantage is that the two shifts from the example would be
13514   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13515   // the vector shift into four scalar shifts plus four pairs of vector
13516   // insert/extract.
13517   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13518       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13519     unsigned TargetOpcode = X86ISD::MOVSS;
13520     bool CanBeSimplified;
13521     // The splat value for the first packed shift (the 'X' from the example).
13522     SDValue Amt1 = Amt->getOperand(0);
13523     // The splat value for the second packed shift (the 'Y' from the example).
13524     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13525                                         Amt->getOperand(2);
13526
13527     // See if it is possible to replace this node with a sequence of
13528     // two shifts followed by a MOVSS/MOVSD
13529     if (VT == MVT::v4i32) {
13530       // Check if it is legal to use a MOVSS.
13531       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13532                         Amt2 == Amt->getOperand(3);
13533       if (!CanBeSimplified) {
13534         // Otherwise, check if we can still simplify this node using a MOVSD.
13535         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13536                           Amt->getOperand(2) == Amt->getOperand(3);
13537         TargetOpcode = X86ISD::MOVSD;
13538         Amt2 = Amt->getOperand(2);
13539       }
13540     } else {
13541       // Do similar checks for the case where the machine value type
13542       // is MVT::v8i16.
13543       CanBeSimplified = Amt1 == Amt->getOperand(1);
13544       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13545         CanBeSimplified = Amt2 == Amt->getOperand(i);
13546
13547       if (!CanBeSimplified) {
13548         TargetOpcode = X86ISD::MOVSD;
13549         CanBeSimplified = true;
13550         Amt2 = Amt->getOperand(4);
13551         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13552           CanBeSimplified = Amt1 == Amt->getOperand(i);
13553         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13554           CanBeSimplified = Amt2 == Amt->getOperand(j);
13555       }
13556     }
13557     
13558     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13559         isa<ConstantSDNode>(Amt2)) {
13560       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13561       EVT CastVT = MVT::v4i32;
13562       SDValue Splat1 = 
13563         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13564       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13565       SDValue Splat2 = 
13566         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13567       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13568       if (TargetOpcode == X86ISD::MOVSD)
13569         CastVT = MVT::v2i64;
13570       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13571       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13572       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13573                                             BitCast1, DAG);
13574       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13575     }
13576   }
13577
13578   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13579     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13580
13581     // a = a << 5;
13582     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13583     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13584
13585     // Turn 'a' into a mask suitable for VSELECT
13586     SDValue VSelM = DAG.getConstant(0x80, VT);
13587     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13588     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13589
13590     SDValue CM1 = DAG.getConstant(0x0f, VT);
13591     SDValue CM2 = DAG.getConstant(0x3f, VT);
13592
13593     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13594     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13595     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13596     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13597     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13598
13599     // a += a
13600     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13601     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13602     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13603
13604     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13605     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13606     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13607     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13608     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13609
13610     // a += a
13611     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13612     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13613     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13614
13615     // return VSELECT(r, r+r, a);
13616     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13617                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13618     return R;
13619   }
13620
13621   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13622   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13623   // solution better.
13624   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13625     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13626     unsigned ExtOpc =
13627         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13628     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13629     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13630     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13631                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13632     }
13633
13634   // Decompose 256-bit shifts into smaller 128-bit shifts.
13635   if (VT.is256BitVector()) {
13636     unsigned NumElems = VT.getVectorNumElements();
13637     MVT EltVT = VT.getVectorElementType();
13638     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13639
13640     // Extract the two vectors
13641     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13642     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13643
13644     // Recreate the shift amount vectors
13645     SDValue Amt1, Amt2;
13646     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13647       // Constant shift amount
13648       SmallVector<SDValue, 4> Amt1Csts;
13649       SmallVector<SDValue, 4> Amt2Csts;
13650       for (unsigned i = 0; i != NumElems/2; ++i)
13651         Amt1Csts.push_back(Amt->getOperand(i));
13652       for (unsigned i = NumElems/2; i != NumElems; ++i)
13653         Amt2Csts.push_back(Amt->getOperand(i));
13654
13655       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13656                                  &Amt1Csts[0], NumElems/2);
13657       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13658                                  &Amt2Csts[0], NumElems/2);
13659     } else {
13660       // Variable shift amount
13661       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13662       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13663     }
13664
13665     // Issue new vector shifts for the smaller types
13666     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13667     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13668
13669     // Concatenate the result back
13670     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13671   }
13672
13673   return SDValue();
13674 }
13675
13676 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13677   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13678   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13679   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13680   // has only one use.
13681   SDNode *N = Op.getNode();
13682   SDValue LHS = N->getOperand(0);
13683   SDValue RHS = N->getOperand(1);
13684   unsigned BaseOp = 0;
13685   unsigned Cond = 0;
13686   SDLoc DL(Op);
13687   switch (Op.getOpcode()) {
13688   default: llvm_unreachable("Unknown ovf instruction!");
13689   case ISD::SADDO:
13690     // A subtract of one will be selected as a INC. Note that INC doesn't
13691     // set CF, so we can't do this for UADDO.
13692     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13693       if (C->isOne()) {
13694         BaseOp = X86ISD::INC;
13695         Cond = X86::COND_O;
13696         break;
13697       }
13698     BaseOp = X86ISD::ADD;
13699     Cond = X86::COND_O;
13700     break;
13701   case ISD::UADDO:
13702     BaseOp = X86ISD::ADD;
13703     Cond = X86::COND_B;
13704     break;
13705   case ISD::SSUBO:
13706     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13707     // set CF, so we can't do this for USUBO.
13708     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13709       if (C->isOne()) {
13710         BaseOp = X86ISD::DEC;
13711         Cond = X86::COND_O;
13712         break;
13713       }
13714     BaseOp = X86ISD::SUB;
13715     Cond = X86::COND_O;
13716     break;
13717   case ISD::USUBO:
13718     BaseOp = X86ISD::SUB;
13719     Cond = X86::COND_B;
13720     break;
13721   case ISD::SMULO:
13722     BaseOp = X86ISD::SMUL;
13723     Cond = X86::COND_O;
13724     break;
13725   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13726     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13727                                  MVT::i32);
13728     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13729
13730     SDValue SetCC =
13731       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13732                   DAG.getConstant(X86::COND_O, MVT::i32),
13733                   SDValue(Sum.getNode(), 2));
13734
13735     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13736   }
13737   }
13738
13739   // Also sets EFLAGS.
13740   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13741   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13742
13743   SDValue SetCC =
13744     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13745                 DAG.getConstant(Cond, MVT::i32),
13746                 SDValue(Sum.getNode(), 1));
13747
13748   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13749 }
13750
13751 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13752                                                   SelectionDAG &DAG) const {
13753   SDLoc dl(Op);
13754   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13755   MVT VT = Op.getSimpleValueType();
13756
13757   if (!Subtarget->hasSSE2() || !VT.isVector())
13758     return SDValue();
13759
13760   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13761                       ExtraVT.getScalarType().getSizeInBits();
13762
13763   switch (VT.SimpleTy) {
13764     default: return SDValue();
13765     case MVT::v8i32:
13766     case MVT::v16i16:
13767       if (!Subtarget->hasFp256())
13768         return SDValue();
13769       if (!Subtarget->hasInt256()) {
13770         // needs to be split
13771         unsigned NumElems = VT.getVectorNumElements();
13772
13773         // Extract the LHS vectors
13774         SDValue LHS = Op.getOperand(0);
13775         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13776         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13777
13778         MVT EltVT = VT.getVectorElementType();
13779         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13780
13781         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13782         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13783         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13784                                    ExtraNumElems/2);
13785         SDValue Extra = DAG.getValueType(ExtraVT);
13786
13787         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13788         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13789
13790         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13791       }
13792       // fall through
13793     case MVT::v4i32:
13794     case MVT::v8i16: {
13795       SDValue Op0 = Op.getOperand(0);
13796       SDValue Op00 = Op0.getOperand(0);
13797       SDValue Tmp1;
13798       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13799       if (Op0.getOpcode() == ISD::BITCAST &&
13800           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13801         // (sext (vzext x)) -> (vsext x)
13802         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13803         if (Tmp1.getNode()) {
13804           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13805           // This folding is only valid when the in-reg type is a vector of i8,
13806           // i16, or i32.
13807           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13808               ExtraEltVT == MVT::i32) {
13809             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13810             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13811                    "This optimization is invalid without a VZEXT.");
13812             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13813           }
13814           Op0 = Tmp1;
13815         }
13816       }
13817
13818       // If the above didn't work, then just use Shift-Left + Shift-Right.
13819       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13820                                         DAG);
13821       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13822                                         DAG);
13823     }
13824   }
13825 }
13826
13827 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13828                                  SelectionDAG &DAG) {
13829   SDLoc dl(Op);
13830   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13831     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13832   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13833     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13834
13835   // The only fence that needs an instruction is a sequentially-consistent
13836   // cross-thread fence.
13837   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13838     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13839     // no-sse2). There isn't any reason to disable it if the target processor
13840     // supports it.
13841     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13842       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13843
13844     SDValue Chain = Op.getOperand(0);
13845     SDValue Zero = DAG.getConstant(0, MVT::i32);
13846     SDValue Ops[] = {
13847       DAG.getRegister(X86::ESP, MVT::i32), // Base
13848       DAG.getTargetConstant(1, MVT::i8),   // Scale
13849       DAG.getRegister(0, MVT::i32),        // Index
13850       DAG.getTargetConstant(0, MVT::i32),  // Disp
13851       DAG.getRegister(0, MVT::i32),        // Segment.
13852       Zero,
13853       Chain
13854     };
13855     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13856     return SDValue(Res, 0);
13857   }
13858
13859   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13860   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13861 }
13862
13863 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13864                              SelectionDAG &DAG) {
13865   MVT T = Op.getSimpleValueType();
13866   SDLoc DL(Op);
13867   unsigned Reg = 0;
13868   unsigned size = 0;
13869   switch(T.SimpleTy) {
13870   default: llvm_unreachable("Invalid value type!");
13871   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13872   case MVT::i16: Reg = X86::AX;  size = 2; break;
13873   case MVT::i32: Reg = X86::EAX; size = 4; break;
13874   case MVT::i64:
13875     assert(Subtarget->is64Bit() && "Node not type legal!");
13876     Reg = X86::RAX; size = 8;
13877     break;
13878   }
13879   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13880                                     Op.getOperand(2), SDValue());
13881   SDValue Ops[] = { cpIn.getValue(0),
13882                     Op.getOperand(1),
13883                     Op.getOperand(3),
13884                     DAG.getTargetConstant(size, MVT::i8),
13885                     cpIn.getValue(1) };
13886   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13887   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13888   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13889                                            Ops, array_lengthof(Ops), T, MMO);
13890   SDValue cpOut =
13891     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13892   return cpOut;
13893 }
13894
13895 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13896                             SelectionDAG &DAG) {
13897   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13898   MVT DstVT = Op.getSimpleValueType();
13899   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13900          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13901   assert((DstVT == MVT::i64 ||
13902           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13903          "Unexpected custom BITCAST");
13904   // i64 <=> MMX conversions are Legal.
13905   if (SrcVT==MVT::i64 && DstVT.isVector())
13906     return Op;
13907   if (DstVT==MVT::i64 && SrcVT.isVector())
13908     return Op;
13909   // MMX <=> MMX conversions are Legal.
13910   if (SrcVT.isVector() && DstVT.isVector())
13911     return Op;
13912   // All other conversions need to be expanded.
13913   return SDValue();
13914 }
13915
13916 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13917   SDNode *Node = Op.getNode();
13918   SDLoc dl(Node);
13919   EVT T = Node->getValueType(0);
13920   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13921                               DAG.getConstant(0, T), Node->getOperand(2));
13922   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13923                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13924                        Node->getOperand(0),
13925                        Node->getOperand(1), negOp,
13926                        cast<AtomicSDNode>(Node)->getMemOperand(),
13927                        cast<AtomicSDNode>(Node)->getOrdering(),
13928                        cast<AtomicSDNode>(Node)->getSynchScope());
13929 }
13930
13931 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13932   SDNode *Node = Op.getNode();
13933   SDLoc dl(Node);
13934   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13935
13936   // Convert seq_cst store -> xchg
13937   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13938   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13939   //        (The only way to get a 16-byte store is cmpxchg16b)
13940   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13941   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13942       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13943     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13944                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13945                                  Node->getOperand(0),
13946                                  Node->getOperand(1), Node->getOperand(2),
13947                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13948                                  cast<AtomicSDNode>(Node)->getOrdering(),
13949                                  cast<AtomicSDNode>(Node)->getSynchScope());
13950     return Swap.getValue(1);
13951   }
13952   // Other atomic stores have a simple pattern.
13953   return Op;
13954 }
13955
13956 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13957   EVT VT = Op.getNode()->getSimpleValueType(0);
13958
13959   // Let legalize expand this if it isn't a legal type yet.
13960   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13961     return SDValue();
13962
13963   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13964
13965   unsigned Opc;
13966   bool ExtraOp = false;
13967   switch (Op.getOpcode()) {
13968   default: llvm_unreachable("Invalid code");
13969   case ISD::ADDC: Opc = X86ISD::ADD; break;
13970   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13971   case ISD::SUBC: Opc = X86ISD::SUB; break;
13972   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13973   }
13974
13975   if (!ExtraOp)
13976     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13977                        Op.getOperand(1));
13978   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13979                      Op.getOperand(1), Op.getOperand(2));
13980 }
13981
13982 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13983                             SelectionDAG &DAG) {
13984   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13985
13986   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13987   // which returns the values as { float, float } (in XMM0) or
13988   // { double, double } (which is returned in XMM0, XMM1).
13989   SDLoc dl(Op);
13990   SDValue Arg = Op.getOperand(0);
13991   EVT ArgVT = Arg.getValueType();
13992   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13993
13994   TargetLowering::ArgListTy Args;
13995   TargetLowering::ArgListEntry Entry;
13996
13997   Entry.Node = Arg;
13998   Entry.Ty = ArgTy;
13999   Entry.isSExt = false;
14000   Entry.isZExt = false;
14001   Args.push_back(Entry);
14002
14003   bool isF64 = ArgVT == MVT::f64;
14004   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14005   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14006   // the results are returned via SRet in memory.
14007   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14009   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14010
14011   Type *RetTy = isF64
14012     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14013     : (Type*)VectorType::get(ArgTy, 4);
14014   TargetLowering::
14015     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14016                          false, false, false, false, 0,
14017                          CallingConv::C, /*isTaillCall=*/false,
14018                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14019                          Callee, Args, DAG, dl);
14020   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14021
14022   if (isF64)
14023     // Returned in xmm0 and xmm1.
14024     return CallResult.first;
14025
14026   // Returned in bits 0:31 and 32:64 xmm0.
14027   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14028                                CallResult.first, DAG.getIntPtrConstant(0));
14029   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14030                                CallResult.first, DAG.getIntPtrConstant(1));
14031   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14032   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14033 }
14034
14035 /// LowerOperation - Provide custom lowering hooks for some operations.
14036 ///
14037 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14038   switch (Op.getOpcode()) {
14039   default: llvm_unreachable("Should not custom lower this!");
14040   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14041   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14042   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14043   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14044   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14045   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14046   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14047   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14048   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14049   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14050   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14051   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14052   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14053   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14054   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14055   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14056   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14057   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14058   case ISD::SHL_PARTS:
14059   case ISD::SRA_PARTS:
14060   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14061   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14062   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14063   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14064   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14065   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14066   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14067   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14068   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14069   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14070   case ISD::FABS:               return LowerFABS(Op, DAG);
14071   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14072   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14073   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14074   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14075   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14076   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14077   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14078   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14079   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14080   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14081   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14082   case ISD::INTRINSIC_VOID:
14083   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14084   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14085   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14086   case ISD::FRAME_TO_ARGS_OFFSET:
14087                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14088   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14089   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14090   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14091   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14092   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14093   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14094   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14095   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14096   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14097   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14098   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14099   case ISD::SRA:
14100   case ISD::SRL:
14101   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14102   case ISD::SADDO:
14103   case ISD::UADDO:
14104   case ISD::SSUBO:
14105   case ISD::USUBO:
14106   case ISD::SMULO:
14107   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14108   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14109   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14110   case ISD::ADDC:
14111   case ISD::ADDE:
14112   case ISD::SUBC:
14113   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14114   case ISD::ADD:                return LowerADD(Op, DAG);
14115   case ISD::SUB:                return LowerSUB(Op, DAG);
14116   case ISD::SDIV:               return LowerSDIV(Op, DAG);
14117   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14118   }
14119 }
14120
14121 static void ReplaceATOMIC_LOAD(SDNode *Node,
14122                                   SmallVectorImpl<SDValue> &Results,
14123                                   SelectionDAG &DAG) {
14124   SDLoc dl(Node);
14125   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14126
14127   // Convert wide load -> cmpxchg8b/cmpxchg16b
14128   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14129   //        (The only way to get a 16-byte load is cmpxchg16b)
14130   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14131   SDValue Zero = DAG.getConstant(0, VT);
14132   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14133                                Node->getOperand(0),
14134                                Node->getOperand(1), Zero, Zero,
14135                                cast<AtomicSDNode>(Node)->getMemOperand(),
14136                                cast<AtomicSDNode>(Node)->getOrdering(),
14137                                cast<AtomicSDNode>(Node)->getOrdering(),
14138                                cast<AtomicSDNode>(Node)->getSynchScope());
14139   Results.push_back(Swap.getValue(0));
14140   Results.push_back(Swap.getValue(1));
14141 }
14142
14143 static void
14144 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14145                         SelectionDAG &DAG, unsigned NewOp) {
14146   SDLoc dl(Node);
14147   assert (Node->getValueType(0) == MVT::i64 &&
14148           "Only know how to expand i64 atomics");
14149
14150   SDValue Chain = Node->getOperand(0);
14151   SDValue In1 = Node->getOperand(1);
14152   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14153                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14154   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14155                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14156   SDValue Ops[] = { Chain, In1, In2L, In2H };
14157   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14158   SDValue Result =
14159     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14160                             cast<MemSDNode>(Node)->getMemOperand());
14161   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14162   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14163   Results.push_back(Result.getValue(2));
14164 }
14165
14166 /// ReplaceNodeResults - Replace a node with an illegal result type
14167 /// with a new node built out of custom code.
14168 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14169                                            SmallVectorImpl<SDValue>&Results,
14170                                            SelectionDAG &DAG) const {
14171   SDLoc dl(N);
14172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14173   switch (N->getOpcode()) {
14174   default:
14175     llvm_unreachable("Do not know how to custom type legalize this operation!");
14176   case ISD::SIGN_EXTEND_INREG:
14177   case ISD::ADDC:
14178   case ISD::ADDE:
14179   case ISD::SUBC:
14180   case ISD::SUBE:
14181     // We don't want to expand or promote these.
14182     return;
14183   case ISD::FP_TO_SINT:
14184   case ISD::FP_TO_UINT: {
14185     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14186
14187     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14188       return;
14189
14190     std::pair<SDValue,SDValue> Vals =
14191         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14192     SDValue FIST = Vals.first, StackSlot = Vals.second;
14193     if (FIST.getNode() != 0) {
14194       EVT VT = N->getValueType(0);
14195       // Return a load from the stack slot.
14196       if (StackSlot.getNode() != 0)
14197         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14198                                       MachinePointerInfo(),
14199                                       false, false, false, 0));
14200       else
14201         Results.push_back(FIST);
14202     }
14203     return;
14204   }
14205   case ISD::UINT_TO_FP: {
14206     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14207     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14208         N->getValueType(0) != MVT::v2f32)
14209       return;
14210     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14211                                  N->getOperand(0));
14212     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14213                                      MVT::f64);
14214     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14215     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14216                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14217     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14218     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14219     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14220     return;
14221   }
14222   case ISD::FP_ROUND: {
14223     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14224         return;
14225     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14226     Results.push_back(V);
14227     return;
14228   }
14229   case ISD::INTRINSIC_W_CHAIN: {
14230     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14231     switch (IntNo) {
14232     default : llvm_unreachable("Do not know how to custom type "
14233                                "legalize this intrinsic operation!");
14234     case Intrinsic::x86_rdtsc:
14235       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14236                                      Results);
14237     case Intrinsic::x86_rdtscp:
14238       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14239                                      Results);
14240     }
14241   }
14242   case ISD::READCYCLECOUNTER: {
14243     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14244                                    Results);
14245   }
14246   case ISD::ATOMIC_CMP_SWAP: {
14247     EVT T = N->getValueType(0);
14248     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14249     bool Regs64bit = T == MVT::i128;
14250     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14251     SDValue cpInL, cpInH;
14252     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14253                         DAG.getConstant(0, HalfT));
14254     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14255                         DAG.getConstant(1, HalfT));
14256     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14257                              Regs64bit ? X86::RAX : X86::EAX,
14258                              cpInL, SDValue());
14259     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14260                              Regs64bit ? X86::RDX : X86::EDX,
14261                              cpInH, cpInL.getValue(1));
14262     SDValue swapInL, swapInH;
14263     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14264                           DAG.getConstant(0, HalfT));
14265     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14266                           DAG.getConstant(1, HalfT));
14267     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14268                                Regs64bit ? X86::RBX : X86::EBX,
14269                                swapInL, cpInH.getValue(1));
14270     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14271                                Regs64bit ? X86::RCX : X86::ECX,
14272                                swapInH, swapInL.getValue(1));
14273     SDValue Ops[] = { swapInH.getValue(0),
14274                       N->getOperand(1),
14275                       swapInH.getValue(1) };
14276     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14277     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14278     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14279                                   X86ISD::LCMPXCHG8_DAG;
14280     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14281                                              Ops, array_lengthof(Ops), T, MMO);
14282     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14283                                         Regs64bit ? X86::RAX : X86::EAX,
14284                                         HalfT, Result.getValue(1));
14285     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14286                                         Regs64bit ? X86::RDX : X86::EDX,
14287                                         HalfT, cpOutL.getValue(2));
14288     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14289     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14290     Results.push_back(cpOutH.getValue(1));
14291     return;
14292   }
14293   case ISD::ATOMIC_LOAD_ADD:
14294   case ISD::ATOMIC_LOAD_AND:
14295   case ISD::ATOMIC_LOAD_NAND:
14296   case ISD::ATOMIC_LOAD_OR:
14297   case ISD::ATOMIC_LOAD_SUB:
14298   case ISD::ATOMIC_LOAD_XOR:
14299   case ISD::ATOMIC_LOAD_MAX:
14300   case ISD::ATOMIC_LOAD_MIN:
14301   case ISD::ATOMIC_LOAD_UMAX:
14302   case ISD::ATOMIC_LOAD_UMIN:
14303   case ISD::ATOMIC_SWAP: {
14304     unsigned Opc;
14305     switch (N->getOpcode()) {
14306     default: llvm_unreachable("Unexpected opcode");
14307     case ISD::ATOMIC_LOAD_ADD:
14308       Opc = X86ISD::ATOMADD64_DAG;
14309       break;
14310     case ISD::ATOMIC_LOAD_AND:
14311       Opc = X86ISD::ATOMAND64_DAG;
14312       break;
14313     case ISD::ATOMIC_LOAD_NAND:
14314       Opc = X86ISD::ATOMNAND64_DAG;
14315       break;
14316     case ISD::ATOMIC_LOAD_OR:
14317       Opc = X86ISD::ATOMOR64_DAG;
14318       break;
14319     case ISD::ATOMIC_LOAD_SUB:
14320       Opc = X86ISD::ATOMSUB64_DAG;
14321       break;
14322     case ISD::ATOMIC_LOAD_XOR:
14323       Opc = X86ISD::ATOMXOR64_DAG;
14324       break;
14325     case ISD::ATOMIC_LOAD_MAX:
14326       Opc = X86ISD::ATOMMAX64_DAG;
14327       break;
14328     case ISD::ATOMIC_LOAD_MIN:
14329       Opc = X86ISD::ATOMMIN64_DAG;
14330       break;
14331     case ISD::ATOMIC_LOAD_UMAX:
14332       Opc = X86ISD::ATOMUMAX64_DAG;
14333       break;
14334     case ISD::ATOMIC_LOAD_UMIN:
14335       Opc = X86ISD::ATOMUMIN64_DAG;
14336       break;
14337     case ISD::ATOMIC_SWAP:
14338       Opc = X86ISD::ATOMSWAP64_DAG;
14339       break;
14340     }
14341     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14342     return;
14343   }
14344   case ISD::ATOMIC_LOAD:
14345     ReplaceATOMIC_LOAD(N, Results, DAG);
14346   }
14347 }
14348
14349 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14350   switch (Opcode) {
14351   default: return NULL;
14352   case X86ISD::BSF:                return "X86ISD::BSF";
14353   case X86ISD::BSR:                return "X86ISD::BSR";
14354   case X86ISD::SHLD:               return "X86ISD::SHLD";
14355   case X86ISD::SHRD:               return "X86ISD::SHRD";
14356   case X86ISD::FAND:               return "X86ISD::FAND";
14357   case X86ISD::FANDN:              return "X86ISD::FANDN";
14358   case X86ISD::FOR:                return "X86ISD::FOR";
14359   case X86ISD::FXOR:               return "X86ISD::FXOR";
14360   case X86ISD::FSRL:               return "X86ISD::FSRL";
14361   case X86ISD::FILD:               return "X86ISD::FILD";
14362   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14363   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14364   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14365   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14366   case X86ISD::FLD:                return "X86ISD::FLD";
14367   case X86ISD::FST:                return "X86ISD::FST";
14368   case X86ISD::CALL:               return "X86ISD::CALL";
14369   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14370   case X86ISD::BT:                 return "X86ISD::BT";
14371   case X86ISD::CMP:                return "X86ISD::CMP";
14372   case X86ISD::COMI:               return "X86ISD::COMI";
14373   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14374   case X86ISD::CMPM:               return "X86ISD::CMPM";
14375   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14376   case X86ISD::SETCC:              return "X86ISD::SETCC";
14377   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14378   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14379   case X86ISD::CMOV:               return "X86ISD::CMOV";
14380   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14381   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14382   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14383   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14384   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14385   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14386   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14387   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14388   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14389   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14390   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14391   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14392   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14393   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14394   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14395   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14396   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14397   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14398   case X86ISD::HADD:               return "X86ISD::HADD";
14399   case X86ISD::HSUB:               return "X86ISD::HSUB";
14400   case X86ISD::FHADD:              return "X86ISD::FHADD";
14401   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14402   case X86ISD::UMAX:               return "X86ISD::UMAX";
14403   case X86ISD::UMIN:               return "X86ISD::UMIN";
14404   case X86ISD::SMAX:               return "X86ISD::SMAX";
14405   case X86ISD::SMIN:               return "X86ISD::SMIN";
14406   case X86ISD::FMAX:               return "X86ISD::FMAX";
14407   case X86ISD::FMIN:               return "X86ISD::FMIN";
14408   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14409   case X86ISD::FMINC:              return "X86ISD::FMINC";
14410   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14411   case X86ISD::FRCP:               return "X86ISD::FRCP";
14412   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14413   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14414   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14415   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14416   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14417   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14418   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14419   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14420   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14421   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14422   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14423   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14424   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14425   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14426   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14427   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14428   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14429   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14430   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14431   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14432   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14433   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14434   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14435   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14436   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14437   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14438   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14439   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14440   case X86ISD::VSHL:               return "X86ISD::VSHL";
14441   case X86ISD::VSRL:               return "X86ISD::VSRL";
14442   case X86ISD::VSRA:               return "X86ISD::VSRA";
14443   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14444   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14445   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14446   case X86ISD::CMPP:               return "X86ISD::CMPP";
14447   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14448   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14449   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14450   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14451   case X86ISD::ADD:                return "X86ISD::ADD";
14452   case X86ISD::SUB:                return "X86ISD::SUB";
14453   case X86ISD::ADC:                return "X86ISD::ADC";
14454   case X86ISD::SBB:                return "X86ISD::SBB";
14455   case X86ISD::SMUL:               return "X86ISD::SMUL";
14456   case X86ISD::UMUL:               return "X86ISD::UMUL";
14457   case X86ISD::INC:                return "X86ISD::INC";
14458   case X86ISD::DEC:                return "X86ISD::DEC";
14459   case X86ISD::OR:                 return "X86ISD::OR";
14460   case X86ISD::XOR:                return "X86ISD::XOR";
14461   case X86ISD::AND:                return "X86ISD::AND";
14462   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14463   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14464   case X86ISD::PTEST:              return "X86ISD::PTEST";
14465   case X86ISD::TESTP:              return "X86ISD::TESTP";
14466   case X86ISD::TESTM:              return "X86ISD::TESTM";
14467   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14468   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14469   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14470   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14471   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14472   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14473   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14474   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14475   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14476   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14477   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14478   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14479   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14480   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14481   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14482   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14483   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14484   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14485   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14486   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14487   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14488   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14489   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14490   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14491   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14492   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14493   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14494   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14495   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14496   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14497   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14498   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14499   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14500   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14501   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14502   case X86ISD::SAHF:               return "X86ISD::SAHF";
14503   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14504   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14505   case X86ISD::FMADD:              return "X86ISD::FMADD";
14506   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14507   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14508   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14509   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14510   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14511   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14512   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14513   case X86ISD::XTEST:              return "X86ISD::XTEST";
14514   }
14515 }
14516
14517 // isLegalAddressingMode - Return true if the addressing mode represented
14518 // by AM is legal for this target, for a load/store of the specified type.
14519 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14520                                               Type *Ty) const {
14521   // X86 supports extremely general addressing modes.
14522   CodeModel::Model M = getTargetMachine().getCodeModel();
14523   Reloc::Model R = getTargetMachine().getRelocationModel();
14524
14525   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14526   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14527     return false;
14528
14529   if (AM.BaseGV) {
14530     unsigned GVFlags =
14531       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14532
14533     // If a reference to this global requires an extra load, we can't fold it.
14534     if (isGlobalStubReference(GVFlags))
14535       return false;
14536
14537     // If BaseGV requires a register for the PIC base, we cannot also have a
14538     // BaseReg specified.
14539     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14540       return false;
14541
14542     // If lower 4G is not available, then we must use rip-relative addressing.
14543     if ((M != CodeModel::Small || R != Reloc::Static) &&
14544         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14545       return false;
14546   }
14547
14548   switch (AM.Scale) {
14549   case 0:
14550   case 1:
14551   case 2:
14552   case 4:
14553   case 8:
14554     // These scales always work.
14555     break;
14556   case 3:
14557   case 5:
14558   case 9:
14559     // These scales are formed with basereg+scalereg.  Only accept if there is
14560     // no basereg yet.
14561     if (AM.HasBaseReg)
14562       return false;
14563     break;
14564   default:  // Other stuff never works.
14565     return false;
14566   }
14567
14568   return true;
14569 }
14570
14571 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14572   unsigned Bits = Ty->getScalarSizeInBits();
14573
14574   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14575   // particularly cheaper than those without.
14576   if (Bits == 8)
14577     return false;
14578
14579   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14580   // variable shifts just as cheap as scalar ones.
14581   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14582     return false;
14583
14584   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14585   // fully general vector.
14586   return true;
14587 }
14588
14589 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14590   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14591     return false;
14592   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14593   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14594   return NumBits1 > NumBits2;
14595 }
14596
14597 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14598   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14599     return false;
14600
14601   if (!isTypeLegal(EVT::getEVT(Ty1)))
14602     return false;
14603
14604   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14605
14606   // Assuming the caller doesn't have a zeroext or signext return parameter,
14607   // truncation all the way down to i1 is valid.
14608   return true;
14609 }
14610
14611 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14612   return isInt<32>(Imm);
14613 }
14614
14615 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14616   // Can also use sub to handle negated immediates.
14617   return isInt<32>(Imm);
14618 }
14619
14620 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14621   if (!VT1.isInteger() || !VT2.isInteger())
14622     return false;
14623   unsigned NumBits1 = VT1.getSizeInBits();
14624   unsigned NumBits2 = VT2.getSizeInBits();
14625   return NumBits1 > NumBits2;
14626 }
14627
14628 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14629   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14630   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14631 }
14632
14633 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14634   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14635   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14636 }
14637
14638 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14639   EVT VT1 = Val.getValueType();
14640   if (isZExtFree(VT1, VT2))
14641     return true;
14642
14643   if (Val.getOpcode() != ISD::LOAD)
14644     return false;
14645
14646   if (!VT1.isSimple() || !VT1.isInteger() ||
14647       !VT2.isSimple() || !VT2.isInteger())
14648     return false;
14649
14650   switch (VT1.getSimpleVT().SimpleTy) {
14651   default: break;
14652   case MVT::i8:
14653   case MVT::i16:
14654   case MVT::i32:
14655     // X86 has 8, 16, and 32-bit zero-extending loads.
14656     return true;
14657   }
14658
14659   return false;
14660 }
14661
14662 bool
14663 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14664   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14665     return false;
14666
14667   VT = VT.getScalarType();
14668
14669   if (!VT.isSimple())
14670     return false;
14671
14672   switch (VT.getSimpleVT().SimpleTy) {
14673   case MVT::f32:
14674   case MVT::f64:
14675     return true;
14676   default:
14677     break;
14678   }
14679
14680   return false;
14681 }
14682
14683 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14684   // i16 instructions are longer (0x66 prefix) and potentially slower.
14685   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14686 }
14687
14688 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14689 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14690 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14691 /// are assumed to be legal.
14692 bool
14693 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14694                                       EVT VT) const {
14695   if (!VT.isSimple())
14696     return false;
14697
14698   MVT SVT = VT.getSimpleVT();
14699
14700   // Very little shuffling can be done for 64-bit vectors right now.
14701   if (VT.getSizeInBits() == 64)
14702     return false;
14703
14704   // FIXME: pshufb, blends, shifts.
14705   return (SVT.getVectorNumElements() == 2 ||
14706           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14707           isMOVLMask(M, SVT) ||
14708           isSHUFPMask(M, SVT) ||
14709           isPSHUFDMask(M, SVT) ||
14710           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14711           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14712           isPALIGNRMask(M, SVT, Subtarget) ||
14713           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14714           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14715           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14716           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14717 }
14718
14719 bool
14720 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14721                                           EVT VT) const {
14722   if (!VT.isSimple())
14723     return false;
14724
14725   MVT SVT = VT.getSimpleVT();
14726   unsigned NumElts = SVT.getVectorNumElements();
14727   // FIXME: This collection of masks seems suspect.
14728   if (NumElts == 2)
14729     return true;
14730   if (NumElts == 4 && SVT.is128BitVector()) {
14731     return (isMOVLMask(Mask, SVT)  ||
14732             isCommutedMOVLMask(Mask, SVT, true) ||
14733             isSHUFPMask(Mask, SVT) ||
14734             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14735   }
14736   return false;
14737 }
14738
14739 //===----------------------------------------------------------------------===//
14740 //                           X86 Scheduler Hooks
14741 //===----------------------------------------------------------------------===//
14742
14743 /// Utility function to emit xbegin specifying the start of an RTM region.
14744 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14745                                      const TargetInstrInfo *TII) {
14746   DebugLoc DL = MI->getDebugLoc();
14747
14748   const BasicBlock *BB = MBB->getBasicBlock();
14749   MachineFunction::iterator I = MBB;
14750   ++I;
14751
14752   // For the v = xbegin(), we generate
14753   //
14754   // thisMBB:
14755   //  xbegin sinkMBB
14756   //
14757   // mainMBB:
14758   //  eax = -1
14759   //
14760   // sinkMBB:
14761   //  v = eax
14762
14763   MachineBasicBlock *thisMBB = MBB;
14764   MachineFunction *MF = MBB->getParent();
14765   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14766   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14767   MF->insert(I, mainMBB);
14768   MF->insert(I, sinkMBB);
14769
14770   // Transfer the remainder of BB and its successor edges to sinkMBB.
14771   sinkMBB->splice(sinkMBB->begin(), MBB,
14772                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14773   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14774
14775   // thisMBB:
14776   //  xbegin sinkMBB
14777   //  # fallthrough to mainMBB
14778   //  # abortion to sinkMBB
14779   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14780   thisMBB->addSuccessor(mainMBB);
14781   thisMBB->addSuccessor(sinkMBB);
14782
14783   // mainMBB:
14784   //  EAX = -1
14785   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14786   mainMBB->addSuccessor(sinkMBB);
14787
14788   // sinkMBB:
14789   // EAX is live into the sinkMBB
14790   sinkMBB->addLiveIn(X86::EAX);
14791   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14792           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14793     .addReg(X86::EAX);
14794
14795   MI->eraseFromParent();
14796   return sinkMBB;
14797 }
14798
14799 // Get CMPXCHG opcode for the specified data type.
14800 static unsigned getCmpXChgOpcode(EVT VT) {
14801   switch (VT.getSimpleVT().SimpleTy) {
14802   case MVT::i8:  return X86::LCMPXCHG8;
14803   case MVT::i16: return X86::LCMPXCHG16;
14804   case MVT::i32: return X86::LCMPXCHG32;
14805   case MVT::i64: return X86::LCMPXCHG64;
14806   default:
14807     break;
14808   }
14809   llvm_unreachable("Invalid operand size!");
14810 }
14811
14812 // Get LOAD opcode for the specified data type.
14813 static unsigned getLoadOpcode(EVT VT) {
14814   switch (VT.getSimpleVT().SimpleTy) {
14815   case MVT::i8:  return X86::MOV8rm;
14816   case MVT::i16: return X86::MOV16rm;
14817   case MVT::i32: return X86::MOV32rm;
14818   case MVT::i64: return X86::MOV64rm;
14819   default:
14820     break;
14821   }
14822   llvm_unreachable("Invalid operand size!");
14823 }
14824
14825 // Get opcode of the non-atomic one from the specified atomic instruction.
14826 static unsigned getNonAtomicOpcode(unsigned Opc) {
14827   switch (Opc) {
14828   case X86::ATOMAND8:  return X86::AND8rr;
14829   case X86::ATOMAND16: return X86::AND16rr;
14830   case X86::ATOMAND32: return X86::AND32rr;
14831   case X86::ATOMAND64: return X86::AND64rr;
14832   case X86::ATOMOR8:   return X86::OR8rr;
14833   case X86::ATOMOR16:  return X86::OR16rr;
14834   case X86::ATOMOR32:  return X86::OR32rr;
14835   case X86::ATOMOR64:  return X86::OR64rr;
14836   case X86::ATOMXOR8:  return X86::XOR8rr;
14837   case X86::ATOMXOR16: return X86::XOR16rr;
14838   case X86::ATOMXOR32: return X86::XOR32rr;
14839   case X86::ATOMXOR64: return X86::XOR64rr;
14840   }
14841   llvm_unreachable("Unhandled atomic-load-op opcode!");
14842 }
14843
14844 // Get opcode of the non-atomic one from the specified atomic instruction with
14845 // extra opcode.
14846 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14847                                                unsigned &ExtraOpc) {
14848   switch (Opc) {
14849   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14850   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14851   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14852   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14853   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14854   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14855   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14856   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14857   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14858   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14859   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14860   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14861   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14862   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14863   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14864   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14865   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14866   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14867   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14868   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14869   }
14870   llvm_unreachable("Unhandled atomic-load-op opcode!");
14871 }
14872
14873 // Get opcode of the non-atomic one from the specified atomic instruction for
14874 // 64-bit data type on 32-bit target.
14875 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14876   switch (Opc) {
14877   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14878   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14879   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14880   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14881   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14882   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14883   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14884   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14885   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14886   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14887   }
14888   llvm_unreachable("Unhandled atomic-load-op opcode!");
14889 }
14890
14891 // Get opcode of the non-atomic one from the specified atomic instruction for
14892 // 64-bit data type on 32-bit target with extra opcode.
14893 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14894                                                    unsigned &HiOpc,
14895                                                    unsigned &ExtraOpc) {
14896   switch (Opc) {
14897   case X86::ATOMNAND6432:
14898     ExtraOpc = X86::NOT32r;
14899     HiOpc = X86::AND32rr;
14900     return X86::AND32rr;
14901   }
14902   llvm_unreachable("Unhandled atomic-load-op opcode!");
14903 }
14904
14905 // Get pseudo CMOV opcode from the specified data type.
14906 static unsigned getPseudoCMOVOpc(EVT VT) {
14907   switch (VT.getSimpleVT().SimpleTy) {
14908   case MVT::i8:  return X86::CMOV_GR8;
14909   case MVT::i16: return X86::CMOV_GR16;
14910   case MVT::i32: return X86::CMOV_GR32;
14911   default:
14912     break;
14913   }
14914   llvm_unreachable("Unknown CMOV opcode!");
14915 }
14916
14917 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14918 // They will be translated into a spin-loop or compare-exchange loop from
14919 //
14920 //    ...
14921 //    dst = atomic-fetch-op MI.addr, MI.val
14922 //    ...
14923 //
14924 // to
14925 //
14926 //    ...
14927 //    t1 = LOAD MI.addr
14928 // loop:
14929 //    t4 = phi(t1, t3 / loop)
14930 //    t2 = OP MI.val, t4
14931 //    EAX = t4
14932 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14933 //    t3 = EAX
14934 //    JNE loop
14935 // sink:
14936 //    dst = t3
14937 //    ...
14938 MachineBasicBlock *
14939 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14940                                        MachineBasicBlock *MBB) const {
14941   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14942   DebugLoc DL = MI->getDebugLoc();
14943
14944   MachineFunction *MF = MBB->getParent();
14945   MachineRegisterInfo &MRI = MF->getRegInfo();
14946
14947   const BasicBlock *BB = MBB->getBasicBlock();
14948   MachineFunction::iterator I = MBB;
14949   ++I;
14950
14951   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14952          "Unexpected number of operands");
14953
14954   assert(MI->hasOneMemOperand() &&
14955          "Expected atomic-load-op to have one memoperand");
14956
14957   // Memory Reference
14958   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14959   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14960
14961   unsigned DstReg, SrcReg;
14962   unsigned MemOpndSlot;
14963
14964   unsigned CurOp = 0;
14965
14966   DstReg = MI->getOperand(CurOp++).getReg();
14967   MemOpndSlot = CurOp;
14968   CurOp += X86::AddrNumOperands;
14969   SrcReg = MI->getOperand(CurOp++).getReg();
14970
14971   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14972   MVT::SimpleValueType VT = *RC->vt_begin();
14973   unsigned t1 = MRI.createVirtualRegister(RC);
14974   unsigned t2 = MRI.createVirtualRegister(RC);
14975   unsigned t3 = MRI.createVirtualRegister(RC);
14976   unsigned t4 = MRI.createVirtualRegister(RC);
14977   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14978
14979   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14980   unsigned LOADOpc = getLoadOpcode(VT);
14981
14982   // For the atomic load-arith operator, we generate
14983   //
14984   //  thisMBB:
14985   //    t1 = LOAD [MI.addr]
14986   //  mainMBB:
14987   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14988   //    t1 = OP MI.val, EAX
14989   //    EAX = t4
14990   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14991   //    t3 = EAX
14992   //    JNE mainMBB
14993   //  sinkMBB:
14994   //    dst = t3
14995
14996   MachineBasicBlock *thisMBB = MBB;
14997   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14998   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14999   MF->insert(I, mainMBB);
15000   MF->insert(I, sinkMBB);
15001
15002   MachineInstrBuilder MIB;
15003
15004   // Transfer the remainder of BB and its successor edges to sinkMBB.
15005   sinkMBB->splice(sinkMBB->begin(), MBB,
15006                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15007   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15008
15009   // thisMBB:
15010   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15011   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15012     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15013     if (NewMO.isReg())
15014       NewMO.setIsKill(false);
15015     MIB.addOperand(NewMO);
15016   }
15017   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15018     unsigned flags = (*MMOI)->getFlags();
15019     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15020     MachineMemOperand *MMO =
15021       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15022                                (*MMOI)->getSize(),
15023                                (*MMOI)->getBaseAlignment(),
15024                                (*MMOI)->getTBAAInfo(),
15025                                (*MMOI)->getRanges());
15026     MIB.addMemOperand(MMO);
15027   }
15028
15029   thisMBB->addSuccessor(mainMBB);
15030
15031   // mainMBB:
15032   MachineBasicBlock *origMainMBB = mainMBB;
15033
15034   // Add a PHI.
15035   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15036                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15037
15038   unsigned Opc = MI->getOpcode();
15039   switch (Opc) {
15040   default:
15041     llvm_unreachable("Unhandled atomic-load-op opcode!");
15042   case X86::ATOMAND8:
15043   case X86::ATOMAND16:
15044   case X86::ATOMAND32:
15045   case X86::ATOMAND64:
15046   case X86::ATOMOR8:
15047   case X86::ATOMOR16:
15048   case X86::ATOMOR32:
15049   case X86::ATOMOR64:
15050   case X86::ATOMXOR8:
15051   case X86::ATOMXOR16:
15052   case X86::ATOMXOR32:
15053   case X86::ATOMXOR64: {
15054     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15055     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15056       .addReg(t4);
15057     break;
15058   }
15059   case X86::ATOMNAND8:
15060   case X86::ATOMNAND16:
15061   case X86::ATOMNAND32:
15062   case X86::ATOMNAND64: {
15063     unsigned Tmp = MRI.createVirtualRegister(RC);
15064     unsigned NOTOpc;
15065     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15066     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15067       .addReg(t4);
15068     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15069     break;
15070   }
15071   case X86::ATOMMAX8:
15072   case X86::ATOMMAX16:
15073   case X86::ATOMMAX32:
15074   case X86::ATOMMAX64:
15075   case X86::ATOMMIN8:
15076   case X86::ATOMMIN16:
15077   case X86::ATOMMIN32:
15078   case X86::ATOMMIN64:
15079   case X86::ATOMUMAX8:
15080   case X86::ATOMUMAX16:
15081   case X86::ATOMUMAX32:
15082   case X86::ATOMUMAX64:
15083   case X86::ATOMUMIN8:
15084   case X86::ATOMUMIN16:
15085   case X86::ATOMUMIN32:
15086   case X86::ATOMUMIN64: {
15087     unsigned CMPOpc;
15088     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15089
15090     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15091       .addReg(SrcReg)
15092       .addReg(t4);
15093
15094     if (Subtarget->hasCMov()) {
15095       if (VT != MVT::i8) {
15096         // Native support
15097         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15098           .addReg(SrcReg)
15099           .addReg(t4);
15100       } else {
15101         // Promote i8 to i32 to use CMOV32
15102         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15103         const TargetRegisterClass *RC32 =
15104           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15105         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15106         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15107         unsigned Tmp = MRI.createVirtualRegister(RC32);
15108
15109         unsigned Undef = MRI.createVirtualRegister(RC32);
15110         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15111
15112         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15113           .addReg(Undef)
15114           .addReg(SrcReg)
15115           .addImm(X86::sub_8bit);
15116         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15117           .addReg(Undef)
15118           .addReg(t4)
15119           .addImm(X86::sub_8bit);
15120
15121         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15122           .addReg(SrcReg32)
15123           .addReg(AccReg32);
15124
15125         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15126           .addReg(Tmp, 0, X86::sub_8bit);
15127       }
15128     } else {
15129       // Use pseudo select and lower them.
15130       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15131              "Invalid atomic-load-op transformation!");
15132       unsigned SelOpc = getPseudoCMOVOpc(VT);
15133       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15134       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15135       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15136               .addReg(SrcReg).addReg(t4)
15137               .addImm(CC);
15138       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15139       // Replace the original PHI node as mainMBB is changed after CMOV
15140       // lowering.
15141       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15142         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15143       Phi->eraseFromParent();
15144     }
15145     break;
15146   }
15147   }
15148
15149   // Copy PhyReg back from virtual register.
15150   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15151     .addReg(t4);
15152
15153   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15154   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15155     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15156     if (NewMO.isReg())
15157       NewMO.setIsKill(false);
15158     MIB.addOperand(NewMO);
15159   }
15160   MIB.addReg(t2);
15161   MIB.setMemRefs(MMOBegin, MMOEnd);
15162
15163   // Copy PhyReg back to virtual register.
15164   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15165     .addReg(PhyReg);
15166
15167   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15168
15169   mainMBB->addSuccessor(origMainMBB);
15170   mainMBB->addSuccessor(sinkMBB);
15171
15172   // sinkMBB:
15173   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15174           TII->get(TargetOpcode::COPY), DstReg)
15175     .addReg(t3);
15176
15177   MI->eraseFromParent();
15178   return sinkMBB;
15179 }
15180
15181 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15182 // instructions. They will be translated into a spin-loop or compare-exchange
15183 // loop from
15184 //
15185 //    ...
15186 //    dst = atomic-fetch-op MI.addr, MI.val
15187 //    ...
15188 //
15189 // to
15190 //
15191 //    ...
15192 //    t1L = LOAD [MI.addr + 0]
15193 //    t1H = LOAD [MI.addr + 4]
15194 // loop:
15195 //    t4L = phi(t1L, t3L / loop)
15196 //    t4H = phi(t1H, t3H / loop)
15197 //    t2L = OP MI.val.lo, t4L
15198 //    t2H = OP MI.val.hi, t4H
15199 //    EAX = t4L
15200 //    EDX = t4H
15201 //    EBX = t2L
15202 //    ECX = t2H
15203 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15204 //    t3L = EAX
15205 //    t3H = EDX
15206 //    JNE loop
15207 // sink:
15208 //    dstL = t3L
15209 //    dstH = t3H
15210 //    ...
15211 MachineBasicBlock *
15212 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15213                                            MachineBasicBlock *MBB) const {
15214   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15215   DebugLoc DL = MI->getDebugLoc();
15216
15217   MachineFunction *MF = MBB->getParent();
15218   MachineRegisterInfo &MRI = MF->getRegInfo();
15219
15220   const BasicBlock *BB = MBB->getBasicBlock();
15221   MachineFunction::iterator I = MBB;
15222   ++I;
15223
15224   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15225          "Unexpected number of operands");
15226
15227   assert(MI->hasOneMemOperand() &&
15228          "Expected atomic-load-op32 to have one memoperand");
15229
15230   // Memory Reference
15231   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15232   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15233
15234   unsigned DstLoReg, DstHiReg;
15235   unsigned SrcLoReg, SrcHiReg;
15236   unsigned MemOpndSlot;
15237
15238   unsigned CurOp = 0;
15239
15240   DstLoReg = MI->getOperand(CurOp++).getReg();
15241   DstHiReg = MI->getOperand(CurOp++).getReg();
15242   MemOpndSlot = CurOp;
15243   CurOp += X86::AddrNumOperands;
15244   SrcLoReg = MI->getOperand(CurOp++).getReg();
15245   SrcHiReg = MI->getOperand(CurOp++).getReg();
15246
15247   const TargetRegisterClass *RC = &X86::GR32RegClass;
15248   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15249
15250   unsigned t1L = MRI.createVirtualRegister(RC);
15251   unsigned t1H = MRI.createVirtualRegister(RC);
15252   unsigned t2L = MRI.createVirtualRegister(RC);
15253   unsigned t2H = MRI.createVirtualRegister(RC);
15254   unsigned t3L = MRI.createVirtualRegister(RC);
15255   unsigned t3H = MRI.createVirtualRegister(RC);
15256   unsigned t4L = MRI.createVirtualRegister(RC);
15257   unsigned t4H = MRI.createVirtualRegister(RC);
15258
15259   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15260   unsigned LOADOpc = X86::MOV32rm;
15261
15262   // For the atomic load-arith operator, we generate
15263   //
15264   //  thisMBB:
15265   //    t1L = LOAD [MI.addr + 0]
15266   //    t1H = LOAD [MI.addr + 4]
15267   //  mainMBB:
15268   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15269   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15270   //    t2L = OP MI.val.lo, t4L
15271   //    t2H = OP MI.val.hi, t4H
15272   //    EBX = t2L
15273   //    ECX = t2H
15274   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15275   //    t3L = EAX
15276   //    t3H = EDX
15277   //    JNE loop
15278   //  sinkMBB:
15279   //    dstL = t3L
15280   //    dstH = t3H
15281
15282   MachineBasicBlock *thisMBB = MBB;
15283   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15284   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15285   MF->insert(I, mainMBB);
15286   MF->insert(I, sinkMBB);
15287
15288   MachineInstrBuilder MIB;
15289
15290   // Transfer the remainder of BB and its successor edges to sinkMBB.
15291   sinkMBB->splice(sinkMBB->begin(), MBB,
15292                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15293   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15294
15295   // thisMBB:
15296   // Lo
15297   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15298   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15299     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15300     if (NewMO.isReg())
15301       NewMO.setIsKill(false);
15302     MIB.addOperand(NewMO);
15303   }
15304   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15305     unsigned flags = (*MMOI)->getFlags();
15306     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15307     MachineMemOperand *MMO =
15308       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15309                                (*MMOI)->getSize(),
15310                                (*MMOI)->getBaseAlignment(),
15311                                (*MMOI)->getTBAAInfo(),
15312                                (*MMOI)->getRanges());
15313     MIB.addMemOperand(MMO);
15314   };
15315   MachineInstr *LowMI = MIB;
15316
15317   // Hi
15318   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15319   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15320     if (i == X86::AddrDisp) {
15321       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15322     } else {
15323       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15324       if (NewMO.isReg())
15325         NewMO.setIsKill(false);
15326       MIB.addOperand(NewMO);
15327     }
15328   }
15329   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15330
15331   thisMBB->addSuccessor(mainMBB);
15332
15333   // mainMBB:
15334   MachineBasicBlock *origMainMBB = mainMBB;
15335
15336   // Add PHIs.
15337   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15338                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15339   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15340                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15341
15342   unsigned Opc = MI->getOpcode();
15343   switch (Opc) {
15344   default:
15345     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15346   case X86::ATOMAND6432:
15347   case X86::ATOMOR6432:
15348   case X86::ATOMXOR6432:
15349   case X86::ATOMADD6432:
15350   case X86::ATOMSUB6432: {
15351     unsigned HiOpc;
15352     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15353     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15354       .addReg(SrcLoReg);
15355     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15356       .addReg(SrcHiReg);
15357     break;
15358   }
15359   case X86::ATOMNAND6432: {
15360     unsigned HiOpc, NOTOpc;
15361     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15362     unsigned TmpL = MRI.createVirtualRegister(RC);
15363     unsigned TmpH = MRI.createVirtualRegister(RC);
15364     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15365       .addReg(t4L);
15366     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15367       .addReg(t4H);
15368     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15369     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15370     break;
15371   }
15372   case X86::ATOMMAX6432:
15373   case X86::ATOMMIN6432:
15374   case X86::ATOMUMAX6432:
15375   case X86::ATOMUMIN6432: {
15376     unsigned HiOpc;
15377     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15378     unsigned cL = MRI.createVirtualRegister(RC8);
15379     unsigned cH = MRI.createVirtualRegister(RC8);
15380     unsigned cL32 = MRI.createVirtualRegister(RC);
15381     unsigned cH32 = MRI.createVirtualRegister(RC);
15382     unsigned cc = MRI.createVirtualRegister(RC);
15383     // cl := cmp src_lo, lo
15384     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15385       .addReg(SrcLoReg).addReg(t4L);
15386     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15387     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15388     // ch := cmp src_hi, hi
15389     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15390       .addReg(SrcHiReg).addReg(t4H);
15391     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15392     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15393     // cc := if (src_hi == hi) ? cl : ch;
15394     if (Subtarget->hasCMov()) {
15395       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15396         .addReg(cH32).addReg(cL32);
15397     } else {
15398       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15399               .addReg(cH32).addReg(cL32)
15400               .addImm(X86::COND_E);
15401       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15402     }
15403     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15404     if (Subtarget->hasCMov()) {
15405       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15406         .addReg(SrcLoReg).addReg(t4L);
15407       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15408         .addReg(SrcHiReg).addReg(t4H);
15409     } else {
15410       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15411               .addReg(SrcLoReg).addReg(t4L)
15412               .addImm(X86::COND_NE);
15413       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15414       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15415       // 2nd CMOV lowering.
15416       mainMBB->addLiveIn(X86::EFLAGS);
15417       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15418               .addReg(SrcHiReg).addReg(t4H)
15419               .addImm(X86::COND_NE);
15420       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15421       // Replace the original PHI node as mainMBB is changed after CMOV
15422       // lowering.
15423       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15424         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15425       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15426         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15427       PhiL->eraseFromParent();
15428       PhiH->eraseFromParent();
15429     }
15430     break;
15431   }
15432   case X86::ATOMSWAP6432: {
15433     unsigned HiOpc;
15434     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15435     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15436     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15437     break;
15438   }
15439   }
15440
15441   // Copy EDX:EAX back from HiReg:LoReg
15442   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15443   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15444   // Copy ECX:EBX from t1H:t1L
15445   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15446   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15447
15448   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15449   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15450     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15451     if (NewMO.isReg())
15452       NewMO.setIsKill(false);
15453     MIB.addOperand(NewMO);
15454   }
15455   MIB.setMemRefs(MMOBegin, MMOEnd);
15456
15457   // Copy EDX:EAX back to t3H:t3L
15458   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15459   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15460
15461   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15462
15463   mainMBB->addSuccessor(origMainMBB);
15464   mainMBB->addSuccessor(sinkMBB);
15465
15466   // sinkMBB:
15467   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15468           TII->get(TargetOpcode::COPY), DstLoReg)
15469     .addReg(t3L);
15470   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15471           TII->get(TargetOpcode::COPY), DstHiReg)
15472     .addReg(t3H);
15473
15474   MI->eraseFromParent();
15475   return sinkMBB;
15476 }
15477
15478 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15479 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15480 // in the .td file.
15481 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15482                                        const TargetInstrInfo *TII) {
15483   unsigned Opc;
15484   switch (MI->getOpcode()) {
15485   default: llvm_unreachable("illegal opcode!");
15486   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15487   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15488   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15489   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15490   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15491   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15492   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15493   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15494   }
15495
15496   DebugLoc dl = MI->getDebugLoc();
15497   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15498
15499   unsigned NumArgs = MI->getNumOperands();
15500   for (unsigned i = 1; i < NumArgs; ++i) {
15501     MachineOperand &Op = MI->getOperand(i);
15502     if (!(Op.isReg() && Op.isImplicit()))
15503       MIB.addOperand(Op);
15504   }
15505   if (MI->hasOneMemOperand())
15506     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15507
15508   BuildMI(*BB, MI, dl,
15509     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15510     .addReg(X86::XMM0);
15511
15512   MI->eraseFromParent();
15513   return BB;
15514 }
15515
15516 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15517 // defs in an instruction pattern
15518 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15519                                        const TargetInstrInfo *TII) {
15520   unsigned Opc;
15521   switch (MI->getOpcode()) {
15522   default: llvm_unreachable("illegal opcode!");
15523   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15524   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15525   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15526   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15527   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15528   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15529   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15530   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15531   }
15532
15533   DebugLoc dl = MI->getDebugLoc();
15534   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15535
15536   unsigned NumArgs = MI->getNumOperands(); // remove the results
15537   for (unsigned i = 1; i < NumArgs; ++i) {
15538     MachineOperand &Op = MI->getOperand(i);
15539     if (!(Op.isReg() && Op.isImplicit()))
15540       MIB.addOperand(Op);
15541   }
15542   if (MI->hasOneMemOperand())
15543     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15544
15545   BuildMI(*BB, MI, dl,
15546     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15547     .addReg(X86::ECX);
15548
15549   MI->eraseFromParent();
15550   return BB;
15551 }
15552
15553 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15554                                        const TargetInstrInfo *TII,
15555                                        const X86Subtarget* Subtarget) {
15556   DebugLoc dl = MI->getDebugLoc();
15557
15558   // Address into RAX/EAX, other two args into ECX, EDX.
15559   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15560   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15561   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15562   for (int i = 0; i < X86::AddrNumOperands; ++i)
15563     MIB.addOperand(MI->getOperand(i));
15564
15565   unsigned ValOps = X86::AddrNumOperands;
15566   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15567     .addReg(MI->getOperand(ValOps).getReg());
15568   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15569     .addReg(MI->getOperand(ValOps+1).getReg());
15570
15571   // The instruction doesn't actually take any operands though.
15572   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15573
15574   MI->eraseFromParent(); // The pseudo is gone now.
15575   return BB;
15576 }
15577
15578 MachineBasicBlock *
15579 X86TargetLowering::EmitVAARG64WithCustomInserter(
15580                    MachineInstr *MI,
15581                    MachineBasicBlock *MBB) const {
15582   // Emit va_arg instruction on X86-64.
15583
15584   // Operands to this pseudo-instruction:
15585   // 0  ) Output        : destination address (reg)
15586   // 1-5) Input         : va_list address (addr, i64mem)
15587   // 6  ) ArgSize       : Size (in bytes) of vararg type
15588   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15589   // 8  ) Align         : Alignment of type
15590   // 9  ) EFLAGS (implicit-def)
15591
15592   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15593   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15594
15595   unsigned DestReg = MI->getOperand(0).getReg();
15596   MachineOperand &Base = MI->getOperand(1);
15597   MachineOperand &Scale = MI->getOperand(2);
15598   MachineOperand &Index = MI->getOperand(3);
15599   MachineOperand &Disp = MI->getOperand(4);
15600   MachineOperand &Segment = MI->getOperand(5);
15601   unsigned ArgSize = MI->getOperand(6).getImm();
15602   unsigned ArgMode = MI->getOperand(7).getImm();
15603   unsigned Align = MI->getOperand(8).getImm();
15604
15605   // Memory Reference
15606   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15607   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15608   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15609
15610   // Machine Information
15611   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15612   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15613   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15614   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15615   DebugLoc DL = MI->getDebugLoc();
15616
15617   // struct va_list {
15618   //   i32   gp_offset
15619   //   i32   fp_offset
15620   //   i64   overflow_area (address)
15621   //   i64   reg_save_area (address)
15622   // }
15623   // sizeof(va_list) = 24
15624   // alignment(va_list) = 8
15625
15626   unsigned TotalNumIntRegs = 6;
15627   unsigned TotalNumXMMRegs = 8;
15628   bool UseGPOffset = (ArgMode == 1);
15629   bool UseFPOffset = (ArgMode == 2);
15630   unsigned MaxOffset = TotalNumIntRegs * 8 +
15631                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15632
15633   /* Align ArgSize to a multiple of 8 */
15634   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15635   bool NeedsAlign = (Align > 8);
15636
15637   MachineBasicBlock *thisMBB = MBB;
15638   MachineBasicBlock *overflowMBB;
15639   MachineBasicBlock *offsetMBB;
15640   MachineBasicBlock *endMBB;
15641
15642   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15643   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15644   unsigned OffsetReg = 0;
15645
15646   if (!UseGPOffset && !UseFPOffset) {
15647     // If we only pull from the overflow region, we don't create a branch.
15648     // We don't need to alter control flow.
15649     OffsetDestReg = 0; // unused
15650     OverflowDestReg = DestReg;
15651
15652     offsetMBB = NULL;
15653     overflowMBB = thisMBB;
15654     endMBB = thisMBB;
15655   } else {
15656     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15657     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15658     // If not, pull from overflow_area. (branch to overflowMBB)
15659     //
15660     //       thisMBB
15661     //         |     .
15662     //         |        .
15663     //     offsetMBB   overflowMBB
15664     //         |        .
15665     //         |     .
15666     //        endMBB
15667
15668     // Registers for the PHI in endMBB
15669     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15670     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15671
15672     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15673     MachineFunction *MF = MBB->getParent();
15674     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15675     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15676     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15677
15678     MachineFunction::iterator MBBIter = MBB;
15679     ++MBBIter;
15680
15681     // Insert the new basic blocks
15682     MF->insert(MBBIter, offsetMBB);
15683     MF->insert(MBBIter, overflowMBB);
15684     MF->insert(MBBIter, endMBB);
15685
15686     // Transfer the remainder of MBB and its successor edges to endMBB.
15687     endMBB->splice(endMBB->begin(), thisMBB,
15688                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15689     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15690
15691     // Make offsetMBB and overflowMBB successors of thisMBB
15692     thisMBB->addSuccessor(offsetMBB);
15693     thisMBB->addSuccessor(overflowMBB);
15694
15695     // endMBB is a successor of both offsetMBB and overflowMBB
15696     offsetMBB->addSuccessor(endMBB);
15697     overflowMBB->addSuccessor(endMBB);
15698
15699     // Load the offset value into a register
15700     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15701     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15702       .addOperand(Base)
15703       .addOperand(Scale)
15704       .addOperand(Index)
15705       .addDisp(Disp, UseFPOffset ? 4 : 0)
15706       .addOperand(Segment)
15707       .setMemRefs(MMOBegin, MMOEnd);
15708
15709     // Check if there is enough room left to pull this argument.
15710     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15711       .addReg(OffsetReg)
15712       .addImm(MaxOffset + 8 - ArgSizeA8);
15713
15714     // Branch to "overflowMBB" if offset >= max
15715     // Fall through to "offsetMBB" otherwise
15716     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15717       .addMBB(overflowMBB);
15718   }
15719
15720   // In offsetMBB, emit code to use the reg_save_area.
15721   if (offsetMBB) {
15722     assert(OffsetReg != 0);
15723
15724     // Read the reg_save_area address.
15725     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15726     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15727       .addOperand(Base)
15728       .addOperand(Scale)
15729       .addOperand(Index)
15730       .addDisp(Disp, 16)
15731       .addOperand(Segment)
15732       .setMemRefs(MMOBegin, MMOEnd);
15733
15734     // Zero-extend the offset
15735     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15736       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15737         .addImm(0)
15738         .addReg(OffsetReg)
15739         .addImm(X86::sub_32bit);
15740
15741     // Add the offset to the reg_save_area to get the final address.
15742     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15743       .addReg(OffsetReg64)
15744       .addReg(RegSaveReg);
15745
15746     // Compute the offset for the next argument
15747     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15748     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15749       .addReg(OffsetReg)
15750       .addImm(UseFPOffset ? 16 : 8);
15751
15752     // Store it back into the va_list.
15753     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15754       .addOperand(Base)
15755       .addOperand(Scale)
15756       .addOperand(Index)
15757       .addDisp(Disp, UseFPOffset ? 4 : 0)
15758       .addOperand(Segment)
15759       .addReg(NextOffsetReg)
15760       .setMemRefs(MMOBegin, MMOEnd);
15761
15762     // Jump to endMBB
15763     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15764       .addMBB(endMBB);
15765   }
15766
15767   //
15768   // Emit code to use overflow area
15769   //
15770
15771   // Load the overflow_area address into a register.
15772   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15773   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15774     .addOperand(Base)
15775     .addOperand(Scale)
15776     .addOperand(Index)
15777     .addDisp(Disp, 8)
15778     .addOperand(Segment)
15779     .setMemRefs(MMOBegin, MMOEnd);
15780
15781   // If we need to align it, do so. Otherwise, just copy the address
15782   // to OverflowDestReg.
15783   if (NeedsAlign) {
15784     // Align the overflow address
15785     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15786     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15787
15788     // aligned_addr = (addr + (align-1)) & ~(align-1)
15789     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15790       .addReg(OverflowAddrReg)
15791       .addImm(Align-1);
15792
15793     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15794       .addReg(TmpReg)
15795       .addImm(~(uint64_t)(Align-1));
15796   } else {
15797     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15798       .addReg(OverflowAddrReg);
15799   }
15800
15801   // Compute the next overflow address after this argument.
15802   // (the overflow address should be kept 8-byte aligned)
15803   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15804   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15805     .addReg(OverflowDestReg)
15806     .addImm(ArgSizeA8);
15807
15808   // Store the new overflow address.
15809   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15810     .addOperand(Base)
15811     .addOperand(Scale)
15812     .addOperand(Index)
15813     .addDisp(Disp, 8)
15814     .addOperand(Segment)
15815     .addReg(NextAddrReg)
15816     .setMemRefs(MMOBegin, MMOEnd);
15817
15818   // If we branched, emit the PHI to the front of endMBB.
15819   if (offsetMBB) {
15820     BuildMI(*endMBB, endMBB->begin(), DL,
15821             TII->get(X86::PHI), DestReg)
15822       .addReg(OffsetDestReg).addMBB(offsetMBB)
15823       .addReg(OverflowDestReg).addMBB(overflowMBB);
15824   }
15825
15826   // Erase the pseudo instruction
15827   MI->eraseFromParent();
15828
15829   return endMBB;
15830 }
15831
15832 MachineBasicBlock *
15833 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15834                                                  MachineInstr *MI,
15835                                                  MachineBasicBlock *MBB) const {
15836   // Emit code to save XMM registers to the stack. The ABI says that the
15837   // number of registers to save is given in %al, so it's theoretically
15838   // possible to do an indirect jump trick to avoid saving all of them,
15839   // however this code takes a simpler approach and just executes all
15840   // of the stores if %al is non-zero. It's less code, and it's probably
15841   // easier on the hardware branch predictor, and stores aren't all that
15842   // expensive anyway.
15843
15844   // Create the new basic blocks. One block contains all the XMM stores,
15845   // and one block is the final destination regardless of whether any
15846   // stores were performed.
15847   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15848   MachineFunction *F = MBB->getParent();
15849   MachineFunction::iterator MBBIter = MBB;
15850   ++MBBIter;
15851   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15852   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15853   F->insert(MBBIter, XMMSaveMBB);
15854   F->insert(MBBIter, EndMBB);
15855
15856   // Transfer the remainder of MBB and its successor edges to EndMBB.
15857   EndMBB->splice(EndMBB->begin(), MBB,
15858                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15859   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15860
15861   // The original block will now fall through to the XMM save block.
15862   MBB->addSuccessor(XMMSaveMBB);
15863   // The XMMSaveMBB will fall through to the end block.
15864   XMMSaveMBB->addSuccessor(EndMBB);
15865
15866   // Now add the instructions.
15867   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15868   DebugLoc DL = MI->getDebugLoc();
15869
15870   unsigned CountReg = MI->getOperand(0).getReg();
15871   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15872   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15873
15874   if (!Subtarget->isTargetWin64()) {
15875     // If %al is 0, branch around the XMM save block.
15876     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15877     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15878     MBB->addSuccessor(EndMBB);
15879   }
15880
15881   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15882   // that was just emitted, but clearly shouldn't be "saved".
15883   assert((MI->getNumOperands() <= 3 ||
15884           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15885           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15886          && "Expected last argument to be EFLAGS");
15887   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15888   // In the XMM save block, save all the XMM argument registers.
15889   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15890     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15891     MachineMemOperand *MMO =
15892       F->getMachineMemOperand(
15893           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15894         MachineMemOperand::MOStore,
15895         /*Size=*/16, /*Align=*/16);
15896     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15897       .addFrameIndex(RegSaveFrameIndex)
15898       .addImm(/*Scale=*/1)
15899       .addReg(/*IndexReg=*/0)
15900       .addImm(/*Disp=*/Offset)
15901       .addReg(/*Segment=*/0)
15902       .addReg(MI->getOperand(i).getReg())
15903       .addMemOperand(MMO);
15904   }
15905
15906   MI->eraseFromParent();   // The pseudo instruction is gone now.
15907
15908   return EndMBB;
15909 }
15910
15911 // The EFLAGS operand of SelectItr might be missing a kill marker
15912 // because there were multiple uses of EFLAGS, and ISel didn't know
15913 // which to mark. Figure out whether SelectItr should have had a
15914 // kill marker, and set it if it should. Returns the correct kill
15915 // marker value.
15916 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15917                                      MachineBasicBlock* BB,
15918                                      const TargetRegisterInfo* TRI) {
15919   // Scan forward through BB for a use/def of EFLAGS.
15920   MachineBasicBlock::iterator miI(std::next(SelectItr));
15921   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15922     const MachineInstr& mi = *miI;
15923     if (mi.readsRegister(X86::EFLAGS))
15924       return false;
15925     if (mi.definesRegister(X86::EFLAGS))
15926       break; // Should have kill-flag - update below.
15927   }
15928
15929   // If we hit the end of the block, check whether EFLAGS is live into a
15930   // successor.
15931   if (miI == BB->end()) {
15932     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15933                                           sEnd = BB->succ_end();
15934          sItr != sEnd; ++sItr) {
15935       MachineBasicBlock* succ = *sItr;
15936       if (succ->isLiveIn(X86::EFLAGS))
15937         return false;
15938     }
15939   }
15940
15941   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15942   // out. SelectMI should have a kill flag on EFLAGS.
15943   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15944   return true;
15945 }
15946
15947 MachineBasicBlock *
15948 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15949                                      MachineBasicBlock *BB) const {
15950   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15951   DebugLoc DL = MI->getDebugLoc();
15952
15953   // To "insert" a SELECT_CC instruction, we actually have to insert the
15954   // diamond control-flow pattern.  The incoming instruction knows the
15955   // destination vreg to set, the condition code register to branch on, the
15956   // true/false values to select between, and a branch opcode to use.
15957   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15958   MachineFunction::iterator It = BB;
15959   ++It;
15960
15961   //  thisMBB:
15962   //  ...
15963   //   TrueVal = ...
15964   //   cmpTY ccX, r1, r2
15965   //   bCC copy1MBB
15966   //   fallthrough --> copy0MBB
15967   MachineBasicBlock *thisMBB = BB;
15968   MachineFunction *F = BB->getParent();
15969   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15970   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15971   F->insert(It, copy0MBB);
15972   F->insert(It, sinkMBB);
15973
15974   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15975   // live into the sink and copy blocks.
15976   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15977   if (!MI->killsRegister(X86::EFLAGS) &&
15978       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15979     copy0MBB->addLiveIn(X86::EFLAGS);
15980     sinkMBB->addLiveIn(X86::EFLAGS);
15981   }
15982
15983   // Transfer the remainder of BB and its successor edges to sinkMBB.
15984   sinkMBB->splice(sinkMBB->begin(), BB,
15985                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
15986   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15987
15988   // Add the true and fallthrough blocks as its successors.
15989   BB->addSuccessor(copy0MBB);
15990   BB->addSuccessor(sinkMBB);
15991
15992   // Create the conditional branch instruction.
15993   unsigned Opc =
15994     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15995   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15996
15997   //  copy0MBB:
15998   //   %FalseValue = ...
15999   //   # fallthrough to sinkMBB
16000   copy0MBB->addSuccessor(sinkMBB);
16001
16002   //  sinkMBB:
16003   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16004   //  ...
16005   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16006           TII->get(X86::PHI), MI->getOperand(0).getReg())
16007     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16008     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16009
16010   MI->eraseFromParent();   // The pseudo instruction is gone now.
16011   return sinkMBB;
16012 }
16013
16014 MachineBasicBlock *
16015 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16016                                         bool Is64Bit) const {
16017   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16018   DebugLoc DL = MI->getDebugLoc();
16019   MachineFunction *MF = BB->getParent();
16020   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16021
16022   assert(MF->shouldSplitStack());
16023
16024   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16025   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16026
16027   // BB:
16028   //  ... [Till the alloca]
16029   // If stacklet is not large enough, jump to mallocMBB
16030   //
16031   // bumpMBB:
16032   //  Allocate by subtracting from RSP
16033   //  Jump to continueMBB
16034   //
16035   // mallocMBB:
16036   //  Allocate by call to runtime
16037   //
16038   // continueMBB:
16039   //  ...
16040   //  [rest of original BB]
16041   //
16042
16043   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16044   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16045   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16046
16047   MachineRegisterInfo &MRI = MF->getRegInfo();
16048   const TargetRegisterClass *AddrRegClass =
16049     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16050
16051   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16052     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16053     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16054     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16055     sizeVReg = MI->getOperand(1).getReg(),
16056     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16057
16058   MachineFunction::iterator MBBIter = BB;
16059   ++MBBIter;
16060
16061   MF->insert(MBBIter, bumpMBB);
16062   MF->insert(MBBIter, mallocMBB);
16063   MF->insert(MBBIter, continueMBB);
16064
16065   continueMBB->splice(continueMBB->begin(), BB,
16066                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16067   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16068
16069   // Add code to the main basic block to check if the stack limit has been hit,
16070   // and if so, jump to mallocMBB otherwise to bumpMBB.
16071   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16072   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16073     .addReg(tmpSPVReg).addReg(sizeVReg);
16074   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16075     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16076     .addReg(SPLimitVReg);
16077   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16078
16079   // bumpMBB simply decreases the stack pointer, since we know the current
16080   // stacklet has enough space.
16081   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16082     .addReg(SPLimitVReg);
16083   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16084     .addReg(SPLimitVReg);
16085   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16086
16087   // Calls into a routine in libgcc to allocate more space from the heap.
16088   const uint32_t *RegMask =
16089     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16090   if (Is64Bit) {
16091     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16092       .addReg(sizeVReg);
16093     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16094       .addExternalSymbol("__morestack_allocate_stack_space")
16095       .addRegMask(RegMask)
16096       .addReg(X86::RDI, RegState::Implicit)
16097       .addReg(X86::RAX, RegState::ImplicitDefine);
16098   } else {
16099     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16100       .addImm(12);
16101     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16102     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16103       .addExternalSymbol("__morestack_allocate_stack_space")
16104       .addRegMask(RegMask)
16105       .addReg(X86::EAX, RegState::ImplicitDefine);
16106   }
16107
16108   if (!Is64Bit)
16109     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16110       .addImm(16);
16111
16112   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16113     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16114   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16115
16116   // Set up the CFG correctly.
16117   BB->addSuccessor(bumpMBB);
16118   BB->addSuccessor(mallocMBB);
16119   mallocMBB->addSuccessor(continueMBB);
16120   bumpMBB->addSuccessor(continueMBB);
16121
16122   // Take care of the PHI nodes.
16123   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16124           MI->getOperand(0).getReg())
16125     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16126     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16127
16128   // Delete the original pseudo instruction.
16129   MI->eraseFromParent();
16130
16131   // And we're done.
16132   return continueMBB;
16133 }
16134
16135 MachineBasicBlock *
16136 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16137                                           MachineBasicBlock *BB) const {
16138   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16139   DebugLoc DL = MI->getDebugLoc();
16140
16141   assert(!Subtarget->isTargetMacho());
16142
16143   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16144   // non-trivial part is impdef of ESP.
16145
16146   if (Subtarget->isTargetWin64()) {
16147     if (Subtarget->isTargetCygMing()) {
16148       // ___chkstk(Mingw64):
16149       // Clobbers R10, R11, RAX and EFLAGS.
16150       // Updates RSP.
16151       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16152         .addExternalSymbol("___chkstk")
16153         .addReg(X86::RAX, RegState::Implicit)
16154         .addReg(X86::RSP, RegState::Implicit)
16155         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16156         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16157         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16158     } else {
16159       // __chkstk(MSVCRT): does not update stack pointer.
16160       // Clobbers R10, R11 and EFLAGS.
16161       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16162         .addExternalSymbol("__chkstk")
16163         .addReg(X86::RAX, RegState::Implicit)
16164         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16165       // RAX has the offset to be subtracted from RSP.
16166       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16167         .addReg(X86::RSP)
16168         .addReg(X86::RAX);
16169     }
16170   } else {
16171     const char *StackProbeSymbol =
16172       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16173
16174     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16175       .addExternalSymbol(StackProbeSymbol)
16176       .addReg(X86::EAX, RegState::Implicit)
16177       .addReg(X86::ESP, RegState::Implicit)
16178       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16179       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16180       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16181   }
16182
16183   MI->eraseFromParent();   // The pseudo instruction is gone now.
16184   return BB;
16185 }
16186
16187 MachineBasicBlock *
16188 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16189                                       MachineBasicBlock *BB) const {
16190   // This is pretty easy.  We're taking the value that we received from
16191   // our load from the relocation, sticking it in either RDI (x86-64)
16192   // or EAX and doing an indirect call.  The return value will then
16193   // be in the normal return register.
16194   const X86InstrInfo *TII
16195     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16196   DebugLoc DL = MI->getDebugLoc();
16197   MachineFunction *F = BB->getParent();
16198
16199   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16200   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16201
16202   // Get a register mask for the lowered call.
16203   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16204   // proper register mask.
16205   const uint32_t *RegMask =
16206     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16207   if (Subtarget->is64Bit()) {
16208     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16209                                       TII->get(X86::MOV64rm), X86::RDI)
16210     .addReg(X86::RIP)
16211     .addImm(0).addReg(0)
16212     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16213                       MI->getOperand(3).getTargetFlags())
16214     .addReg(0);
16215     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16216     addDirectMem(MIB, X86::RDI);
16217     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16218   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16219     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16220                                       TII->get(X86::MOV32rm), X86::EAX)
16221     .addReg(0)
16222     .addImm(0).addReg(0)
16223     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16224                       MI->getOperand(3).getTargetFlags())
16225     .addReg(0);
16226     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16227     addDirectMem(MIB, X86::EAX);
16228     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16229   } else {
16230     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16231                                       TII->get(X86::MOV32rm), X86::EAX)
16232     .addReg(TII->getGlobalBaseReg(F))
16233     .addImm(0).addReg(0)
16234     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16235                       MI->getOperand(3).getTargetFlags())
16236     .addReg(0);
16237     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16238     addDirectMem(MIB, X86::EAX);
16239     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16240   }
16241
16242   MI->eraseFromParent(); // The pseudo instruction is gone now.
16243   return BB;
16244 }
16245
16246 MachineBasicBlock *
16247 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16248                                     MachineBasicBlock *MBB) const {
16249   DebugLoc DL = MI->getDebugLoc();
16250   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16251
16252   MachineFunction *MF = MBB->getParent();
16253   MachineRegisterInfo &MRI = MF->getRegInfo();
16254
16255   const BasicBlock *BB = MBB->getBasicBlock();
16256   MachineFunction::iterator I = MBB;
16257   ++I;
16258
16259   // Memory Reference
16260   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16261   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16262
16263   unsigned DstReg;
16264   unsigned MemOpndSlot = 0;
16265
16266   unsigned CurOp = 0;
16267
16268   DstReg = MI->getOperand(CurOp++).getReg();
16269   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16270   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16271   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16272   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16273
16274   MemOpndSlot = CurOp;
16275
16276   MVT PVT = getPointerTy();
16277   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16278          "Invalid Pointer Size!");
16279
16280   // For v = setjmp(buf), we generate
16281   //
16282   // thisMBB:
16283   //  buf[LabelOffset] = restoreMBB
16284   //  SjLjSetup restoreMBB
16285   //
16286   // mainMBB:
16287   //  v_main = 0
16288   //
16289   // sinkMBB:
16290   //  v = phi(main, restore)
16291   //
16292   // restoreMBB:
16293   //  v_restore = 1
16294
16295   MachineBasicBlock *thisMBB = MBB;
16296   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16297   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16298   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16299   MF->insert(I, mainMBB);
16300   MF->insert(I, sinkMBB);
16301   MF->push_back(restoreMBB);
16302
16303   MachineInstrBuilder MIB;
16304
16305   // Transfer the remainder of BB and its successor edges to sinkMBB.
16306   sinkMBB->splice(sinkMBB->begin(), MBB,
16307                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16308   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16309
16310   // thisMBB:
16311   unsigned PtrStoreOpc = 0;
16312   unsigned LabelReg = 0;
16313   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16314   Reloc::Model RM = getTargetMachine().getRelocationModel();
16315   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16316                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16317
16318   // Prepare IP either in reg or imm.
16319   if (!UseImmLabel) {
16320     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16321     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16322     LabelReg = MRI.createVirtualRegister(PtrRC);
16323     if (Subtarget->is64Bit()) {
16324       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16325               .addReg(X86::RIP)
16326               .addImm(0)
16327               .addReg(0)
16328               .addMBB(restoreMBB)
16329               .addReg(0);
16330     } else {
16331       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16332       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16333               .addReg(XII->getGlobalBaseReg(MF))
16334               .addImm(0)
16335               .addReg(0)
16336               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16337               .addReg(0);
16338     }
16339   } else
16340     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16341   // Store IP
16342   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16343   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16344     if (i == X86::AddrDisp)
16345       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16346     else
16347       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16348   }
16349   if (!UseImmLabel)
16350     MIB.addReg(LabelReg);
16351   else
16352     MIB.addMBB(restoreMBB);
16353   MIB.setMemRefs(MMOBegin, MMOEnd);
16354   // Setup
16355   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16356           .addMBB(restoreMBB);
16357
16358   const X86RegisterInfo *RegInfo =
16359     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16360   MIB.addRegMask(RegInfo->getNoPreservedMask());
16361   thisMBB->addSuccessor(mainMBB);
16362   thisMBB->addSuccessor(restoreMBB);
16363
16364   // mainMBB:
16365   //  EAX = 0
16366   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16367   mainMBB->addSuccessor(sinkMBB);
16368
16369   // sinkMBB:
16370   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16371           TII->get(X86::PHI), DstReg)
16372     .addReg(mainDstReg).addMBB(mainMBB)
16373     .addReg(restoreDstReg).addMBB(restoreMBB);
16374
16375   // restoreMBB:
16376   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16377   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16378   restoreMBB->addSuccessor(sinkMBB);
16379
16380   MI->eraseFromParent();
16381   return sinkMBB;
16382 }
16383
16384 MachineBasicBlock *
16385 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16386                                      MachineBasicBlock *MBB) const {
16387   DebugLoc DL = MI->getDebugLoc();
16388   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16389
16390   MachineFunction *MF = MBB->getParent();
16391   MachineRegisterInfo &MRI = MF->getRegInfo();
16392
16393   // Memory Reference
16394   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16395   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16396
16397   MVT PVT = getPointerTy();
16398   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16399          "Invalid Pointer Size!");
16400
16401   const TargetRegisterClass *RC =
16402     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16403   unsigned Tmp = MRI.createVirtualRegister(RC);
16404   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16405   const X86RegisterInfo *RegInfo =
16406     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16407   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16408   unsigned SP = RegInfo->getStackRegister();
16409
16410   MachineInstrBuilder MIB;
16411
16412   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16413   const int64_t SPOffset = 2 * PVT.getStoreSize();
16414
16415   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16416   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16417
16418   // Reload FP
16419   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16420   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16421     MIB.addOperand(MI->getOperand(i));
16422   MIB.setMemRefs(MMOBegin, MMOEnd);
16423   // Reload IP
16424   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16425   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16426     if (i == X86::AddrDisp)
16427       MIB.addDisp(MI->getOperand(i), LabelOffset);
16428     else
16429       MIB.addOperand(MI->getOperand(i));
16430   }
16431   MIB.setMemRefs(MMOBegin, MMOEnd);
16432   // Reload SP
16433   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16434   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16435     if (i == X86::AddrDisp)
16436       MIB.addDisp(MI->getOperand(i), SPOffset);
16437     else
16438       MIB.addOperand(MI->getOperand(i));
16439   }
16440   MIB.setMemRefs(MMOBegin, MMOEnd);
16441   // Jump
16442   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16443
16444   MI->eraseFromParent();
16445   return MBB;
16446 }
16447
16448 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16449 // accumulator loops. Writing back to the accumulator allows the coalescer
16450 // to remove extra copies in the loop.   
16451 MachineBasicBlock *
16452 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16453                                  MachineBasicBlock *MBB) const {
16454   MachineOperand &AddendOp = MI->getOperand(3);
16455
16456   // Bail out early if the addend isn't a register - we can't switch these.
16457   if (!AddendOp.isReg())
16458     return MBB;
16459
16460   MachineFunction &MF = *MBB->getParent();
16461   MachineRegisterInfo &MRI = MF.getRegInfo();
16462
16463   // Check whether the addend is defined by a PHI:
16464   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16465   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16466   if (!AddendDef.isPHI())
16467     return MBB;
16468
16469   // Look for the following pattern:
16470   // loop:
16471   //   %addend = phi [%entry, 0], [%loop, %result]
16472   //   ...
16473   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16474
16475   // Replace with:
16476   //   loop:
16477   //   %addend = phi [%entry, 0], [%loop, %result]
16478   //   ...
16479   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16480
16481   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16482     assert(AddendDef.getOperand(i).isReg());
16483     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16484     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16485     if (&PHISrcInst == MI) {
16486       // Found a matching instruction.
16487       unsigned NewFMAOpc = 0;
16488       switch (MI->getOpcode()) {
16489         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16490         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16491         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16492         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16493         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16494         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16495         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16496         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16497         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16498         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16499         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16500         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16501         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16502         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16503         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16504         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16505         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16506         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16507         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16508         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16509         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16510         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16511         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16512         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16513         default: llvm_unreachable("Unrecognized FMA variant.");
16514       }
16515
16516       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16517       MachineInstrBuilder MIB =
16518         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16519         .addOperand(MI->getOperand(0))
16520         .addOperand(MI->getOperand(3))
16521         .addOperand(MI->getOperand(2))
16522         .addOperand(MI->getOperand(1));
16523       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16524       MI->eraseFromParent();
16525     }
16526   }
16527
16528   return MBB;
16529 }
16530
16531 MachineBasicBlock *
16532 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16533                                                MachineBasicBlock *BB) const {
16534   switch (MI->getOpcode()) {
16535   default: llvm_unreachable("Unexpected instr type to insert");
16536   case X86::TAILJMPd64:
16537   case X86::TAILJMPr64:
16538   case X86::TAILJMPm64:
16539     llvm_unreachable("TAILJMP64 would not be touched here.");
16540   case X86::TCRETURNdi64:
16541   case X86::TCRETURNri64:
16542   case X86::TCRETURNmi64:
16543     return BB;
16544   case X86::WIN_ALLOCA:
16545     return EmitLoweredWinAlloca(MI, BB);
16546   case X86::SEG_ALLOCA_32:
16547     return EmitLoweredSegAlloca(MI, BB, false);
16548   case X86::SEG_ALLOCA_64:
16549     return EmitLoweredSegAlloca(MI, BB, true);
16550   case X86::TLSCall_32:
16551   case X86::TLSCall_64:
16552     return EmitLoweredTLSCall(MI, BB);
16553   case X86::CMOV_GR8:
16554   case X86::CMOV_FR32:
16555   case X86::CMOV_FR64:
16556   case X86::CMOV_V4F32:
16557   case X86::CMOV_V2F64:
16558   case X86::CMOV_V2I64:
16559   case X86::CMOV_V8F32:
16560   case X86::CMOV_V4F64:
16561   case X86::CMOV_V4I64:
16562   case X86::CMOV_V16F32:
16563   case X86::CMOV_V8F64:
16564   case X86::CMOV_V8I64:
16565   case X86::CMOV_GR16:
16566   case X86::CMOV_GR32:
16567   case X86::CMOV_RFP32:
16568   case X86::CMOV_RFP64:
16569   case X86::CMOV_RFP80:
16570     return EmitLoweredSelect(MI, BB);
16571
16572   case X86::FP32_TO_INT16_IN_MEM:
16573   case X86::FP32_TO_INT32_IN_MEM:
16574   case X86::FP32_TO_INT64_IN_MEM:
16575   case X86::FP64_TO_INT16_IN_MEM:
16576   case X86::FP64_TO_INT32_IN_MEM:
16577   case X86::FP64_TO_INT64_IN_MEM:
16578   case X86::FP80_TO_INT16_IN_MEM:
16579   case X86::FP80_TO_INT32_IN_MEM:
16580   case X86::FP80_TO_INT64_IN_MEM: {
16581     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16582     DebugLoc DL = MI->getDebugLoc();
16583
16584     // Change the floating point control register to use "round towards zero"
16585     // mode when truncating to an integer value.
16586     MachineFunction *F = BB->getParent();
16587     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16588     addFrameReference(BuildMI(*BB, MI, DL,
16589                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16590
16591     // Load the old value of the high byte of the control word...
16592     unsigned OldCW =
16593       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16594     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16595                       CWFrameIdx);
16596
16597     // Set the high part to be round to zero...
16598     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16599       .addImm(0xC7F);
16600
16601     // Reload the modified control word now...
16602     addFrameReference(BuildMI(*BB, MI, DL,
16603                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16604
16605     // Restore the memory image of control word to original value
16606     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16607       .addReg(OldCW);
16608
16609     // Get the X86 opcode to use.
16610     unsigned Opc;
16611     switch (MI->getOpcode()) {
16612     default: llvm_unreachable("illegal opcode!");
16613     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16614     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16615     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16616     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16617     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16618     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16619     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16620     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16621     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16622     }
16623
16624     X86AddressMode AM;
16625     MachineOperand &Op = MI->getOperand(0);
16626     if (Op.isReg()) {
16627       AM.BaseType = X86AddressMode::RegBase;
16628       AM.Base.Reg = Op.getReg();
16629     } else {
16630       AM.BaseType = X86AddressMode::FrameIndexBase;
16631       AM.Base.FrameIndex = Op.getIndex();
16632     }
16633     Op = MI->getOperand(1);
16634     if (Op.isImm())
16635       AM.Scale = Op.getImm();
16636     Op = MI->getOperand(2);
16637     if (Op.isImm())
16638       AM.IndexReg = Op.getImm();
16639     Op = MI->getOperand(3);
16640     if (Op.isGlobal()) {
16641       AM.GV = Op.getGlobal();
16642     } else {
16643       AM.Disp = Op.getImm();
16644     }
16645     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16646                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16647
16648     // Reload the original control word now.
16649     addFrameReference(BuildMI(*BB, MI, DL,
16650                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16651
16652     MI->eraseFromParent();   // The pseudo instruction is gone now.
16653     return BB;
16654   }
16655     // String/text processing lowering.
16656   case X86::PCMPISTRM128REG:
16657   case X86::VPCMPISTRM128REG:
16658   case X86::PCMPISTRM128MEM:
16659   case X86::VPCMPISTRM128MEM:
16660   case X86::PCMPESTRM128REG:
16661   case X86::VPCMPESTRM128REG:
16662   case X86::PCMPESTRM128MEM:
16663   case X86::VPCMPESTRM128MEM:
16664     assert(Subtarget->hasSSE42() &&
16665            "Target must have SSE4.2 or AVX features enabled");
16666     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16667
16668   // String/text processing lowering.
16669   case X86::PCMPISTRIREG:
16670   case X86::VPCMPISTRIREG:
16671   case X86::PCMPISTRIMEM:
16672   case X86::VPCMPISTRIMEM:
16673   case X86::PCMPESTRIREG:
16674   case X86::VPCMPESTRIREG:
16675   case X86::PCMPESTRIMEM:
16676   case X86::VPCMPESTRIMEM:
16677     assert(Subtarget->hasSSE42() &&
16678            "Target must have SSE4.2 or AVX features enabled");
16679     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16680
16681   // Thread synchronization.
16682   case X86::MONITOR:
16683     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16684
16685   // xbegin
16686   case X86::XBEGIN:
16687     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16688
16689   // Atomic Lowering.
16690   case X86::ATOMAND8:
16691   case X86::ATOMAND16:
16692   case X86::ATOMAND32:
16693   case X86::ATOMAND64:
16694     // Fall through
16695   case X86::ATOMOR8:
16696   case X86::ATOMOR16:
16697   case X86::ATOMOR32:
16698   case X86::ATOMOR64:
16699     // Fall through
16700   case X86::ATOMXOR16:
16701   case X86::ATOMXOR8:
16702   case X86::ATOMXOR32:
16703   case X86::ATOMXOR64:
16704     // Fall through
16705   case X86::ATOMNAND8:
16706   case X86::ATOMNAND16:
16707   case X86::ATOMNAND32:
16708   case X86::ATOMNAND64:
16709     // Fall through
16710   case X86::ATOMMAX8:
16711   case X86::ATOMMAX16:
16712   case X86::ATOMMAX32:
16713   case X86::ATOMMAX64:
16714     // Fall through
16715   case X86::ATOMMIN8:
16716   case X86::ATOMMIN16:
16717   case X86::ATOMMIN32:
16718   case X86::ATOMMIN64:
16719     // Fall through
16720   case X86::ATOMUMAX8:
16721   case X86::ATOMUMAX16:
16722   case X86::ATOMUMAX32:
16723   case X86::ATOMUMAX64:
16724     // Fall through
16725   case X86::ATOMUMIN8:
16726   case X86::ATOMUMIN16:
16727   case X86::ATOMUMIN32:
16728   case X86::ATOMUMIN64:
16729     return EmitAtomicLoadArith(MI, BB);
16730
16731   // This group does 64-bit operations on a 32-bit host.
16732   case X86::ATOMAND6432:
16733   case X86::ATOMOR6432:
16734   case X86::ATOMXOR6432:
16735   case X86::ATOMNAND6432:
16736   case X86::ATOMADD6432:
16737   case X86::ATOMSUB6432:
16738   case X86::ATOMMAX6432:
16739   case X86::ATOMMIN6432:
16740   case X86::ATOMUMAX6432:
16741   case X86::ATOMUMIN6432:
16742   case X86::ATOMSWAP6432:
16743     return EmitAtomicLoadArith6432(MI, BB);
16744
16745   case X86::VASTART_SAVE_XMM_REGS:
16746     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16747
16748   case X86::VAARG_64:
16749     return EmitVAARG64WithCustomInserter(MI, BB);
16750
16751   case X86::EH_SjLj_SetJmp32:
16752   case X86::EH_SjLj_SetJmp64:
16753     return emitEHSjLjSetJmp(MI, BB);
16754
16755   case X86::EH_SjLj_LongJmp32:
16756   case X86::EH_SjLj_LongJmp64:
16757     return emitEHSjLjLongJmp(MI, BB);
16758
16759   case TargetOpcode::STACKMAP:
16760   case TargetOpcode::PATCHPOINT:
16761     return emitPatchPoint(MI, BB);
16762
16763   case X86::VFMADDPDr213r:
16764   case X86::VFMADDPSr213r:
16765   case X86::VFMADDSDr213r:
16766   case X86::VFMADDSSr213r:
16767   case X86::VFMSUBPDr213r:
16768   case X86::VFMSUBPSr213r:
16769   case X86::VFMSUBSDr213r:
16770   case X86::VFMSUBSSr213r:
16771   case X86::VFNMADDPDr213r:
16772   case X86::VFNMADDPSr213r:
16773   case X86::VFNMADDSDr213r:
16774   case X86::VFNMADDSSr213r:
16775   case X86::VFNMSUBPDr213r:
16776   case X86::VFNMSUBPSr213r:
16777   case X86::VFNMSUBSDr213r:
16778   case X86::VFNMSUBSSr213r:
16779   case X86::VFMADDPDr213rY:
16780   case X86::VFMADDPSr213rY:
16781   case X86::VFMSUBPDr213rY:
16782   case X86::VFMSUBPSr213rY:
16783   case X86::VFNMADDPDr213rY:
16784   case X86::VFNMADDPSr213rY:
16785   case X86::VFNMSUBPDr213rY:
16786   case X86::VFNMSUBPSr213rY:
16787     return emitFMA3Instr(MI, BB);
16788   }
16789 }
16790
16791 //===----------------------------------------------------------------------===//
16792 //                           X86 Optimization Hooks
16793 //===----------------------------------------------------------------------===//
16794
16795 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16796                                                        APInt &KnownZero,
16797                                                        APInt &KnownOne,
16798                                                        const SelectionDAG &DAG,
16799                                                        unsigned Depth) const {
16800   unsigned BitWidth = KnownZero.getBitWidth();
16801   unsigned Opc = Op.getOpcode();
16802   assert((Opc >= ISD::BUILTIN_OP_END ||
16803           Opc == ISD::INTRINSIC_WO_CHAIN ||
16804           Opc == ISD::INTRINSIC_W_CHAIN ||
16805           Opc == ISD::INTRINSIC_VOID) &&
16806          "Should use MaskedValueIsZero if you don't know whether Op"
16807          " is a target node!");
16808
16809   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16810   switch (Opc) {
16811   default: break;
16812   case X86ISD::ADD:
16813   case X86ISD::SUB:
16814   case X86ISD::ADC:
16815   case X86ISD::SBB:
16816   case X86ISD::SMUL:
16817   case X86ISD::UMUL:
16818   case X86ISD::INC:
16819   case X86ISD::DEC:
16820   case X86ISD::OR:
16821   case X86ISD::XOR:
16822   case X86ISD::AND:
16823     // These nodes' second result is a boolean.
16824     if (Op.getResNo() == 0)
16825       break;
16826     // Fallthrough
16827   case X86ISD::SETCC:
16828     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16829     break;
16830   case ISD::INTRINSIC_WO_CHAIN: {
16831     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16832     unsigned NumLoBits = 0;
16833     switch (IntId) {
16834     default: break;
16835     case Intrinsic::x86_sse_movmsk_ps:
16836     case Intrinsic::x86_avx_movmsk_ps_256:
16837     case Intrinsic::x86_sse2_movmsk_pd:
16838     case Intrinsic::x86_avx_movmsk_pd_256:
16839     case Intrinsic::x86_mmx_pmovmskb:
16840     case Intrinsic::x86_sse2_pmovmskb_128:
16841     case Intrinsic::x86_avx2_pmovmskb: {
16842       // High bits of movmskp{s|d}, pmovmskb are known zero.
16843       switch (IntId) {
16844         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16845         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16846         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16847         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16848         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16849         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16850         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16851         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16852       }
16853       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16854       break;
16855     }
16856     }
16857     break;
16858   }
16859   }
16860 }
16861
16862 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16863   SDValue Op,
16864   const SelectionDAG &,
16865   unsigned Depth) const {
16866   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16867   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16868     return Op.getValueType().getScalarType().getSizeInBits();
16869
16870   // Fallback case.
16871   return 1;
16872 }
16873
16874 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16875 /// node is a GlobalAddress + offset.
16876 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16877                                        const GlobalValue* &GA,
16878                                        int64_t &Offset) const {
16879   if (N->getOpcode() == X86ISD::Wrapper) {
16880     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16881       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16882       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16883       return true;
16884     }
16885   }
16886   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16887 }
16888
16889 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16890 /// same as extracting the high 128-bit part of 256-bit vector and then
16891 /// inserting the result into the low part of a new 256-bit vector
16892 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16893   EVT VT = SVOp->getValueType(0);
16894   unsigned NumElems = VT.getVectorNumElements();
16895
16896   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16897   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16898     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16899         SVOp->getMaskElt(j) >= 0)
16900       return false;
16901
16902   return true;
16903 }
16904
16905 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16906 /// same as extracting the low 128-bit part of 256-bit vector and then
16907 /// inserting the result into the high part of a new 256-bit vector
16908 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16909   EVT VT = SVOp->getValueType(0);
16910   unsigned NumElems = VT.getVectorNumElements();
16911
16912   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16913   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16914     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16915         SVOp->getMaskElt(j) >= 0)
16916       return false;
16917
16918   return true;
16919 }
16920
16921 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16922 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16923                                         TargetLowering::DAGCombinerInfo &DCI,
16924                                         const X86Subtarget* Subtarget) {
16925   SDLoc dl(N);
16926   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16927   SDValue V1 = SVOp->getOperand(0);
16928   SDValue V2 = SVOp->getOperand(1);
16929   EVT VT = SVOp->getValueType(0);
16930   unsigned NumElems = VT.getVectorNumElements();
16931
16932   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16933       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16934     //
16935     //                   0,0,0,...
16936     //                      |
16937     //    V      UNDEF    BUILD_VECTOR    UNDEF
16938     //     \      /           \           /
16939     //  CONCAT_VECTOR         CONCAT_VECTOR
16940     //         \                  /
16941     //          \                /
16942     //          RESULT: V + zero extended
16943     //
16944     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16945         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16946         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16947       return SDValue();
16948
16949     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16950       return SDValue();
16951
16952     // To match the shuffle mask, the first half of the mask should
16953     // be exactly the first vector, and all the rest a splat with the
16954     // first element of the second one.
16955     for (unsigned i = 0; i != NumElems/2; ++i)
16956       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16957           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16958         return SDValue();
16959
16960     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16961     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16962       if (Ld->hasNUsesOfValue(1, 0)) {
16963         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16964         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16965         SDValue ResNode =
16966           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16967                                   array_lengthof(Ops),
16968                                   Ld->getMemoryVT(),
16969                                   Ld->getPointerInfo(),
16970                                   Ld->getAlignment(),
16971                                   false/*isVolatile*/, true/*ReadMem*/,
16972                                   false/*WriteMem*/);
16973
16974         // Make sure the newly-created LOAD is in the same position as Ld in
16975         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16976         // and update uses of Ld's output chain to use the TokenFactor.
16977         if (Ld->hasAnyUseOfValue(1)) {
16978           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16979                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16980           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16981           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16982                                  SDValue(ResNode.getNode(), 1));
16983         }
16984
16985         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16986       }
16987     }
16988
16989     // Emit a zeroed vector and insert the desired subvector on its
16990     // first half.
16991     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16992     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16993     return DCI.CombineTo(N, InsV);
16994   }
16995
16996   //===--------------------------------------------------------------------===//
16997   // Combine some shuffles into subvector extracts and inserts:
16998   //
16999
17000   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17001   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17002     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17003     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17004     return DCI.CombineTo(N, InsV);
17005   }
17006
17007   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17008   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17009     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17010     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17011     return DCI.CombineTo(N, InsV);
17012   }
17013
17014   return SDValue();
17015 }
17016
17017 /// PerformShuffleCombine - Performs several different shuffle combines.
17018 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17019                                      TargetLowering::DAGCombinerInfo &DCI,
17020                                      const X86Subtarget *Subtarget) {
17021   SDLoc dl(N);
17022   EVT VT = N->getValueType(0);
17023
17024   // Don't create instructions with illegal types after legalize types has run.
17025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17026   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17027     return SDValue();
17028
17029   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17030   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17031       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17032     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17033
17034   // Only handle 128 wide vector from here on.
17035   if (!VT.is128BitVector())
17036     return SDValue();
17037
17038   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17039   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17040   // consecutive, non-overlapping, and in the right order.
17041   SmallVector<SDValue, 16> Elts;
17042   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17043     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17044
17045   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17046 }
17047
17048 /// PerformTruncateCombine - Converts truncate operation to
17049 /// a sequence of vector shuffle operations.
17050 /// It is possible when we truncate 256-bit vector to 128-bit vector
17051 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17052                                       TargetLowering::DAGCombinerInfo &DCI,
17053                                       const X86Subtarget *Subtarget)  {
17054   return SDValue();
17055 }
17056
17057 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17058 /// specific shuffle of a load can be folded into a single element load.
17059 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17060 /// shuffles have been customed lowered so we need to handle those here.
17061 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17062                                          TargetLowering::DAGCombinerInfo &DCI) {
17063   if (DCI.isBeforeLegalizeOps())
17064     return SDValue();
17065
17066   SDValue InVec = N->getOperand(0);
17067   SDValue EltNo = N->getOperand(1);
17068
17069   if (!isa<ConstantSDNode>(EltNo))
17070     return SDValue();
17071
17072   EVT VT = InVec.getValueType();
17073
17074   bool HasShuffleIntoBitcast = false;
17075   if (InVec.getOpcode() == ISD::BITCAST) {
17076     // Don't duplicate a load with other uses.
17077     if (!InVec.hasOneUse())
17078       return SDValue();
17079     EVT BCVT = InVec.getOperand(0).getValueType();
17080     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17081       return SDValue();
17082     InVec = InVec.getOperand(0);
17083     HasShuffleIntoBitcast = true;
17084   }
17085
17086   if (!isTargetShuffle(InVec.getOpcode()))
17087     return SDValue();
17088
17089   // Don't duplicate a load with other uses.
17090   if (!InVec.hasOneUse())
17091     return SDValue();
17092
17093   SmallVector<int, 16> ShuffleMask;
17094   bool UnaryShuffle;
17095   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17096                             UnaryShuffle))
17097     return SDValue();
17098
17099   // Select the input vector, guarding against out of range extract vector.
17100   unsigned NumElems = VT.getVectorNumElements();
17101   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17102   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17103   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17104                                          : InVec.getOperand(1);
17105
17106   // If inputs to shuffle are the same for both ops, then allow 2 uses
17107   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17108
17109   if (LdNode.getOpcode() == ISD::BITCAST) {
17110     // Don't duplicate a load with other uses.
17111     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17112       return SDValue();
17113
17114     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17115     LdNode = LdNode.getOperand(0);
17116   }
17117
17118   if (!ISD::isNormalLoad(LdNode.getNode()))
17119     return SDValue();
17120
17121   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17122
17123   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17124     return SDValue();
17125
17126   if (HasShuffleIntoBitcast) {
17127     // If there's a bitcast before the shuffle, check if the load type and
17128     // alignment is valid.
17129     unsigned Align = LN0->getAlignment();
17130     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17131     unsigned NewAlign = TLI.getDataLayout()->
17132       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17133
17134     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17135       return SDValue();
17136   }
17137
17138   // All checks match so transform back to vector_shuffle so that DAG combiner
17139   // can finish the job
17140   SDLoc dl(N);
17141
17142   // Create shuffle node taking into account the case that its a unary shuffle
17143   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17144   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17145                                  InVec.getOperand(0), Shuffle,
17146                                  &ShuffleMask[0]);
17147   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17148   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17149                      EltNo);
17150 }
17151
17152 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17153 /// generation and convert it from being a bunch of shuffles and extracts
17154 /// to a simple store and scalar loads to extract the elements.
17155 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17156                                          TargetLowering::DAGCombinerInfo &DCI) {
17157   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17158   if (NewOp.getNode())
17159     return NewOp;
17160
17161   SDValue InputVector = N->getOperand(0);
17162
17163   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17164   // from mmx to v2i32 has a single usage.
17165   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17166       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17167       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17168     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17169                        N->getValueType(0),
17170                        InputVector.getNode()->getOperand(0));
17171
17172   // Only operate on vectors of 4 elements, where the alternative shuffling
17173   // gets to be more expensive.
17174   if (InputVector.getValueType() != MVT::v4i32)
17175     return SDValue();
17176
17177   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17178   // single use which is a sign-extend or zero-extend, and all elements are
17179   // used.
17180   SmallVector<SDNode *, 4> Uses;
17181   unsigned ExtractedElements = 0;
17182   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17183        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17184     if (UI.getUse().getResNo() != InputVector.getResNo())
17185       return SDValue();
17186
17187     SDNode *Extract = *UI;
17188     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17189       return SDValue();
17190
17191     if (Extract->getValueType(0) != MVT::i32)
17192       return SDValue();
17193     if (!Extract->hasOneUse())
17194       return SDValue();
17195     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17196         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17197       return SDValue();
17198     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17199       return SDValue();
17200
17201     // Record which element was extracted.
17202     ExtractedElements |=
17203       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17204
17205     Uses.push_back(Extract);
17206   }
17207
17208   // If not all the elements were used, this may not be worthwhile.
17209   if (ExtractedElements != 15)
17210     return SDValue();
17211
17212   // Ok, we've now decided to do the transformation.
17213   SDLoc dl(InputVector);
17214
17215   // Store the value to a temporary stack slot.
17216   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17217   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17218                             MachinePointerInfo(), false, false, 0);
17219
17220   // Replace each use (extract) with a load of the appropriate element.
17221   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17222        UE = Uses.end(); UI != UE; ++UI) {
17223     SDNode *Extract = *UI;
17224
17225     // cOMpute the element's address.
17226     SDValue Idx = Extract->getOperand(1);
17227     unsigned EltSize =
17228         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17229     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17230     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17231     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17232
17233     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17234                                      StackPtr, OffsetVal);
17235
17236     // Load the scalar.
17237     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17238                                      ScalarAddr, MachinePointerInfo(),
17239                                      false, false, false, 0);
17240
17241     // Replace the exact with the load.
17242     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17243   }
17244
17245   // The replacement was made in place; don't return anything.
17246   return SDValue();
17247 }
17248
17249 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17250 static std::pair<unsigned, bool>
17251 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17252                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17253   if (!VT.isVector())
17254     return std::make_pair(0, false);
17255
17256   bool NeedSplit = false;
17257   switch (VT.getSimpleVT().SimpleTy) {
17258   default: return std::make_pair(0, false);
17259   case MVT::v32i8:
17260   case MVT::v16i16:
17261   case MVT::v8i32:
17262     if (!Subtarget->hasAVX2())
17263       NeedSplit = true;
17264     if (!Subtarget->hasAVX())
17265       return std::make_pair(0, false);
17266     break;
17267   case MVT::v16i8:
17268   case MVT::v8i16:
17269   case MVT::v4i32:
17270     if (!Subtarget->hasSSE2())
17271       return std::make_pair(0, false);
17272   }
17273
17274   // SSE2 has only a small subset of the operations.
17275   bool hasUnsigned = Subtarget->hasSSE41() ||
17276                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17277   bool hasSigned = Subtarget->hasSSE41() ||
17278                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17279
17280   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17281
17282   unsigned Opc = 0;
17283   // Check for x CC y ? x : y.
17284   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17285       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17286     switch (CC) {
17287     default: break;
17288     case ISD::SETULT:
17289     case ISD::SETULE:
17290       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17291     case ISD::SETUGT:
17292     case ISD::SETUGE:
17293       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17294     case ISD::SETLT:
17295     case ISD::SETLE:
17296       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17297     case ISD::SETGT:
17298     case ISD::SETGE:
17299       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17300     }
17301   // Check for x CC y ? y : x -- a min/max with reversed arms.
17302   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17303              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17304     switch (CC) {
17305     default: break;
17306     case ISD::SETULT:
17307     case ISD::SETULE:
17308       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17309     case ISD::SETUGT:
17310     case ISD::SETUGE:
17311       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17312     case ISD::SETLT:
17313     case ISD::SETLE:
17314       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17315     case ISD::SETGT:
17316     case ISD::SETGE:
17317       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17318     }
17319   }
17320
17321   return std::make_pair(Opc, NeedSplit);
17322 }
17323
17324 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17325 /// nodes.
17326 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17327                                     TargetLowering::DAGCombinerInfo &DCI,
17328                                     const X86Subtarget *Subtarget) {
17329   SDLoc DL(N);
17330   SDValue Cond = N->getOperand(0);
17331   // Get the LHS/RHS of the select.
17332   SDValue LHS = N->getOperand(1);
17333   SDValue RHS = N->getOperand(2);
17334   EVT VT = LHS.getValueType();
17335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17336
17337   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17338   // instructions match the semantics of the common C idiom x<y?x:y but not
17339   // x<=y?x:y, because of how they handle negative zero (which can be
17340   // ignored in unsafe-math mode).
17341   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17342       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17343       (Subtarget->hasSSE2() ||
17344        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17345     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17346
17347     unsigned Opcode = 0;
17348     // Check for x CC y ? x : y.
17349     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17350         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17351       switch (CC) {
17352       default: break;
17353       case ISD::SETULT:
17354         // Converting this to a min would handle NaNs incorrectly, and swapping
17355         // the operands would cause it to handle comparisons between positive
17356         // and negative zero incorrectly.
17357         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17358           if (!DAG.getTarget().Options.UnsafeFPMath &&
17359               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17360             break;
17361           std::swap(LHS, RHS);
17362         }
17363         Opcode = X86ISD::FMIN;
17364         break;
17365       case ISD::SETOLE:
17366         // Converting this to a min would handle comparisons between positive
17367         // and negative zero incorrectly.
17368         if (!DAG.getTarget().Options.UnsafeFPMath &&
17369             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17370           break;
17371         Opcode = X86ISD::FMIN;
17372         break;
17373       case ISD::SETULE:
17374         // Converting this to a min would handle both negative zeros and NaNs
17375         // incorrectly, but we can swap the operands to fix both.
17376         std::swap(LHS, RHS);
17377       case ISD::SETOLT:
17378       case ISD::SETLT:
17379       case ISD::SETLE:
17380         Opcode = X86ISD::FMIN;
17381         break;
17382
17383       case ISD::SETOGE:
17384         // Converting this to a max would handle comparisons between positive
17385         // and negative zero incorrectly.
17386         if (!DAG.getTarget().Options.UnsafeFPMath &&
17387             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17388           break;
17389         Opcode = X86ISD::FMAX;
17390         break;
17391       case ISD::SETUGT:
17392         // Converting this to a max would handle NaNs incorrectly, and swapping
17393         // the operands would cause it to handle comparisons between positive
17394         // and negative zero incorrectly.
17395         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17396           if (!DAG.getTarget().Options.UnsafeFPMath &&
17397               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17398             break;
17399           std::swap(LHS, RHS);
17400         }
17401         Opcode = X86ISD::FMAX;
17402         break;
17403       case ISD::SETUGE:
17404         // Converting this to a max would handle both negative zeros and NaNs
17405         // incorrectly, but we can swap the operands to fix both.
17406         std::swap(LHS, RHS);
17407       case ISD::SETOGT:
17408       case ISD::SETGT:
17409       case ISD::SETGE:
17410         Opcode = X86ISD::FMAX;
17411         break;
17412       }
17413     // Check for x CC y ? y : x -- a min/max with reversed arms.
17414     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17415                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17416       switch (CC) {
17417       default: break;
17418       case ISD::SETOGE:
17419         // Converting this to a min would handle comparisons between positive
17420         // and negative zero incorrectly, and swapping the operands would
17421         // cause it to handle NaNs incorrectly.
17422         if (!DAG.getTarget().Options.UnsafeFPMath &&
17423             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17424           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17425             break;
17426           std::swap(LHS, RHS);
17427         }
17428         Opcode = X86ISD::FMIN;
17429         break;
17430       case ISD::SETUGT:
17431         // Converting this to a min would handle NaNs incorrectly.
17432         if (!DAG.getTarget().Options.UnsafeFPMath &&
17433             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17434           break;
17435         Opcode = X86ISD::FMIN;
17436         break;
17437       case ISD::SETUGE:
17438         // Converting this to a min would handle both negative zeros and NaNs
17439         // incorrectly, but we can swap the operands to fix both.
17440         std::swap(LHS, RHS);
17441       case ISD::SETOGT:
17442       case ISD::SETGT:
17443       case ISD::SETGE:
17444         Opcode = X86ISD::FMIN;
17445         break;
17446
17447       case ISD::SETULT:
17448         // Converting this to a max would handle NaNs incorrectly.
17449         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17450           break;
17451         Opcode = X86ISD::FMAX;
17452         break;
17453       case ISD::SETOLE:
17454         // Converting this to a max would handle comparisons between positive
17455         // and negative zero incorrectly, and swapping the operands would
17456         // cause it to handle NaNs incorrectly.
17457         if (!DAG.getTarget().Options.UnsafeFPMath &&
17458             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17459           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17460             break;
17461           std::swap(LHS, RHS);
17462         }
17463         Opcode = X86ISD::FMAX;
17464         break;
17465       case ISD::SETULE:
17466         // Converting this to a max would handle both negative zeros and NaNs
17467         // incorrectly, but we can swap the operands to fix both.
17468         std::swap(LHS, RHS);
17469       case ISD::SETOLT:
17470       case ISD::SETLT:
17471       case ISD::SETLE:
17472         Opcode = X86ISD::FMAX;
17473         break;
17474       }
17475     }
17476
17477     if (Opcode)
17478       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17479   }
17480
17481   EVT CondVT = Cond.getValueType();
17482   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17483       CondVT.getVectorElementType() == MVT::i1) {
17484     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17485     // lowering on AVX-512. In this case we convert it to
17486     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17487     // The same situation for all 128 and 256-bit vectors of i8 and i16
17488     EVT OpVT = LHS.getValueType();
17489     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17490         (OpVT.getVectorElementType() == MVT::i8 ||
17491          OpVT.getVectorElementType() == MVT::i16)) {
17492       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17493       DCI.AddToWorklist(Cond.getNode());
17494       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17495     }
17496   }
17497   // If this is a select between two integer constants, try to do some
17498   // optimizations.
17499   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17500     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17501       // Don't do this for crazy integer types.
17502       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17503         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17504         // so that TrueC (the true value) is larger than FalseC.
17505         bool NeedsCondInvert = false;
17506
17507         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17508             // Efficiently invertible.
17509             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17510              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17511               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17512           NeedsCondInvert = true;
17513           std::swap(TrueC, FalseC);
17514         }
17515
17516         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17517         if (FalseC->getAPIntValue() == 0 &&
17518             TrueC->getAPIntValue().isPowerOf2()) {
17519           if (NeedsCondInvert) // Invert the condition if needed.
17520             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17521                                DAG.getConstant(1, Cond.getValueType()));
17522
17523           // Zero extend the condition if needed.
17524           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17525
17526           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17527           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17528                              DAG.getConstant(ShAmt, MVT::i8));
17529         }
17530
17531         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17532         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17533           if (NeedsCondInvert) // Invert the condition if needed.
17534             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17535                                DAG.getConstant(1, Cond.getValueType()));
17536
17537           // Zero extend the condition if needed.
17538           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17539                              FalseC->getValueType(0), Cond);
17540           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17541                              SDValue(FalseC, 0));
17542         }
17543
17544         // Optimize cases that will turn into an LEA instruction.  This requires
17545         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17546         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17547           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17548           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17549
17550           bool isFastMultiplier = false;
17551           if (Diff < 10) {
17552             switch ((unsigned char)Diff) {
17553               default: break;
17554               case 1:  // result = add base, cond
17555               case 2:  // result = lea base(    , cond*2)
17556               case 3:  // result = lea base(cond, cond*2)
17557               case 4:  // result = lea base(    , cond*4)
17558               case 5:  // result = lea base(cond, cond*4)
17559               case 8:  // result = lea base(    , cond*8)
17560               case 9:  // result = lea base(cond, cond*8)
17561                 isFastMultiplier = true;
17562                 break;
17563             }
17564           }
17565
17566           if (isFastMultiplier) {
17567             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17568             if (NeedsCondInvert) // Invert the condition if needed.
17569               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17570                                  DAG.getConstant(1, Cond.getValueType()));
17571
17572             // Zero extend the condition if needed.
17573             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17574                                Cond);
17575             // Scale the condition by the difference.
17576             if (Diff != 1)
17577               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17578                                  DAG.getConstant(Diff, Cond.getValueType()));
17579
17580             // Add the base if non-zero.
17581             if (FalseC->getAPIntValue() != 0)
17582               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17583                                  SDValue(FalseC, 0));
17584             return Cond;
17585           }
17586         }
17587       }
17588   }
17589
17590   // Canonicalize max and min:
17591   // (x > y) ? x : y -> (x >= y) ? x : y
17592   // (x < y) ? x : y -> (x <= y) ? x : y
17593   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17594   // the need for an extra compare
17595   // against zero. e.g.
17596   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17597   // subl   %esi, %edi
17598   // testl  %edi, %edi
17599   // movl   $0, %eax
17600   // cmovgl %edi, %eax
17601   // =>
17602   // xorl   %eax, %eax
17603   // subl   %esi, $edi
17604   // cmovsl %eax, %edi
17605   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17606       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17607       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17608     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17609     switch (CC) {
17610     default: break;
17611     case ISD::SETLT:
17612     case ISD::SETGT: {
17613       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17614       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17615                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17616       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17617     }
17618     }
17619   }
17620
17621   // Early exit check
17622   if (!TLI.isTypeLegal(VT))
17623     return SDValue();
17624
17625   // Match VSELECTs into subs with unsigned saturation.
17626   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17627       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17628       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17629        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17630     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17631
17632     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17633     // left side invert the predicate to simplify logic below.
17634     SDValue Other;
17635     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17636       Other = RHS;
17637       CC = ISD::getSetCCInverse(CC, true);
17638     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17639       Other = LHS;
17640     }
17641
17642     if (Other.getNode() && Other->getNumOperands() == 2 &&
17643         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17644       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17645       SDValue CondRHS = Cond->getOperand(1);
17646
17647       // Look for a general sub with unsigned saturation first.
17648       // x >= y ? x-y : 0 --> subus x, y
17649       // x >  y ? x-y : 0 --> subus x, y
17650       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17651           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17652         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17653
17654       // If the RHS is a constant we have to reverse the const canonicalization.
17655       // x > C-1 ? x+-C : 0 --> subus x, C
17656       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17657           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17658         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17659         if (CondRHS.getConstantOperandVal(0) == -A-1)
17660           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17661                              DAG.getConstant(-A, VT));
17662       }
17663
17664       // Another special case: If C was a sign bit, the sub has been
17665       // canonicalized into a xor.
17666       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17667       //        it's safe to decanonicalize the xor?
17668       // x s< 0 ? x^C : 0 --> subus x, C
17669       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17670           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17671           isSplatVector(OpRHS.getNode())) {
17672         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17673         if (A.isSignBit())
17674           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17675       }
17676     }
17677   }
17678
17679   // Try to match a min/max vector operation.
17680   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17681     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17682     unsigned Opc = ret.first;
17683     bool NeedSplit = ret.second;
17684
17685     if (Opc && NeedSplit) {
17686       unsigned NumElems = VT.getVectorNumElements();
17687       // Extract the LHS vectors
17688       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17689       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17690
17691       // Extract the RHS vectors
17692       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17693       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17694
17695       // Create min/max for each subvector
17696       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17697       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17698
17699       // Merge the result
17700       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17701     } else if (Opc)
17702       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17703   }
17704
17705   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17706   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17707       // Check if SETCC has already been promoted
17708       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17709       // Check that condition value type matches vselect operand type
17710       CondVT == VT) { 
17711
17712     assert(Cond.getValueType().isVector() &&
17713            "vector select expects a vector selector!");
17714
17715     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17716     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17717
17718     if (!TValIsAllOnes && !FValIsAllZeros) {
17719       // Try invert the condition if true value is not all 1s and false value
17720       // is not all 0s.
17721       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17722       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17723
17724       if (TValIsAllZeros || FValIsAllOnes) {
17725         SDValue CC = Cond.getOperand(2);
17726         ISD::CondCode NewCC =
17727           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17728                                Cond.getOperand(0).getValueType().isInteger());
17729         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17730         std::swap(LHS, RHS);
17731         TValIsAllOnes = FValIsAllOnes;
17732         FValIsAllZeros = TValIsAllZeros;
17733       }
17734     }
17735
17736     if (TValIsAllOnes || FValIsAllZeros) {
17737       SDValue Ret;
17738
17739       if (TValIsAllOnes && FValIsAllZeros)
17740         Ret = Cond;
17741       else if (TValIsAllOnes)
17742         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17743                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17744       else if (FValIsAllZeros)
17745         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17746                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17747
17748       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17749     }
17750   }
17751
17752   // Try to fold this VSELECT into a MOVSS/MOVSD
17753   if (N->getOpcode() == ISD::VSELECT &&
17754       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17755     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17756         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17757       bool CanFold = false;
17758       unsigned NumElems = Cond.getNumOperands();
17759       SDValue A = LHS;
17760       SDValue B = RHS;
17761       
17762       if (isZero(Cond.getOperand(0))) {
17763         CanFold = true;
17764
17765         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17766         // fold (vselect <0,-1> -> (movsd A, B)
17767         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17768           CanFold = isAllOnes(Cond.getOperand(i));
17769       } else if (isAllOnes(Cond.getOperand(0))) {
17770         CanFold = true;
17771         std::swap(A, B);
17772
17773         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17774         // fold (vselect <-1,0> -> (movsd B, A)
17775         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17776           CanFold = isZero(Cond.getOperand(i));
17777       }
17778
17779       if (CanFold) {
17780         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17781           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17782         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17783       }
17784
17785       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17786         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17787         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17788         //                             (v2i64 (bitcast B)))))
17789         //
17790         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17791         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17792         //                             (v2f64 (bitcast B)))))
17793         //
17794         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17795         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17796         //                             (v2i64 (bitcast A)))))
17797         //
17798         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17799         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17800         //                             (v2f64 (bitcast A)))))
17801
17802         CanFold = (isZero(Cond.getOperand(0)) &&
17803                    isZero(Cond.getOperand(1)) &&
17804                    isAllOnes(Cond.getOperand(2)) &&
17805                    isAllOnes(Cond.getOperand(3)));
17806
17807         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17808             isAllOnes(Cond.getOperand(1)) &&
17809             isZero(Cond.getOperand(2)) &&
17810             isZero(Cond.getOperand(3))) {
17811           CanFold = true;
17812           std::swap(LHS, RHS);
17813         }
17814
17815         if (CanFold) {
17816           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17817           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17818           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17819           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17820                                                 NewB, DAG);
17821           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17822         }
17823       }
17824     }
17825   }
17826
17827   // If we know that this node is legal then we know that it is going to be
17828   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17829   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17830   // to simplify previous instructions.
17831   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17832       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17833     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17834
17835     // Don't optimize vector selects that map to mask-registers.
17836     if (BitWidth == 1)
17837       return SDValue();
17838
17839     // Check all uses of that condition operand to check whether it will be
17840     // consumed by non-BLEND instructions, which may depend on all bits are set
17841     // properly.
17842     for (SDNode::use_iterator I = Cond->use_begin(),
17843                               E = Cond->use_end(); I != E; ++I)
17844       if (I->getOpcode() != ISD::VSELECT)
17845         // TODO: Add other opcodes eventually lowered into BLEND.
17846         return SDValue();
17847
17848     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17849     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17850
17851     APInt KnownZero, KnownOne;
17852     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17853                                           DCI.isBeforeLegalizeOps());
17854     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17855         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17856       DCI.CommitTargetLoweringOpt(TLO);
17857   }
17858
17859   return SDValue();
17860 }
17861
17862 // Check whether a boolean test is testing a boolean value generated by
17863 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17864 // code.
17865 //
17866 // Simplify the following patterns:
17867 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17868 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17869 // to (Op EFLAGS Cond)
17870 //
17871 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17872 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17873 // to (Op EFLAGS !Cond)
17874 //
17875 // where Op could be BRCOND or CMOV.
17876 //
17877 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17878   // Quit if not CMP and SUB with its value result used.
17879   if (Cmp.getOpcode() != X86ISD::CMP &&
17880       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17881       return SDValue();
17882
17883   // Quit if not used as a boolean value.
17884   if (CC != X86::COND_E && CC != X86::COND_NE)
17885     return SDValue();
17886
17887   // Check CMP operands. One of them should be 0 or 1 and the other should be
17888   // an SetCC or extended from it.
17889   SDValue Op1 = Cmp.getOperand(0);
17890   SDValue Op2 = Cmp.getOperand(1);
17891
17892   SDValue SetCC;
17893   const ConstantSDNode* C = 0;
17894   bool needOppositeCond = (CC == X86::COND_E);
17895   bool checkAgainstTrue = false; // Is it a comparison against 1?
17896
17897   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17898     SetCC = Op2;
17899   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17900     SetCC = Op1;
17901   else // Quit if all operands are not constants.
17902     return SDValue();
17903
17904   if (C->getZExtValue() == 1) {
17905     needOppositeCond = !needOppositeCond;
17906     checkAgainstTrue = true;
17907   } else if (C->getZExtValue() != 0)
17908     // Quit if the constant is neither 0 or 1.
17909     return SDValue();
17910
17911   bool truncatedToBoolWithAnd = false;
17912   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17913   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17914          SetCC.getOpcode() == ISD::TRUNCATE ||
17915          SetCC.getOpcode() == ISD::AND) {
17916     if (SetCC.getOpcode() == ISD::AND) {
17917       int OpIdx = -1;
17918       ConstantSDNode *CS;
17919       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17920           CS->getZExtValue() == 1)
17921         OpIdx = 1;
17922       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17923           CS->getZExtValue() == 1)
17924         OpIdx = 0;
17925       if (OpIdx == -1)
17926         break;
17927       SetCC = SetCC.getOperand(OpIdx);
17928       truncatedToBoolWithAnd = true;
17929     } else
17930       SetCC = SetCC.getOperand(0);
17931   }
17932
17933   switch (SetCC.getOpcode()) {
17934   case X86ISD::SETCC_CARRY:
17935     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17936     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17937     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17938     // truncated to i1 using 'and'.
17939     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17940       break;
17941     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17942            "Invalid use of SETCC_CARRY!");
17943     // FALL THROUGH
17944   case X86ISD::SETCC:
17945     // Set the condition code or opposite one if necessary.
17946     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17947     if (needOppositeCond)
17948       CC = X86::GetOppositeBranchCondition(CC);
17949     return SetCC.getOperand(1);
17950   case X86ISD::CMOV: {
17951     // Check whether false/true value has canonical one, i.e. 0 or 1.
17952     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17953     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17954     // Quit if true value is not a constant.
17955     if (!TVal)
17956       return SDValue();
17957     // Quit if false value is not a constant.
17958     if (!FVal) {
17959       SDValue Op = SetCC.getOperand(0);
17960       // Skip 'zext' or 'trunc' node.
17961       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17962           Op.getOpcode() == ISD::TRUNCATE)
17963         Op = Op.getOperand(0);
17964       // A special case for rdrand/rdseed, where 0 is set if false cond is
17965       // found.
17966       if ((Op.getOpcode() != X86ISD::RDRAND &&
17967            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17968         return SDValue();
17969     }
17970     // Quit if false value is not the constant 0 or 1.
17971     bool FValIsFalse = true;
17972     if (FVal && FVal->getZExtValue() != 0) {
17973       if (FVal->getZExtValue() != 1)
17974         return SDValue();
17975       // If FVal is 1, opposite cond is needed.
17976       needOppositeCond = !needOppositeCond;
17977       FValIsFalse = false;
17978     }
17979     // Quit if TVal is not the constant opposite of FVal.
17980     if (FValIsFalse && TVal->getZExtValue() != 1)
17981       return SDValue();
17982     if (!FValIsFalse && TVal->getZExtValue() != 0)
17983       return SDValue();
17984     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17985     if (needOppositeCond)
17986       CC = X86::GetOppositeBranchCondition(CC);
17987     return SetCC.getOperand(3);
17988   }
17989   }
17990
17991   return SDValue();
17992 }
17993
17994 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17995 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17996                                   TargetLowering::DAGCombinerInfo &DCI,
17997                                   const X86Subtarget *Subtarget) {
17998   SDLoc DL(N);
17999
18000   // If the flag operand isn't dead, don't touch this CMOV.
18001   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18002     return SDValue();
18003
18004   SDValue FalseOp = N->getOperand(0);
18005   SDValue TrueOp = N->getOperand(1);
18006   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18007   SDValue Cond = N->getOperand(3);
18008
18009   if (CC == X86::COND_E || CC == X86::COND_NE) {
18010     switch (Cond.getOpcode()) {
18011     default: break;
18012     case X86ISD::BSR:
18013     case X86ISD::BSF:
18014       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18015       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18016         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18017     }
18018   }
18019
18020   SDValue Flags;
18021
18022   Flags = checkBoolTestSetCCCombine(Cond, CC);
18023   if (Flags.getNode() &&
18024       // Extra check as FCMOV only supports a subset of X86 cond.
18025       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18026     SDValue Ops[] = { FalseOp, TrueOp,
18027                       DAG.getConstant(CC, MVT::i8), Flags };
18028     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18029                        Ops, array_lengthof(Ops));
18030   }
18031
18032   // If this is a select between two integer constants, try to do some
18033   // optimizations.  Note that the operands are ordered the opposite of SELECT
18034   // operands.
18035   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18036     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18037       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18038       // larger than FalseC (the false value).
18039       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18040         CC = X86::GetOppositeBranchCondition(CC);
18041         std::swap(TrueC, FalseC);
18042         std::swap(TrueOp, FalseOp);
18043       }
18044
18045       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18046       // This is efficient for any integer data type (including i8/i16) and
18047       // shift amount.
18048       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18049         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18050                            DAG.getConstant(CC, MVT::i8), Cond);
18051
18052         // Zero extend the condition if needed.
18053         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18054
18055         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18056         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18057                            DAG.getConstant(ShAmt, MVT::i8));
18058         if (N->getNumValues() == 2)  // Dead flag value?
18059           return DCI.CombineTo(N, Cond, SDValue());
18060         return Cond;
18061       }
18062
18063       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18064       // for any integer data type, including i8/i16.
18065       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18066         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18067                            DAG.getConstant(CC, MVT::i8), Cond);
18068
18069         // Zero extend the condition if needed.
18070         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18071                            FalseC->getValueType(0), Cond);
18072         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18073                            SDValue(FalseC, 0));
18074
18075         if (N->getNumValues() == 2)  // Dead flag value?
18076           return DCI.CombineTo(N, Cond, SDValue());
18077         return Cond;
18078       }
18079
18080       // Optimize cases that will turn into an LEA instruction.  This requires
18081       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18082       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18083         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18084         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18085
18086         bool isFastMultiplier = false;
18087         if (Diff < 10) {
18088           switch ((unsigned char)Diff) {
18089           default: break;
18090           case 1:  // result = add base, cond
18091           case 2:  // result = lea base(    , cond*2)
18092           case 3:  // result = lea base(cond, cond*2)
18093           case 4:  // result = lea base(    , cond*4)
18094           case 5:  // result = lea base(cond, cond*4)
18095           case 8:  // result = lea base(    , cond*8)
18096           case 9:  // result = lea base(cond, cond*8)
18097             isFastMultiplier = true;
18098             break;
18099           }
18100         }
18101
18102         if (isFastMultiplier) {
18103           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18104           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18105                              DAG.getConstant(CC, MVT::i8), Cond);
18106           // Zero extend the condition if needed.
18107           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18108                              Cond);
18109           // Scale the condition by the difference.
18110           if (Diff != 1)
18111             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18112                                DAG.getConstant(Diff, Cond.getValueType()));
18113
18114           // Add the base if non-zero.
18115           if (FalseC->getAPIntValue() != 0)
18116             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18117                                SDValue(FalseC, 0));
18118           if (N->getNumValues() == 2)  // Dead flag value?
18119             return DCI.CombineTo(N, Cond, SDValue());
18120           return Cond;
18121         }
18122       }
18123     }
18124   }
18125
18126   // Handle these cases:
18127   //   (select (x != c), e, c) -> select (x != c), e, x),
18128   //   (select (x == c), c, e) -> select (x == c), x, e)
18129   // where the c is an integer constant, and the "select" is the combination
18130   // of CMOV and CMP.
18131   //
18132   // The rationale for this change is that the conditional-move from a constant
18133   // needs two instructions, however, conditional-move from a register needs
18134   // only one instruction.
18135   //
18136   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18137   //  some instruction-combining opportunities. This opt needs to be
18138   //  postponed as late as possible.
18139   //
18140   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18141     // the DCI.xxxx conditions are provided to postpone the optimization as
18142     // late as possible.
18143
18144     ConstantSDNode *CmpAgainst = 0;
18145     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18146         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18147         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18148
18149       if (CC == X86::COND_NE &&
18150           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18151         CC = X86::GetOppositeBranchCondition(CC);
18152         std::swap(TrueOp, FalseOp);
18153       }
18154
18155       if (CC == X86::COND_E &&
18156           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18157         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18158                           DAG.getConstant(CC, MVT::i8), Cond };
18159         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18160                            array_lengthof(Ops));
18161       }
18162     }
18163   }
18164
18165   return SDValue();
18166 }
18167
18168 /// PerformMulCombine - Optimize a single multiply with constant into two
18169 /// in order to implement it with two cheaper instructions, e.g.
18170 /// LEA + SHL, LEA + LEA.
18171 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18172                                  TargetLowering::DAGCombinerInfo &DCI) {
18173   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18174     return SDValue();
18175
18176   EVT VT = N->getValueType(0);
18177   if (VT != MVT::i64)
18178     return SDValue();
18179
18180   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18181   if (!C)
18182     return SDValue();
18183   uint64_t MulAmt = C->getZExtValue();
18184   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18185     return SDValue();
18186
18187   uint64_t MulAmt1 = 0;
18188   uint64_t MulAmt2 = 0;
18189   if ((MulAmt % 9) == 0) {
18190     MulAmt1 = 9;
18191     MulAmt2 = MulAmt / 9;
18192   } else if ((MulAmt % 5) == 0) {
18193     MulAmt1 = 5;
18194     MulAmt2 = MulAmt / 5;
18195   } else if ((MulAmt % 3) == 0) {
18196     MulAmt1 = 3;
18197     MulAmt2 = MulAmt / 3;
18198   }
18199   if (MulAmt2 &&
18200       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18201     SDLoc DL(N);
18202
18203     if (isPowerOf2_64(MulAmt2) &&
18204         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18205       // If second multiplifer is pow2, issue it first. We want the multiply by
18206       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18207       // is an add.
18208       std::swap(MulAmt1, MulAmt2);
18209
18210     SDValue NewMul;
18211     if (isPowerOf2_64(MulAmt1))
18212       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18213                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18214     else
18215       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18216                            DAG.getConstant(MulAmt1, VT));
18217
18218     if (isPowerOf2_64(MulAmt2))
18219       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18220                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18221     else
18222       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18223                            DAG.getConstant(MulAmt2, VT));
18224
18225     // Do not add new nodes to DAG combiner worklist.
18226     DCI.CombineTo(N, NewMul, false);
18227   }
18228   return SDValue();
18229 }
18230
18231 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18232   SDValue N0 = N->getOperand(0);
18233   SDValue N1 = N->getOperand(1);
18234   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18235   EVT VT = N0.getValueType();
18236
18237   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18238   // since the result of setcc_c is all zero's or all ones.
18239   if (VT.isInteger() && !VT.isVector() &&
18240       N1C && N0.getOpcode() == ISD::AND &&
18241       N0.getOperand(1).getOpcode() == ISD::Constant) {
18242     SDValue N00 = N0.getOperand(0);
18243     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18244         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18245           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18246          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18247       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18248       APInt ShAmt = N1C->getAPIntValue();
18249       Mask = Mask.shl(ShAmt);
18250       if (Mask != 0)
18251         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18252                            N00, DAG.getConstant(Mask, VT));
18253     }
18254   }
18255
18256   // Hardware support for vector shifts is sparse which makes us scalarize the
18257   // vector operations in many cases. Also, on sandybridge ADD is faster than
18258   // shl.
18259   // (shl V, 1) -> add V,V
18260   if (isSplatVector(N1.getNode())) {
18261     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18262     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18263     // We shift all of the values by one. In many cases we do not have
18264     // hardware support for this operation. This is better expressed as an ADD
18265     // of two values.
18266     if (N1C && (1 == N1C->getZExtValue())) {
18267       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18268     }
18269   }
18270
18271   return SDValue();
18272 }
18273
18274 /// \brief Returns a vector of 0s if the node in input is a vector logical
18275 /// shift by a constant amount which is known to be bigger than or equal
18276 /// to the vector element size in bits.
18277 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18278                                       const X86Subtarget *Subtarget) {
18279   EVT VT = N->getValueType(0);
18280
18281   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18282       (!Subtarget->hasInt256() ||
18283        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18284     return SDValue();
18285
18286   SDValue Amt = N->getOperand(1);
18287   SDLoc DL(N);
18288   if (isSplatVector(Amt.getNode())) {
18289     SDValue SclrAmt = Amt->getOperand(0);
18290     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18291       APInt ShiftAmt = C->getAPIntValue();
18292       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18293
18294       // SSE2/AVX2 logical shifts always return a vector of 0s
18295       // if the shift amount is bigger than or equal to
18296       // the element size. The constant shift amount will be
18297       // encoded as a 8-bit immediate.
18298       if (ShiftAmt.trunc(8).uge(MaxAmount))
18299         return getZeroVector(VT, Subtarget, DAG, DL);
18300     }
18301   }
18302
18303   return SDValue();
18304 }
18305
18306 /// PerformShiftCombine - Combine shifts.
18307 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18308                                    TargetLowering::DAGCombinerInfo &DCI,
18309                                    const X86Subtarget *Subtarget) {
18310   if (N->getOpcode() == ISD::SHL) {
18311     SDValue V = PerformSHLCombine(N, DAG);
18312     if (V.getNode()) return V;
18313   }
18314
18315   if (N->getOpcode() != ISD::SRA) {
18316     // Try to fold this logical shift into a zero vector.
18317     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18318     if (V.getNode()) return V;
18319   }
18320
18321   return SDValue();
18322 }
18323
18324 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18325 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18326 // and friends.  Likewise for OR -> CMPNEQSS.
18327 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18328                             TargetLowering::DAGCombinerInfo &DCI,
18329                             const X86Subtarget *Subtarget) {
18330   unsigned opcode;
18331
18332   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18333   // we're requiring SSE2 for both.
18334   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18335     SDValue N0 = N->getOperand(0);
18336     SDValue N1 = N->getOperand(1);
18337     SDValue CMP0 = N0->getOperand(1);
18338     SDValue CMP1 = N1->getOperand(1);
18339     SDLoc DL(N);
18340
18341     // The SETCCs should both refer to the same CMP.
18342     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18343       return SDValue();
18344
18345     SDValue CMP00 = CMP0->getOperand(0);
18346     SDValue CMP01 = CMP0->getOperand(1);
18347     EVT     VT    = CMP00.getValueType();
18348
18349     if (VT == MVT::f32 || VT == MVT::f64) {
18350       bool ExpectingFlags = false;
18351       // Check for any users that want flags:
18352       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18353            !ExpectingFlags && UI != UE; ++UI)
18354         switch (UI->getOpcode()) {
18355         default:
18356         case ISD::BR_CC:
18357         case ISD::BRCOND:
18358         case ISD::SELECT:
18359           ExpectingFlags = true;
18360           break;
18361         case ISD::CopyToReg:
18362         case ISD::SIGN_EXTEND:
18363         case ISD::ZERO_EXTEND:
18364         case ISD::ANY_EXTEND:
18365           break;
18366         }
18367
18368       if (!ExpectingFlags) {
18369         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18370         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18371
18372         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18373           X86::CondCode tmp = cc0;
18374           cc0 = cc1;
18375           cc1 = tmp;
18376         }
18377
18378         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18379             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18380           // FIXME: need symbolic constants for these magic numbers.
18381           // See X86ATTInstPrinter.cpp:printSSECC().
18382           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18383           if (Subtarget->hasAVX512()) {
18384             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18385                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18386             if (N->getValueType(0) != MVT::i1)
18387               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18388                                  FSetCC);
18389             return FSetCC;
18390           }
18391           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18392                                               CMP00.getValueType(), CMP00, CMP01,
18393                                               DAG.getConstant(x86cc, MVT::i8));
18394
18395           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18396           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18397
18398           if (is64BitFP && !Subtarget->is64Bit()) {
18399             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18400             // 64-bit integer, since that's not a legal type. Since
18401             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18402             // bits, but can do this little dance to extract the lowest 32 bits
18403             // and work with those going forward.
18404             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18405                                            OnesOrZeroesF);
18406             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18407                                            Vector64);
18408             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18409                                         Vector32, DAG.getIntPtrConstant(0));
18410             IntVT = MVT::i32;
18411           }
18412
18413           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18414           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18415                                       DAG.getConstant(1, IntVT));
18416           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18417           return OneBitOfTruth;
18418         }
18419       }
18420     }
18421   }
18422   return SDValue();
18423 }
18424
18425 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18426 /// so it can be folded inside ANDNP.
18427 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18428   EVT VT = N->getValueType(0);
18429
18430   // Match direct AllOnes for 128 and 256-bit vectors
18431   if (ISD::isBuildVectorAllOnes(N))
18432     return true;
18433
18434   // Look through a bit convert.
18435   if (N->getOpcode() == ISD::BITCAST)
18436     N = N->getOperand(0).getNode();
18437
18438   // Sometimes the operand may come from a insert_subvector building a 256-bit
18439   // allones vector
18440   if (VT.is256BitVector() &&
18441       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18442     SDValue V1 = N->getOperand(0);
18443     SDValue V2 = N->getOperand(1);
18444
18445     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18446         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18447         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18448         ISD::isBuildVectorAllOnes(V2.getNode()))
18449       return true;
18450   }
18451
18452   return false;
18453 }
18454
18455 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18456 // register. In most cases we actually compare or select YMM-sized registers
18457 // and mixing the two types creates horrible code. This method optimizes
18458 // some of the transition sequences.
18459 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18460                                  TargetLowering::DAGCombinerInfo &DCI,
18461                                  const X86Subtarget *Subtarget) {
18462   EVT VT = N->getValueType(0);
18463   if (!VT.is256BitVector())
18464     return SDValue();
18465
18466   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18467           N->getOpcode() == ISD::ZERO_EXTEND ||
18468           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18469
18470   SDValue Narrow = N->getOperand(0);
18471   EVT NarrowVT = Narrow->getValueType(0);
18472   if (!NarrowVT.is128BitVector())
18473     return SDValue();
18474
18475   if (Narrow->getOpcode() != ISD::XOR &&
18476       Narrow->getOpcode() != ISD::AND &&
18477       Narrow->getOpcode() != ISD::OR)
18478     return SDValue();
18479
18480   SDValue N0  = Narrow->getOperand(0);
18481   SDValue N1  = Narrow->getOperand(1);
18482   SDLoc DL(Narrow);
18483
18484   // The Left side has to be a trunc.
18485   if (N0.getOpcode() != ISD::TRUNCATE)
18486     return SDValue();
18487
18488   // The type of the truncated inputs.
18489   EVT WideVT = N0->getOperand(0)->getValueType(0);
18490   if (WideVT != VT)
18491     return SDValue();
18492
18493   // The right side has to be a 'trunc' or a constant vector.
18494   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18495   bool RHSConst = (isSplatVector(N1.getNode()) &&
18496                    isa<ConstantSDNode>(N1->getOperand(0)));
18497   if (!RHSTrunc && !RHSConst)
18498     return SDValue();
18499
18500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18501
18502   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18503     return SDValue();
18504
18505   // Set N0 and N1 to hold the inputs to the new wide operation.
18506   N0 = N0->getOperand(0);
18507   if (RHSConst) {
18508     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18509                      N1->getOperand(0));
18510     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18511     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18512   } else if (RHSTrunc) {
18513     N1 = N1->getOperand(0);
18514   }
18515
18516   // Generate the wide operation.
18517   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18518   unsigned Opcode = N->getOpcode();
18519   switch (Opcode) {
18520   case ISD::ANY_EXTEND:
18521     return Op;
18522   case ISD::ZERO_EXTEND: {
18523     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18524     APInt Mask = APInt::getAllOnesValue(InBits);
18525     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18526     return DAG.getNode(ISD::AND, DL, VT,
18527                        Op, DAG.getConstant(Mask, VT));
18528   }
18529   case ISD::SIGN_EXTEND:
18530     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18531                        Op, DAG.getValueType(NarrowVT));
18532   default:
18533     llvm_unreachable("Unexpected opcode");
18534   }
18535 }
18536
18537 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18538                                  TargetLowering::DAGCombinerInfo &DCI,
18539                                  const X86Subtarget *Subtarget) {
18540   EVT VT = N->getValueType(0);
18541   if (DCI.isBeforeLegalizeOps())
18542     return SDValue();
18543
18544   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18545   if (R.getNode())
18546     return R;
18547
18548   // Create BEXTR instructions
18549   // BEXTR is ((X >> imm) & (2**size-1))
18550   if (VT == MVT::i32 || VT == MVT::i64) {
18551     SDValue N0 = N->getOperand(0);
18552     SDValue N1 = N->getOperand(1);
18553     SDLoc DL(N);
18554
18555     // Check for BEXTR.
18556     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18557         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18558       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18559       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18560       if (MaskNode && ShiftNode) {
18561         uint64_t Mask = MaskNode->getZExtValue();
18562         uint64_t Shift = ShiftNode->getZExtValue();
18563         if (isMask_64(Mask)) {
18564           uint64_t MaskSize = CountPopulation_64(Mask);
18565           if (Shift + MaskSize <= VT.getSizeInBits())
18566             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18567                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18568         }
18569       }
18570     } // BEXTR
18571
18572     return SDValue();
18573   }
18574
18575   // Want to form ANDNP nodes:
18576   // 1) In the hopes of then easily combining them with OR and AND nodes
18577   //    to form PBLEND/PSIGN.
18578   // 2) To match ANDN packed intrinsics
18579   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18580     return SDValue();
18581
18582   SDValue N0 = N->getOperand(0);
18583   SDValue N1 = N->getOperand(1);
18584   SDLoc DL(N);
18585
18586   // Check LHS for vnot
18587   if (N0.getOpcode() == ISD::XOR &&
18588       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18589       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18590     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18591
18592   // Check RHS for vnot
18593   if (N1.getOpcode() == ISD::XOR &&
18594       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18595       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18596     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18597
18598   return SDValue();
18599 }
18600
18601 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18602                                 TargetLowering::DAGCombinerInfo &DCI,
18603                                 const X86Subtarget *Subtarget) {
18604   if (DCI.isBeforeLegalizeOps())
18605     return SDValue();
18606
18607   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18608   if (R.getNode())
18609     return R;
18610
18611   SDValue N0 = N->getOperand(0);
18612   SDValue N1 = N->getOperand(1);
18613   EVT VT = N->getValueType(0);
18614
18615   // look for psign/blend
18616   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18617     if (!Subtarget->hasSSSE3() ||
18618         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18619       return SDValue();
18620
18621     // Canonicalize pandn to RHS
18622     if (N0.getOpcode() == X86ISD::ANDNP)
18623       std::swap(N0, N1);
18624     // or (and (m, y), (pandn m, x))
18625     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18626       SDValue Mask = N1.getOperand(0);
18627       SDValue X    = N1.getOperand(1);
18628       SDValue Y;
18629       if (N0.getOperand(0) == Mask)
18630         Y = N0.getOperand(1);
18631       if (N0.getOperand(1) == Mask)
18632         Y = N0.getOperand(0);
18633
18634       // Check to see if the mask appeared in both the AND and ANDNP and
18635       if (!Y.getNode())
18636         return SDValue();
18637
18638       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18639       // Look through mask bitcast.
18640       if (Mask.getOpcode() == ISD::BITCAST)
18641         Mask = Mask.getOperand(0);
18642       if (X.getOpcode() == ISD::BITCAST)
18643         X = X.getOperand(0);
18644       if (Y.getOpcode() == ISD::BITCAST)
18645         Y = Y.getOperand(0);
18646
18647       EVT MaskVT = Mask.getValueType();
18648
18649       // Validate that the Mask operand is a vector sra node.
18650       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18651       // there is no psrai.b
18652       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18653       unsigned SraAmt = ~0;
18654       if (Mask.getOpcode() == ISD::SRA) {
18655         SDValue Amt = Mask.getOperand(1);
18656         if (isSplatVector(Amt.getNode())) {
18657           SDValue SclrAmt = Amt->getOperand(0);
18658           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18659             SraAmt = C->getZExtValue();
18660         }
18661       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18662         SDValue SraC = Mask.getOperand(1);
18663         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18664       }
18665       if ((SraAmt + 1) != EltBits)
18666         return SDValue();
18667
18668       SDLoc DL(N);
18669
18670       // Now we know we at least have a plendvb with the mask val.  See if
18671       // we can form a psignb/w/d.
18672       // psign = x.type == y.type == mask.type && y = sub(0, x);
18673       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18674           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18675           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18676         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18677                "Unsupported VT for PSIGN");
18678         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18679         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18680       }
18681       // PBLENDVB only available on SSE 4.1
18682       if (!Subtarget->hasSSE41())
18683         return SDValue();
18684
18685       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18686
18687       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18688       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18689       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18690       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18691       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18692     }
18693   }
18694
18695   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18696     return SDValue();
18697
18698   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18699   MachineFunction &MF = DAG.getMachineFunction();
18700   bool OptForSize = MF.getFunction()->getAttributes().
18701     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18702
18703   // SHLD/SHRD instructions have lower register pressure, but on some
18704   // platforms they have higher latency than the equivalent
18705   // series of shifts/or that would otherwise be generated.
18706   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18707   // have higher latencies and we are not optimizing for size.
18708   if (!OptForSize && Subtarget->isSHLDSlow())
18709     return SDValue();
18710
18711   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18712     std::swap(N0, N1);
18713   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18714     return SDValue();
18715   if (!N0.hasOneUse() || !N1.hasOneUse())
18716     return SDValue();
18717
18718   SDValue ShAmt0 = N0.getOperand(1);
18719   if (ShAmt0.getValueType() != MVT::i8)
18720     return SDValue();
18721   SDValue ShAmt1 = N1.getOperand(1);
18722   if (ShAmt1.getValueType() != MVT::i8)
18723     return SDValue();
18724   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18725     ShAmt0 = ShAmt0.getOperand(0);
18726   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18727     ShAmt1 = ShAmt1.getOperand(0);
18728
18729   SDLoc DL(N);
18730   unsigned Opc = X86ISD::SHLD;
18731   SDValue Op0 = N0.getOperand(0);
18732   SDValue Op1 = N1.getOperand(0);
18733   if (ShAmt0.getOpcode() == ISD::SUB) {
18734     Opc = X86ISD::SHRD;
18735     std::swap(Op0, Op1);
18736     std::swap(ShAmt0, ShAmt1);
18737   }
18738
18739   unsigned Bits = VT.getSizeInBits();
18740   if (ShAmt1.getOpcode() == ISD::SUB) {
18741     SDValue Sum = ShAmt1.getOperand(0);
18742     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18743       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18744       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18745         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18746       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18747         return DAG.getNode(Opc, DL, VT,
18748                            Op0, Op1,
18749                            DAG.getNode(ISD::TRUNCATE, DL,
18750                                        MVT::i8, ShAmt0));
18751     }
18752   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18753     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18754     if (ShAmt0C &&
18755         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18756       return DAG.getNode(Opc, DL, VT,
18757                          N0.getOperand(0), N1.getOperand(0),
18758                          DAG.getNode(ISD::TRUNCATE, DL,
18759                                        MVT::i8, ShAmt0));
18760   }
18761
18762   return SDValue();
18763 }
18764
18765 // Generate NEG and CMOV for integer abs.
18766 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18767   EVT VT = N->getValueType(0);
18768
18769   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18770   // 8-bit integer abs to NEG and CMOV.
18771   if (VT.isInteger() && VT.getSizeInBits() == 8)
18772     return SDValue();
18773
18774   SDValue N0 = N->getOperand(0);
18775   SDValue N1 = N->getOperand(1);
18776   SDLoc DL(N);
18777
18778   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18779   // and change it to SUB and CMOV.
18780   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18781       N0.getOpcode() == ISD::ADD &&
18782       N0.getOperand(1) == N1 &&
18783       N1.getOpcode() == ISD::SRA &&
18784       N1.getOperand(0) == N0.getOperand(0))
18785     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18786       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18787         // Generate SUB & CMOV.
18788         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18789                                   DAG.getConstant(0, VT), N0.getOperand(0));
18790
18791         SDValue Ops[] = { N0.getOperand(0), Neg,
18792                           DAG.getConstant(X86::COND_GE, MVT::i8),
18793                           SDValue(Neg.getNode(), 1) };
18794         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18795                            Ops, array_lengthof(Ops));
18796       }
18797   return SDValue();
18798 }
18799
18800 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18801 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18802                                  TargetLowering::DAGCombinerInfo &DCI,
18803                                  const X86Subtarget *Subtarget) {
18804   if (DCI.isBeforeLegalizeOps())
18805     return SDValue();
18806
18807   if (Subtarget->hasCMov()) {
18808     SDValue RV = performIntegerAbsCombine(N, DAG);
18809     if (RV.getNode())
18810       return RV;
18811   }
18812
18813   return SDValue();
18814 }
18815
18816 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18817 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18818                                   TargetLowering::DAGCombinerInfo &DCI,
18819                                   const X86Subtarget *Subtarget) {
18820   LoadSDNode *Ld = cast<LoadSDNode>(N);
18821   EVT RegVT = Ld->getValueType(0);
18822   EVT MemVT = Ld->getMemoryVT();
18823   SDLoc dl(Ld);
18824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18825   unsigned RegSz = RegVT.getSizeInBits();
18826
18827   // On Sandybridge unaligned 256bit loads are inefficient.
18828   ISD::LoadExtType Ext = Ld->getExtensionType();
18829   unsigned Alignment = Ld->getAlignment();
18830   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18831   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18832       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18833     unsigned NumElems = RegVT.getVectorNumElements();
18834     if (NumElems < 2)
18835       return SDValue();
18836
18837     SDValue Ptr = Ld->getBasePtr();
18838     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18839
18840     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18841                                   NumElems/2);
18842     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18843                                 Ld->getPointerInfo(), Ld->isVolatile(),
18844                                 Ld->isNonTemporal(), Ld->isInvariant(),
18845                                 Alignment);
18846     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18847     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18848                                 Ld->getPointerInfo(), Ld->isVolatile(),
18849                                 Ld->isNonTemporal(), Ld->isInvariant(),
18850                                 std::min(16U, Alignment));
18851     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18852                              Load1.getValue(1),
18853                              Load2.getValue(1));
18854
18855     SDValue NewVec = DAG.getUNDEF(RegVT);
18856     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18857     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18858     return DCI.CombineTo(N, NewVec, TF, true);
18859   }
18860
18861   // If this is a vector EXT Load then attempt to optimize it using a
18862   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18863   // expansion is still better than scalar code.
18864   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18865   // emit a shuffle and a arithmetic shift.
18866   // TODO: It is possible to support ZExt by zeroing the undef values
18867   // during the shuffle phase or after the shuffle.
18868   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18869       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18870     assert(MemVT != RegVT && "Cannot extend to the same type");
18871     assert(MemVT.isVector() && "Must load a vector from memory");
18872
18873     unsigned NumElems = RegVT.getVectorNumElements();
18874     unsigned MemSz = MemVT.getSizeInBits();
18875     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18876
18877     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18878       return SDValue();
18879
18880     // All sizes must be a power of two.
18881     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18882       return SDValue();
18883
18884     // Attempt to load the original value using scalar loads.
18885     // Find the largest scalar type that divides the total loaded size.
18886     MVT SclrLoadTy = MVT::i8;
18887     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18888          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18889       MVT Tp = (MVT::SimpleValueType)tp;
18890       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18891         SclrLoadTy = Tp;
18892       }
18893     }
18894
18895     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18896     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18897         (64 <= MemSz))
18898       SclrLoadTy = MVT::f64;
18899
18900     // Calculate the number of scalar loads that we need to perform
18901     // in order to load our vector from memory.
18902     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18903     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18904       return SDValue();
18905
18906     unsigned loadRegZize = RegSz;
18907     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18908       loadRegZize /= 2;
18909
18910     // Represent our vector as a sequence of elements which are the
18911     // largest scalar that we can load.
18912     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18913       loadRegZize/SclrLoadTy.getSizeInBits());
18914
18915     // Represent the data using the same element type that is stored in
18916     // memory. In practice, we ''widen'' MemVT.
18917     EVT WideVecVT =
18918           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18919                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18920
18921     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18922       "Invalid vector type");
18923
18924     // We can't shuffle using an illegal type.
18925     if (!TLI.isTypeLegal(WideVecVT))
18926       return SDValue();
18927
18928     SmallVector<SDValue, 8> Chains;
18929     SDValue Ptr = Ld->getBasePtr();
18930     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18931                                         TLI.getPointerTy());
18932     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18933
18934     for (unsigned i = 0; i < NumLoads; ++i) {
18935       // Perform a single load.
18936       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18937                                        Ptr, Ld->getPointerInfo(),
18938                                        Ld->isVolatile(), Ld->isNonTemporal(),
18939                                        Ld->isInvariant(), Ld->getAlignment());
18940       Chains.push_back(ScalarLoad.getValue(1));
18941       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18942       // another round of DAGCombining.
18943       if (i == 0)
18944         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18945       else
18946         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18947                           ScalarLoad, DAG.getIntPtrConstant(i));
18948
18949       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18950     }
18951
18952     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18953                                Chains.size());
18954
18955     // Bitcast the loaded value to a vector of the original element type, in
18956     // the size of the target vector type.
18957     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18958     unsigned SizeRatio = RegSz/MemSz;
18959
18960     if (Ext == ISD::SEXTLOAD) {
18961       // If we have SSE4.1 we can directly emit a VSEXT node.
18962       if (Subtarget->hasSSE41()) {
18963         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18964         return DCI.CombineTo(N, Sext, TF, true);
18965       }
18966
18967       // Otherwise we'll shuffle the small elements in the high bits of the
18968       // larger type and perform an arithmetic shift. If the shift is not legal
18969       // it's better to scalarize.
18970       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18971         return SDValue();
18972
18973       // Redistribute the loaded elements into the different locations.
18974       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18975       for (unsigned i = 0; i != NumElems; ++i)
18976         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18977
18978       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18979                                            DAG.getUNDEF(WideVecVT),
18980                                            &ShuffleVec[0]);
18981
18982       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18983
18984       // Build the arithmetic shift.
18985       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18986                      MemVT.getVectorElementType().getSizeInBits();
18987       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18988                           DAG.getConstant(Amt, RegVT));
18989
18990       return DCI.CombineTo(N, Shuff, TF, true);
18991     }
18992
18993     // Redistribute the loaded elements into the different locations.
18994     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18995     for (unsigned i = 0; i != NumElems; ++i)
18996       ShuffleVec[i*SizeRatio] = i;
18997
18998     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18999                                          DAG.getUNDEF(WideVecVT),
19000                                          &ShuffleVec[0]);
19001
19002     // Bitcast to the requested type.
19003     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19004     // Replace the original load with the new sequence
19005     // and return the new chain.
19006     return DCI.CombineTo(N, Shuff, TF, true);
19007   }
19008
19009   return SDValue();
19010 }
19011
19012 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19013 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19014                                    const X86Subtarget *Subtarget) {
19015   StoreSDNode *St = cast<StoreSDNode>(N);
19016   EVT VT = St->getValue().getValueType();
19017   EVT StVT = St->getMemoryVT();
19018   SDLoc dl(St);
19019   SDValue StoredVal = St->getOperand(1);
19020   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19021
19022   // If we are saving a concatenation of two XMM registers, perform two stores.
19023   // On Sandy Bridge, 256-bit memory operations are executed by two
19024   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19025   // memory  operation.
19026   unsigned Alignment = St->getAlignment();
19027   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19028   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19029       StVT == VT && !IsAligned) {
19030     unsigned NumElems = VT.getVectorNumElements();
19031     if (NumElems < 2)
19032       return SDValue();
19033
19034     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19035     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19036
19037     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19038     SDValue Ptr0 = St->getBasePtr();
19039     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19040
19041     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19042                                 St->getPointerInfo(), St->isVolatile(),
19043                                 St->isNonTemporal(), Alignment);
19044     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19045                                 St->getPointerInfo(), St->isVolatile(),
19046                                 St->isNonTemporal(),
19047                                 std::min(16U, Alignment));
19048     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19049   }
19050
19051   // Optimize trunc store (of multiple scalars) to shuffle and store.
19052   // First, pack all of the elements in one place. Next, store to memory
19053   // in fewer chunks.
19054   if (St->isTruncatingStore() && VT.isVector()) {
19055     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19056     unsigned NumElems = VT.getVectorNumElements();
19057     assert(StVT != VT && "Cannot truncate to the same type");
19058     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19059     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19060
19061     // From, To sizes and ElemCount must be pow of two
19062     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19063     // We are going to use the original vector elt for storing.
19064     // Accumulated smaller vector elements must be a multiple of the store size.
19065     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19066
19067     unsigned SizeRatio  = FromSz / ToSz;
19068
19069     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19070
19071     // Create a type on which we perform the shuffle
19072     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19073             StVT.getScalarType(), NumElems*SizeRatio);
19074
19075     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19076
19077     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19078     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19079     for (unsigned i = 0; i != NumElems; ++i)
19080       ShuffleVec[i] = i * SizeRatio;
19081
19082     // Can't shuffle using an illegal type.
19083     if (!TLI.isTypeLegal(WideVecVT))
19084       return SDValue();
19085
19086     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19087                                          DAG.getUNDEF(WideVecVT),
19088                                          &ShuffleVec[0]);
19089     // At this point all of the data is stored at the bottom of the
19090     // register. We now need to save it to mem.
19091
19092     // Find the largest store unit
19093     MVT StoreType = MVT::i8;
19094     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19095          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19096       MVT Tp = (MVT::SimpleValueType)tp;
19097       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19098         StoreType = Tp;
19099     }
19100
19101     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19102     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19103         (64 <= NumElems * ToSz))
19104       StoreType = MVT::f64;
19105
19106     // Bitcast the original vector into a vector of store-size units
19107     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19108             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19109     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19110     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19111     SmallVector<SDValue, 8> Chains;
19112     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19113                                         TLI.getPointerTy());
19114     SDValue Ptr = St->getBasePtr();
19115
19116     // Perform one or more big stores into memory.
19117     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19118       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19119                                    StoreType, ShuffWide,
19120                                    DAG.getIntPtrConstant(i));
19121       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19122                                 St->getPointerInfo(), St->isVolatile(),
19123                                 St->isNonTemporal(), St->getAlignment());
19124       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19125       Chains.push_back(Ch);
19126     }
19127
19128     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19129                                Chains.size());
19130   }
19131
19132   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19133   // the FP state in cases where an emms may be missing.
19134   // A preferable solution to the general problem is to figure out the right
19135   // places to insert EMMS.  This qualifies as a quick hack.
19136
19137   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19138   if (VT.getSizeInBits() != 64)
19139     return SDValue();
19140
19141   const Function *F = DAG.getMachineFunction().getFunction();
19142   bool NoImplicitFloatOps = F->getAttributes().
19143     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19144   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19145                      && Subtarget->hasSSE2();
19146   if ((VT.isVector() ||
19147        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19148       isa<LoadSDNode>(St->getValue()) &&
19149       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19150       St->getChain().hasOneUse() && !St->isVolatile()) {
19151     SDNode* LdVal = St->getValue().getNode();
19152     LoadSDNode *Ld = 0;
19153     int TokenFactorIndex = -1;
19154     SmallVector<SDValue, 8> Ops;
19155     SDNode* ChainVal = St->getChain().getNode();
19156     // Must be a store of a load.  We currently handle two cases:  the load
19157     // is a direct child, and it's under an intervening TokenFactor.  It is
19158     // possible to dig deeper under nested TokenFactors.
19159     if (ChainVal == LdVal)
19160       Ld = cast<LoadSDNode>(St->getChain());
19161     else if (St->getValue().hasOneUse() &&
19162              ChainVal->getOpcode() == ISD::TokenFactor) {
19163       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19164         if (ChainVal->getOperand(i).getNode() == LdVal) {
19165           TokenFactorIndex = i;
19166           Ld = cast<LoadSDNode>(St->getValue());
19167         } else
19168           Ops.push_back(ChainVal->getOperand(i));
19169       }
19170     }
19171
19172     if (!Ld || !ISD::isNormalLoad(Ld))
19173       return SDValue();
19174
19175     // If this is not the MMX case, i.e. we are just turning i64 load/store
19176     // into f64 load/store, avoid the transformation if there are multiple
19177     // uses of the loaded value.
19178     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19179       return SDValue();
19180
19181     SDLoc LdDL(Ld);
19182     SDLoc StDL(N);
19183     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19184     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19185     // pair instead.
19186     if (Subtarget->is64Bit() || F64IsLegal) {
19187       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19188       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19189                                   Ld->getPointerInfo(), Ld->isVolatile(),
19190                                   Ld->isNonTemporal(), Ld->isInvariant(),
19191                                   Ld->getAlignment());
19192       SDValue NewChain = NewLd.getValue(1);
19193       if (TokenFactorIndex != -1) {
19194         Ops.push_back(NewChain);
19195         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19196                                Ops.size());
19197       }
19198       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19199                           St->getPointerInfo(),
19200                           St->isVolatile(), St->isNonTemporal(),
19201                           St->getAlignment());
19202     }
19203
19204     // Otherwise, lower to two pairs of 32-bit loads / stores.
19205     SDValue LoAddr = Ld->getBasePtr();
19206     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19207                                  DAG.getConstant(4, MVT::i32));
19208
19209     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19210                                Ld->getPointerInfo(),
19211                                Ld->isVolatile(), Ld->isNonTemporal(),
19212                                Ld->isInvariant(), Ld->getAlignment());
19213     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19214                                Ld->getPointerInfo().getWithOffset(4),
19215                                Ld->isVolatile(), Ld->isNonTemporal(),
19216                                Ld->isInvariant(),
19217                                MinAlign(Ld->getAlignment(), 4));
19218
19219     SDValue NewChain = LoLd.getValue(1);
19220     if (TokenFactorIndex != -1) {
19221       Ops.push_back(LoLd);
19222       Ops.push_back(HiLd);
19223       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19224                              Ops.size());
19225     }
19226
19227     LoAddr = St->getBasePtr();
19228     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19229                          DAG.getConstant(4, MVT::i32));
19230
19231     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19232                                 St->getPointerInfo(),
19233                                 St->isVolatile(), St->isNonTemporal(),
19234                                 St->getAlignment());
19235     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19236                                 St->getPointerInfo().getWithOffset(4),
19237                                 St->isVolatile(),
19238                                 St->isNonTemporal(),
19239                                 MinAlign(St->getAlignment(), 4));
19240     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19241   }
19242   return SDValue();
19243 }
19244
19245 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19246 /// and return the operands for the horizontal operation in LHS and RHS.  A
19247 /// horizontal operation performs the binary operation on successive elements
19248 /// of its first operand, then on successive elements of its second operand,
19249 /// returning the resulting values in a vector.  For example, if
19250 ///   A = < float a0, float a1, float a2, float a3 >
19251 /// and
19252 ///   B = < float b0, float b1, float b2, float b3 >
19253 /// then the result of doing a horizontal operation on A and B is
19254 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19255 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19256 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19257 /// set to A, RHS to B, and the routine returns 'true'.
19258 /// Note that the binary operation should have the property that if one of the
19259 /// operands is UNDEF then the result is UNDEF.
19260 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19261   // Look for the following pattern: if
19262   //   A = < float a0, float a1, float a2, float a3 >
19263   //   B = < float b0, float b1, float b2, float b3 >
19264   // and
19265   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19266   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19267   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19268   // which is A horizontal-op B.
19269
19270   // At least one of the operands should be a vector shuffle.
19271   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19272       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19273     return false;
19274
19275   MVT VT = LHS.getSimpleValueType();
19276
19277   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19278          "Unsupported vector type for horizontal add/sub");
19279
19280   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19281   // operate independently on 128-bit lanes.
19282   unsigned NumElts = VT.getVectorNumElements();
19283   unsigned NumLanes = VT.getSizeInBits()/128;
19284   unsigned NumLaneElts = NumElts / NumLanes;
19285   assert((NumLaneElts % 2 == 0) &&
19286          "Vector type should have an even number of elements in each lane");
19287   unsigned HalfLaneElts = NumLaneElts/2;
19288
19289   // View LHS in the form
19290   //   LHS = VECTOR_SHUFFLE A, B, LMask
19291   // If LHS is not a shuffle then pretend it is the shuffle
19292   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19293   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19294   // type VT.
19295   SDValue A, B;
19296   SmallVector<int, 16> LMask(NumElts);
19297   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19298     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19299       A = LHS.getOperand(0);
19300     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19301       B = LHS.getOperand(1);
19302     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19303     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19304   } else {
19305     if (LHS.getOpcode() != ISD::UNDEF)
19306       A = LHS;
19307     for (unsigned i = 0; i != NumElts; ++i)
19308       LMask[i] = i;
19309   }
19310
19311   // Likewise, view RHS in the form
19312   //   RHS = VECTOR_SHUFFLE C, D, RMask
19313   SDValue C, D;
19314   SmallVector<int, 16> RMask(NumElts);
19315   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19316     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19317       C = RHS.getOperand(0);
19318     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19319       D = RHS.getOperand(1);
19320     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19321     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19322   } else {
19323     if (RHS.getOpcode() != ISD::UNDEF)
19324       C = RHS;
19325     for (unsigned i = 0; i != NumElts; ++i)
19326       RMask[i] = i;
19327   }
19328
19329   // Check that the shuffles are both shuffling the same vectors.
19330   if (!(A == C && B == D) && !(A == D && B == C))
19331     return false;
19332
19333   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19334   if (!A.getNode() && !B.getNode())
19335     return false;
19336
19337   // If A and B occur in reverse order in RHS, then "swap" them (which means
19338   // rewriting the mask).
19339   if (A != C)
19340     CommuteVectorShuffleMask(RMask, NumElts);
19341
19342   // At this point LHS and RHS are equivalent to
19343   //   LHS = VECTOR_SHUFFLE A, B, LMask
19344   //   RHS = VECTOR_SHUFFLE A, B, RMask
19345   // Check that the masks correspond to performing a horizontal operation.
19346   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19347     for (unsigned i = 0; i != NumLaneElts; ++i) {
19348       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19349
19350       // Ignore any UNDEF components.
19351       if (LIdx < 0 || RIdx < 0 ||
19352           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19353           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19354         continue;
19355
19356       // Check that successive elements are being operated on.  If not, this is
19357       // not a horizontal operation.
19358       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19359       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19360       if (!(LIdx == Index && RIdx == Index + 1) &&
19361           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19362         return false;
19363     }
19364   }
19365
19366   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19367   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19368   return true;
19369 }
19370
19371 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19372 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19373                                   const X86Subtarget *Subtarget) {
19374   EVT VT = N->getValueType(0);
19375   SDValue LHS = N->getOperand(0);
19376   SDValue RHS = N->getOperand(1);
19377
19378   // Try to synthesize horizontal adds from adds of shuffles.
19379   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19380        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19381       isHorizontalBinOp(LHS, RHS, true))
19382     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19383   return SDValue();
19384 }
19385
19386 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19387 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19388                                   const X86Subtarget *Subtarget) {
19389   EVT VT = N->getValueType(0);
19390   SDValue LHS = N->getOperand(0);
19391   SDValue RHS = N->getOperand(1);
19392
19393   // Try to synthesize horizontal subs from subs of shuffles.
19394   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19395        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19396       isHorizontalBinOp(LHS, RHS, false))
19397     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19398   return SDValue();
19399 }
19400
19401 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19402 /// X86ISD::FXOR nodes.
19403 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19404   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19405   // F[X]OR(0.0, x) -> x
19406   // F[X]OR(x, 0.0) -> x
19407   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19408     if (C->getValueAPF().isPosZero())
19409       return N->getOperand(1);
19410   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19411     if (C->getValueAPF().isPosZero())
19412       return N->getOperand(0);
19413   return SDValue();
19414 }
19415
19416 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19417 /// X86ISD::FMAX nodes.
19418 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19419   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19420
19421   // Only perform optimizations if UnsafeMath is used.
19422   if (!DAG.getTarget().Options.UnsafeFPMath)
19423     return SDValue();
19424
19425   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19426   // into FMINC and FMAXC, which are Commutative operations.
19427   unsigned NewOp = 0;
19428   switch (N->getOpcode()) {
19429     default: llvm_unreachable("unknown opcode");
19430     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19431     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19432   }
19433
19434   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19435                      N->getOperand(0), N->getOperand(1));
19436 }
19437
19438 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19439 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19440   // FAND(0.0, x) -> 0.0
19441   // FAND(x, 0.0) -> 0.0
19442   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19443     if (C->getValueAPF().isPosZero())
19444       return N->getOperand(0);
19445   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19446     if (C->getValueAPF().isPosZero())
19447       return N->getOperand(1);
19448   return SDValue();
19449 }
19450
19451 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19452 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19453   // FANDN(x, 0.0) -> 0.0
19454   // FANDN(0.0, x) -> x
19455   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19456     if (C->getValueAPF().isPosZero())
19457       return N->getOperand(1);
19458   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19459     if (C->getValueAPF().isPosZero())
19460       return N->getOperand(1);
19461   return SDValue();
19462 }
19463
19464 static SDValue PerformBTCombine(SDNode *N,
19465                                 SelectionDAG &DAG,
19466                                 TargetLowering::DAGCombinerInfo &DCI) {
19467   // BT ignores high bits in the bit index operand.
19468   SDValue Op1 = N->getOperand(1);
19469   if (Op1.hasOneUse()) {
19470     unsigned BitWidth = Op1.getValueSizeInBits();
19471     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19472     APInt KnownZero, KnownOne;
19473     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19474                                           !DCI.isBeforeLegalizeOps());
19475     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19476     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19477         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19478       DCI.CommitTargetLoweringOpt(TLO);
19479   }
19480   return SDValue();
19481 }
19482
19483 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19484   SDValue Op = N->getOperand(0);
19485   if (Op.getOpcode() == ISD::BITCAST)
19486     Op = Op.getOperand(0);
19487   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19488   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19489       VT.getVectorElementType().getSizeInBits() ==
19490       OpVT.getVectorElementType().getSizeInBits()) {
19491     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19492   }
19493   return SDValue();
19494 }
19495
19496 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19497                                                const X86Subtarget *Subtarget) {
19498   EVT VT = N->getValueType(0);
19499   if (!VT.isVector())
19500     return SDValue();
19501
19502   SDValue N0 = N->getOperand(0);
19503   SDValue N1 = N->getOperand(1);
19504   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19505   SDLoc dl(N);
19506
19507   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19508   // both SSE and AVX2 since there is no sign-extended shift right
19509   // operation on a vector with 64-bit elements.
19510   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19511   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19512   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19513       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19514     SDValue N00 = N0.getOperand(0);
19515
19516     // EXTLOAD has a better solution on AVX2,
19517     // it may be replaced with X86ISD::VSEXT node.
19518     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19519       if (!ISD::isNormalLoad(N00.getNode()))
19520         return SDValue();
19521
19522     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19523         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19524                                   N00, N1);
19525       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19526     }
19527   }
19528   return SDValue();
19529 }
19530
19531 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19532                                   TargetLowering::DAGCombinerInfo &DCI,
19533                                   const X86Subtarget *Subtarget) {
19534   if (!DCI.isBeforeLegalizeOps())
19535     return SDValue();
19536
19537   if (!Subtarget->hasFp256())
19538     return SDValue();
19539
19540   EVT VT = N->getValueType(0);
19541   if (VT.isVector() && VT.getSizeInBits() == 256) {
19542     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19543     if (R.getNode())
19544       return R;
19545   }
19546
19547   return SDValue();
19548 }
19549
19550 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19551                                  const X86Subtarget* Subtarget) {
19552   SDLoc dl(N);
19553   EVT VT = N->getValueType(0);
19554
19555   // Let legalize expand this if it isn't a legal type yet.
19556   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19557     return SDValue();
19558
19559   EVT ScalarVT = VT.getScalarType();
19560   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19561       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19562     return SDValue();
19563
19564   SDValue A = N->getOperand(0);
19565   SDValue B = N->getOperand(1);
19566   SDValue C = N->getOperand(2);
19567
19568   bool NegA = (A.getOpcode() == ISD::FNEG);
19569   bool NegB = (B.getOpcode() == ISD::FNEG);
19570   bool NegC = (C.getOpcode() == ISD::FNEG);
19571
19572   // Negative multiplication when NegA xor NegB
19573   bool NegMul = (NegA != NegB);
19574   if (NegA)
19575     A = A.getOperand(0);
19576   if (NegB)
19577     B = B.getOperand(0);
19578   if (NegC)
19579     C = C.getOperand(0);
19580
19581   unsigned Opcode;
19582   if (!NegMul)
19583     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19584   else
19585     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19586
19587   return DAG.getNode(Opcode, dl, VT, A, B, C);
19588 }
19589
19590 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19591                                   TargetLowering::DAGCombinerInfo &DCI,
19592                                   const X86Subtarget *Subtarget) {
19593   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19594   //           (and (i32 x86isd::setcc_carry), 1)
19595   // This eliminates the zext. This transformation is necessary because
19596   // ISD::SETCC is always legalized to i8.
19597   SDLoc dl(N);
19598   SDValue N0 = N->getOperand(0);
19599   EVT VT = N->getValueType(0);
19600
19601   if (N0.getOpcode() == ISD::AND &&
19602       N0.hasOneUse() &&
19603       N0.getOperand(0).hasOneUse()) {
19604     SDValue N00 = N0.getOperand(0);
19605     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19606       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19607       if (!C || C->getZExtValue() != 1)
19608         return SDValue();
19609       return DAG.getNode(ISD::AND, dl, VT,
19610                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19611                                      N00.getOperand(0), N00.getOperand(1)),
19612                          DAG.getConstant(1, VT));
19613     }
19614   }
19615
19616   if (N0.getOpcode() == ISD::TRUNCATE &&
19617       N0.hasOneUse() &&
19618       N0.getOperand(0).hasOneUse()) {
19619     SDValue N00 = N0.getOperand(0);
19620     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19621       return DAG.getNode(ISD::AND, dl, VT,
19622                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19623                                      N00.getOperand(0), N00.getOperand(1)),
19624                          DAG.getConstant(1, VT));
19625     }
19626   }
19627   if (VT.is256BitVector()) {
19628     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19629     if (R.getNode())
19630       return R;
19631   }
19632
19633   return SDValue();
19634 }
19635
19636 // Optimize x == -y --> x+y == 0
19637 //          x != -y --> x+y != 0
19638 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19639                                       const X86Subtarget* Subtarget) {
19640   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19641   SDValue LHS = N->getOperand(0);
19642   SDValue RHS = N->getOperand(1);
19643   EVT VT = N->getValueType(0);
19644   SDLoc DL(N);
19645
19646   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19647     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19648       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19649         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19650                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19651         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19652                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19653       }
19654   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19655     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19656       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19657         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19658                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19659         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19660                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19661       }
19662
19663   if (VT.getScalarType() == MVT::i1) {
19664     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19665       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19666     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19667     if (!IsSEXT0 && !IsVZero0)
19668       return SDValue();
19669     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19670       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19671     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19672
19673     if (!IsSEXT1 && !IsVZero1)
19674       return SDValue();
19675
19676     if (IsSEXT0 && IsVZero1) {
19677       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19678       if (CC == ISD::SETEQ)
19679         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19680       return LHS.getOperand(0);
19681     }
19682     if (IsSEXT1 && IsVZero0) {
19683       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19684       if (CC == ISD::SETEQ)
19685         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19686       return RHS.getOperand(0);
19687     }
19688   }
19689
19690   return SDValue();
19691 }
19692
19693 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19694 // as "sbb reg,reg", since it can be extended without zext and produces
19695 // an all-ones bit which is more useful than 0/1 in some cases.
19696 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19697                                MVT VT) {
19698   if (VT == MVT::i8)
19699     return DAG.getNode(ISD::AND, DL, VT,
19700                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19701                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19702                        DAG.getConstant(1, VT));
19703   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19704   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19705                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19706                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19707 }
19708
19709 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19710 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19711                                    TargetLowering::DAGCombinerInfo &DCI,
19712                                    const X86Subtarget *Subtarget) {
19713   SDLoc DL(N);
19714   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19715   SDValue EFLAGS = N->getOperand(1);
19716
19717   if (CC == X86::COND_A) {
19718     // Try to convert COND_A into COND_B in an attempt to facilitate
19719     // materializing "setb reg".
19720     //
19721     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19722     // cannot take an immediate as its first operand.
19723     //
19724     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19725         EFLAGS.getValueType().isInteger() &&
19726         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19727       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19728                                    EFLAGS.getNode()->getVTList(),
19729                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19730       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19731       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19732     }
19733   }
19734
19735   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19736   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19737   // cases.
19738   if (CC == X86::COND_B)
19739     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19740
19741   SDValue Flags;
19742
19743   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19744   if (Flags.getNode()) {
19745     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19746     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19747   }
19748
19749   return SDValue();
19750 }
19751
19752 // Optimize branch condition evaluation.
19753 //
19754 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19755                                     TargetLowering::DAGCombinerInfo &DCI,
19756                                     const X86Subtarget *Subtarget) {
19757   SDLoc DL(N);
19758   SDValue Chain = N->getOperand(0);
19759   SDValue Dest = N->getOperand(1);
19760   SDValue EFLAGS = N->getOperand(3);
19761   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19762
19763   SDValue Flags;
19764
19765   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19766   if (Flags.getNode()) {
19767     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19768     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19769                        Flags);
19770   }
19771
19772   return SDValue();
19773 }
19774
19775 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19776                                         const X86TargetLowering *XTLI) {
19777   SDValue Op0 = N->getOperand(0);
19778   EVT InVT = Op0->getValueType(0);
19779
19780   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19781   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19782     SDLoc dl(N);
19783     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19784     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19785     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19786   }
19787
19788   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19789   // a 32-bit target where SSE doesn't support i64->FP operations.
19790   if (Op0.getOpcode() == ISD::LOAD) {
19791     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19792     EVT VT = Ld->getValueType(0);
19793     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19794         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19795         !XTLI->getSubtarget()->is64Bit() &&
19796         VT == MVT::i64) {
19797       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19798                                           Ld->getChain(), Op0, DAG);
19799       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19800       return FILDChain;
19801     }
19802   }
19803   return SDValue();
19804 }
19805
19806 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19807 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19808                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19809   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19810   // the result is either zero or one (depending on the input carry bit).
19811   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19812   if (X86::isZeroNode(N->getOperand(0)) &&
19813       X86::isZeroNode(N->getOperand(1)) &&
19814       // We don't have a good way to replace an EFLAGS use, so only do this when
19815       // dead right now.
19816       SDValue(N, 1).use_empty()) {
19817     SDLoc DL(N);
19818     EVT VT = N->getValueType(0);
19819     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19820     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19821                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19822                                            DAG.getConstant(X86::COND_B,MVT::i8),
19823                                            N->getOperand(2)),
19824                                DAG.getConstant(1, VT));
19825     return DCI.CombineTo(N, Res1, CarryOut);
19826   }
19827
19828   return SDValue();
19829 }
19830
19831 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19832 //      (add Y, (setne X, 0)) -> sbb -1, Y
19833 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19834 //      (sub (setne X, 0), Y) -> adc -1, Y
19835 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19836   SDLoc DL(N);
19837
19838   // Look through ZExts.
19839   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19840   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19841     return SDValue();
19842
19843   SDValue SetCC = Ext.getOperand(0);
19844   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19845     return SDValue();
19846
19847   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19848   if (CC != X86::COND_E && CC != X86::COND_NE)
19849     return SDValue();
19850
19851   SDValue Cmp = SetCC.getOperand(1);
19852   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19853       !X86::isZeroNode(Cmp.getOperand(1)) ||
19854       !Cmp.getOperand(0).getValueType().isInteger())
19855     return SDValue();
19856
19857   SDValue CmpOp0 = Cmp.getOperand(0);
19858   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19859                                DAG.getConstant(1, CmpOp0.getValueType()));
19860
19861   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19862   if (CC == X86::COND_NE)
19863     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19864                        DL, OtherVal.getValueType(), OtherVal,
19865                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19866   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19867                      DL, OtherVal.getValueType(), OtherVal,
19868                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19869 }
19870
19871 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19872 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19873                                  const X86Subtarget *Subtarget) {
19874   EVT VT = N->getValueType(0);
19875   SDValue Op0 = N->getOperand(0);
19876   SDValue Op1 = N->getOperand(1);
19877
19878   // Try to synthesize horizontal adds from adds of shuffles.
19879   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19880        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19881       isHorizontalBinOp(Op0, Op1, true))
19882     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19883
19884   return OptimizeConditionalInDecrement(N, DAG);
19885 }
19886
19887 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19888                                  const X86Subtarget *Subtarget) {
19889   SDValue Op0 = N->getOperand(0);
19890   SDValue Op1 = N->getOperand(1);
19891
19892   // X86 can't encode an immediate LHS of a sub. See if we can push the
19893   // negation into a preceding instruction.
19894   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19895     // If the RHS of the sub is a XOR with one use and a constant, invert the
19896     // immediate. Then add one to the LHS of the sub so we can turn
19897     // X-Y -> X+~Y+1, saving one register.
19898     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19899         isa<ConstantSDNode>(Op1.getOperand(1))) {
19900       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19901       EVT VT = Op0.getValueType();
19902       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19903                                    Op1.getOperand(0),
19904                                    DAG.getConstant(~XorC, VT));
19905       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19906                          DAG.getConstant(C->getAPIntValue()+1, VT));
19907     }
19908   }
19909
19910   // Try to synthesize horizontal adds from adds of shuffles.
19911   EVT VT = N->getValueType(0);
19912   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19913        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19914       isHorizontalBinOp(Op0, Op1, true))
19915     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19916
19917   return OptimizeConditionalInDecrement(N, DAG);
19918 }
19919
19920 /// performVZEXTCombine - Performs build vector combines
19921 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19922                                         TargetLowering::DAGCombinerInfo &DCI,
19923                                         const X86Subtarget *Subtarget) {
19924   // (vzext (bitcast (vzext (x)) -> (vzext x)
19925   SDValue In = N->getOperand(0);
19926   while (In.getOpcode() == ISD::BITCAST)
19927     In = In.getOperand(0);
19928
19929   if (In.getOpcode() != X86ISD::VZEXT)
19930     return SDValue();
19931
19932   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19933                      In.getOperand(0));
19934 }
19935
19936 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19937                                              DAGCombinerInfo &DCI) const {
19938   SelectionDAG &DAG = DCI.DAG;
19939   switch (N->getOpcode()) {
19940   default: break;
19941   case ISD::EXTRACT_VECTOR_ELT:
19942     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19943   case ISD::VSELECT:
19944   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19945   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19946   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19947   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19948   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19949   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19950   case ISD::SHL:
19951   case ISD::SRA:
19952   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19953   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19954   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19955   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19956   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19957   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19958   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19959   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19960   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19961   case X86ISD::FXOR:
19962   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19963   case X86ISD::FMIN:
19964   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19965   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19966   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19967   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19968   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19969   case ISD::ANY_EXTEND:
19970   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19971   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19972   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19973   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19974   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
19975   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19976   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19977   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19978   case X86ISD::SHUFP:       // Handle all target specific shuffles
19979   case X86ISD::PALIGNR:
19980   case X86ISD::UNPCKH:
19981   case X86ISD::UNPCKL:
19982   case X86ISD::MOVHLPS:
19983   case X86ISD::MOVLHPS:
19984   case X86ISD::PSHUFD:
19985   case X86ISD::PSHUFHW:
19986   case X86ISD::PSHUFLW:
19987   case X86ISD::MOVSS:
19988   case X86ISD::MOVSD:
19989   case X86ISD::VPERMILP:
19990   case X86ISD::VPERM2X128:
19991   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19992   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19993   }
19994
19995   return SDValue();
19996 }
19997
19998 /// isTypeDesirableForOp - Return true if the target has native support for
19999 /// the specified value type and it is 'desirable' to use the type for the
20000 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20001 /// instruction encodings are longer and some i16 instructions are slow.
20002 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20003   if (!isTypeLegal(VT))
20004     return false;
20005   if (VT != MVT::i16)
20006     return true;
20007
20008   switch (Opc) {
20009   default:
20010     return true;
20011   case ISD::LOAD:
20012   case ISD::SIGN_EXTEND:
20013   case ISD::ZERO_EXTEND:
20014   case ISD::ANY_EXTEND:
20015   case ISD::SHL:
20016   case ISD::SRL:
20017   case ISD::SUB:
20018   case ISD::ADD:
20019   case ISD::MUL:
20020   case ISD::AND:
20021   case ISD::OR:
20022   case ISD::XOR:
20023     return false;
20024   }
20025 }
20026
20027 /// IsDesirableToPromoteOp - This method query the target whether it is
20028 /// beneficial for dag combiner to promote the specified node. If true, it
20029 /// should return the desired promotion type by reference.
20030 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20031   EVT VT = Op.getValueType();
20032   if (VT != MVT::i16)
20033     return false;
20034
20035   bool Promote = false;
20036   bool Commute = false;
20037   switch (Op.getOpcode()) {
20038   default: break;
20039   case ISD::LOAD: {
20040     LoadSDNode *LD = cast<LoadSDNode>(Op);
20041     // If the non-extending load has a single use and it's not live out, then it
20042     // might be folded.
20043     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20044                                                      Op.hasOneUse()*/) {
20045       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20046              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20047         // The only case where we'd want to promote LOAD (rather then it being
20048         // promoted as an operand is when it's only use is liveout.
20049         if (UI->getOpcode() != ISD::CopyToReg)
20050           return false;
20051       }
20052     }
20053     Promote = true;
20054     break;
20055   }
20056   case ISD::SIGN_EXTEND:
20057   case ISD::ZERO_EXTEND:
20058   case ISD::ANY_EXTEND:
20059     Promote = true;
20060     break;
20061   case ISD::SHL:
20062   case ISD::SRL: {
20063     SDValue N0 = Op.getOperand(0);
20064     // Look out for (store (shl (load), x)).
20065     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20066       return false;
20067     Promote = true;
20068     break;
20069   }
20070   case ISD::ADD:
20071   case ISD::MUL:
20072   case ISD::AND:
20073   case ISD::OR:
20074   case ISD::XOR:
20075     Commute = true;
20076     // fallthrough
20077   case ISD::SUB: {
20078     SDValue N0 = Op.getOperand(0);
20079     SDValue N1 = Op.getOperand(1);
20080     if (!Commute && MayFoldLoad(N1))
20081       return false;
20082     // Avoid disabling potential load folding opportunities.
20083     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20084       return false;
20085     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20086       return false;
20087     Promote = true;
20088   }
20089   }
20090
20091   PVT = MVT::i32;
20092   return Promote;
20093 }
20094
20095 //===----------------------------------------------------------------------===//
20096 //                           X86 Inline Assembly Support
20097 //===----------------------------------------------------------------------===//
20098
20099 namespace {
20100   // Helper to match a string separated by whitespace.
20101   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20102     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20103
20104     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20105       StringRef piece(*args[i]);
20106       if (!s.startswith(piece)) // Check if the piece matches.
20107         return false;
20108
20109       s = s.substr(piece.size());
20110       StringRef::size_type pos = s.find_first_not_of(" \t");
20111       if (pos == 0) // We matched a prefix.
20112         return false;
20113
20114       s = s.substr(pos);
20115     }
20116
20117     return s.empty();
20118   }
20119   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20120 }
20121
20122 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20123
20124   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20125     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20126         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20127         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20128
20129       if (AsmPieces.size() == 3)
20130         return true;
20131       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20132         return true;
20133     }
20134   }
20135   return false;
20136 }
20137
20138 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20139   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20140
20141   std::string AsmStr = IA->getAsmString();
20142
20143   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20144   if (!Ty || Ty->getBitWidth() % 16 != 0)
20145     return false;
20146
20147   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20148   SmallVector<StringRef, 4> AsmPieces;
20149   SplitString(AsmStr, AsmPieces, ";\n");
20150
20151   switch (AsmPieces.size()) {
20152   default: return false;
20153   case 1:
20154     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20155     // we will turn this bswap into something that will be lowered to logical
20156     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20157     // lower so don't worry about this.
20158     // bswap $0
20159     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20160         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20161         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20162         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20163         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20164         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20165       // No need to check constraints, nothing other than the equivalent of
20166       // "=r,0" would be valid here.
20167       return IntrinsicLowering::LowerToByteSwap(CI);
20168     }
20169
20170     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20171     if (CI->getType()->isIntegerTy(16) &&
20172         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20173         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20174          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20175       AsmPieces.clear();
20176       const std::string &ConstraintsStr = IA->getConstraintString();
20177       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20178       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20179       if (clobbersFlagRegisters(AsmPieces))
20180         return IntrinsicLowering::LowerToByteSwap(CI);
20181     }
20182     break;
20183   case 3:
20184     if (CI->getType()->isIntegerTy(32) &&
20185         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20186         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20187         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20188         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20189       AsmPieces.clear();
20190       const std::string &ConstraintsStr = IA->getConstraintString();
20191       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20192       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20193       if (clobbersFlagRegisters(AsmPieces))
20194         return IntrinsicLowering::LowerToByteSwap(CI);
20195     }
20196
20197     if (CI->getType()->isIntegerTy(64)) {
20198       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20199       if (Constraints.size() >= 2 &&
20200           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20201           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20202         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20203         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20204             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20205             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20206           return IntrinsicLowering::LowerToByteSwap(CI);
20207       }
20208     }
20209     break;
20210   }
20211   return false;
20212 }
20213
20214 /// getConstraintType - Given a constraint letter, return the type of
20215 /// constraint it is for this target.
20216 X86TargetLowering::ConstraintType
20217 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20218   if (Constraint.size() == 1) {
20219     switch (Constraint[0]) {
20220     case 'R':
20221     case 'q':
20222     case 'Q':
20223     case 'f':
20224     case 't':
20225     case 'u':
20226     case 'y':
20227     case 'x':
20228     case 'Y':
20229     case 'l':
20230       return C_RegisterClass;
20231     case 'a':
20232     case 'b':
20233     case 'c':
20234     case 'd':
20235     case 'S':
20236     case 'D':
20237     case 'A':
20238       return C_Register;
20239     case 'I':
20240     case 'J':
20241     case 'K':
20242     case 'L':
20243     case 'M':
20244     case 'N':
20245     case 'G':
20246     case 'C':
20247     case 'e':
20248     case 'Z':
20249       return C_Other;
20250     default:
20251       break;
20252     }
20253   }
20254   return TargetLowering::getConstraintType(Constraint);
20255 }
20256
20257 /// Examine constraint type and operand type and determine a weight value.
20258 /// This object must already have been set up with the operand type
20259 /// and the current alternative constraint selected.
20260 TargetLowering::ConstraintWeight
20261   X86TargetLowering::getSingleConstraintMatchWeight(
20262     AsmOperandInfo &info, const char *constraint) const {
20263   ConstraintWeight weight = CW_Invalid;
20264   Value *CallOperandVal = info.CallOperandVal;
20265     // If we don't have a value, we can't do a match,
20266     // but allow it at the lowest weight.
20267   if (CallOperandVal == NULL)
20268     return CW_Default;
20269   Type *type = CallOperandVal->getType();
20270   // Look at the constraint type.
20271   switch (*constraint) {
20272   default:
20273     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20274   case 'R':
20275   case 'q':
20276   case 'Q':
20277   case 'a':
20278   case 'b':
20279   case 'c':
20280   case 'd':
20281   case 'S':
20282   case 'D':
20283   case 'A':
20284     if (CallOperandVal->getType()->isIntegerTy())
20285       weight = CW_SpecificReg;
20286     break;
20287   case 'f':
20288   case 't':
20289   case 'u':
20290     if (type->isFloatingPointTy())
20291       weight = CW_SpecificReg;
20292     break;
20293   case 'y':
20294     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20295       weight = CW_SpecificReg;
20296     break;
20297   case 'x':
20298   case 'Y':
20299     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20300         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20301       weight = CW_Register;
20302     break;
20303   case 'I':
20304     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20305       if (C->getZExtValue() <= 31)
20306         weight = CW_Constant;
20307     }
20308     break;
20309   case 'J':
20310     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20311       if (C->getZExtValue() <= 63)
20312         weight = CW_Constant;
20313     }
20314     break;
20315   case 'K':
20316     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20317       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20318         weight = CW_Constant;
20319     }
20320     break;
20321   case 'L':
20322     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20323       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20324         weight = CW_Constant;
20325     }
20326     break;
20327   case 'M':
20328     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20329       if (C->getZExtValue() <= 3)
20330         weight = CW_Constant;
20331     }
20332     break;
20333   case 'N':
20334     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20335       if (C->getZExtValue() <= 0xff)
20336         weight = CW_Constant;
20337     }
20338     break;
20339   case 'G':
20340   case 'C':
20341     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20342       weight = CW_Constant;
20343     }
20344     break;
20345   case 'e':
20346     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20347       if ((C->getSExtValue() >= -0x80000000LL) &&
20348           (C->getSExtValue() <= 0x7fffffffLL))
20349         weight = CW_Constant;
20350     }
20351     break;
20352   case 'Z':
20353     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20354       if (C->getZExtValue() <= 0xffffffff)
20355         weight = CW_Constant;
20356     }
20357     break;
20358   }
20359   return weight;
20360 }
20361
20362 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20363 /// with another that has more specific requirements based on the type of the
20364 /// corresponding operand.
20365 const char *X86TargetLowering::
20366 LowerXConstraint(EVT ConstraintVT) const {
20367   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20368   // 'f' like normal targets.
20369   if (ConstraintVT.isFloatingPoint()) {
20370     if (Subtarget->hasSSE2())
20371       return "Y";
20372     if (Subtarget->hasSSE1())
20373       return "x";
20374   }
20375
20376   return TargetLowering::LowerXConstraint(ConstraintVT);
20377 }
20378
20379 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20380 /// vector.  If it is invalid, don't add anything to Ops.
20381 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20382                                                      std::string &Constraint,
20383                                                      std::vector<SDValue>&Ops,
20384                                                      SelectionDAG &DAG) const {
20385   SDValue Result(0, 0);
20386
20387   // Only support length 1 constraints for now.
20388   if (Constraint.length() > 1) return;
20389
20390   char ConstraintLetter = Constraint[0];
20391   switch (ConstraintLetter) {
20392   default: break;
20393   case 'I':
20394     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20395       if (C->getZExtValue() <= 31) {
20396         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20397         break;
20398       }
20399     }
20400     return;
20401   case 'J':
20402     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20403       if (C->getZExtValue() <= 63) {
20404         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20405         break;
20406       }
20407     }
20408     return;
20409   case 'K':
20410     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20411       if (isInt<8>(C->getSExtValue())) {
20412         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20413         break;
20414       }
20415     }
20416     return;
20417   case 'N':
20418     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20419       if (C->getZExtValue() <= 255) {
20420         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20421         break;
20422       }
20423     }
20424     return;
20425   case 'e': {
20426     // 32-bit signed value
20427     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20428       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20429                                            C->getSExtValue())) {
20430         // Widen to 64 bits here to get it sign extended.
20431         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20432         break;
20433       }
20434     // FIXME gcc accepts some relocatable values here too, but only in certain
20435     // memory models; it's complicated.
20436     }
20437     return;
20438   }
20439   case 'Z': {
20440     // 32-bit unsigned value
20441     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20442       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20443                                            C->getZExtValue())) {
20444         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20445         break;
20446       }
20447     }
20448     // FIXME gcc accepts some relocatable values here too, but only in certain
20449     // memory models; it's complicated.
20450     return;
20451   }
20452   case 'i': {
20453     // Literal immediates are always ok.
20454     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20455       // Widen to 64 bits here to get it sign extended.
20456       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20457       break;
20458     }
20459
20460     // In any sort of PIC mode addresses need to be computed at runtime by
20461     // adding in a register or some sort of table lookup.  These can't
20462     // be used as immediates.
20463     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20464       return;
20465
20466     // If we are in non-pic codegen mode, we allow the address of a global (with
20467     // an optional displacement) to be used with 'i'.
20468     GlobalAddressSDNode *GA = 0;
20469     int64_t Offset = 0;
20470
20471     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20472     while (1) {
20473       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20474         Offset += GA->getOffset();
20475         break;
20476       } else if (Op.getOpcode() == ISD::ADD) {
20477         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20478           Offset += C->getZExtValue();
20479           Op = Op.getOperand(0);
20480           continue;
20481         }
20482       } else if (Op.getOpcode() == ISD::SUB) {
20483         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20484           Offset += -C->getZExtValue();
20485           Op = Op.getOperand(0);
20486           continue;
20487         }
20488       }
20489
20490       // Otherwise, this isn't something we can handle, reject it.
20491       return;
20492     }
20493
20494     const GlobalValue *GV = GA->getGlobal();
20495     // If we require an extra load to get this address, as in PIC mode, we
20496     // can't accept it.
20497     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20498                                                         getTargetMachine())))
20499       return;
20500
20501     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20502                                         GA->getValueType(0), Offset);
20503     break;
20504   }
20505   }
20506
20507   if (Result.getNode()) {
20508     Ops.push_back(Result);
20509     return;
20510   }
20511   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20512 }
20513
20514 std::pair<unsigned, const TargetRegisterClass*>
20515 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20516                                                 MVT VT) const {
20517   // First, see if this is a constraint that directly corresponds to an LLVM
20518   // register class.
20519   if (Constraint.size() == 1) {
20520     // GCC Constraint Letters
20521     switch (Constraint[0]) {
20522     default: break;
20523       // TODO: Slight differences here in allocation order and leaving
20524       // RIP in the class. Do they matter any more here than they do
20525       // in the normal allocation?
20526     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20527       if (Subtarget->is64Bit()) {
20528         if (VT == MVT::i32 || VT == MVT::f32)
20529           return std::make_pair(0U, &X86::GR32RegClass);
20530         if (VT == MVT::i16)
20531           return std::make_pair(0U, &X86::GR16RegClass);
20532         if (VT == MVT::i8 || VT == MVT::i1)
20533           return std::make_pair(0U, &X86::GR8RegClass);
20534         if (VT == MVT::i64 || VT == MVT::f64)
20535           return std::make_pair(0U, &X86::GR64RegClass);
20536         break;
20537       }
20538       // 32-bit fallthrough
20539     case 'Q':   // Q_REGS
20540       if (VT == MVT::i32 || VT == MVT::f32)
20541         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20542       if (VT == MVT::i16)
20543         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20544       if (VT == MVT::i8 || VT == MVT::i1)
20545         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20546       if (VT == MVT::i64)
20547         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20548       break;
20549     case 'r':   // GENERAL_REGS
20550     case 'l':   // INDEX_REGS
20551       if (VT == MVT::i8 || VT == MVT::i1)
20552         return std::make_pair(0U, &X86::GR8RegClass);
20553       if (VT == MVT::i16)
20554         return std::make_pair(0U, &X86::GR16RegClass);
20555       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20556         return std::make_pair(0U, &X86::GR32RegClass);
20557       return std::make_pair(0U, &X86::GR64RegClass);
20558     case 'R':   // LEGACY_REGS
20559       if (VT == MVT::i8 || VT == MVT::i1)
20560         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20561       if (VT == MVT::i16)
20562         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20563       if (VT == MVT::i32 || !Subtarget->is64Bit())
20564         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20565       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20566     case 'f':  // FP Stack registers.
20567       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20568       // value to the correct fpstack register class.
20569       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20570         return std::make_pair(0U, &X86::RFP32RegClass);
20571       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20572         return std::make_pair(0U, &X86::RFP64RegClass);
20573       return std::make_pair(0U, &X86::RFP80RegClass);
20574     case 'y':   // MMX_REGS if MMX allowed.
20575       if (!Subtarget->hasMMX()) break;
20576       return std::make_pair(0U, &X86::VR64RegClass);
20577     case 'Y':   // SSE_REGS if SSE2 allowed
20578       if (!Subtarget->hasSSE2()) break;
20579       // FALL THROUGH.
20580     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20581       if (!Subtarget->hasSSE1()) break;
20582
20583       switch (VT.SimpleTy) {
20584       default: break;
20585       // Scalar SSE types.
20586       case MVT::f32:
20587       case MVT::i32:
20588         return std::make_pair(0U, &X86::FR32RegClass);
20589       case MVT::f64:
20590       case MVT::i64:
20591         return std::make_pair(0U, &X86::FR64RegClass);
20592       // Vector types.
20593       case MVT::v16i8:
20594       case MVT::v8i16:
20595       case MVT::v4i32:
20596       case MVT::v2i64:
20597       case MVT::v4f32:
20598       case MVT::v2f64:
20599         return std::make_pair(0U, &X86::VR128RegClass);
20600       // AVX types.
20601       case MVT::v32i8:
20602       case MVT::v16i16:
20603       case MVT::v8i32:
20604       case MVT::v4i64:
20605       case MVT::v8f32:
20606       case MVT::v4f64:
20607         return std::make_pair(0U, &X86::VR256RegClass);
20608       case MVT::v8f64:
20609       case MVT::v16f32:
20610       case MVT::v16i32:
20611       case MVT::v8i64:
20612         return std::make_pair(0U, &X86::VR512RegClass);
20613       }
20614       break;
20615     }
20616   }
20617
20618   // Use the default implementation in TargetLowering to convert the register
20619   // constraint into a member of a register class.
20620   std::pair<unsigned, const TargetRegisterClass*> Res;
20621   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20622
20623   // Not found as a standard register?
20624   if (Res.second == 0) {
20625     // Map st(0) -> st(7) -> ST0
20626     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20627         tolower(Constraint[1]) == 's' &&
20628         tolower(Constraint[2]) == 't' &&
20629         Constraint[3] == '(' &&
20630         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20631         Constraint[5] == ')' &&
20632         Constraint[6] == '}') {
20633
20634       Res.first = X86::ST0+Constraint[4]-'0';
20635       Res.second = &X86::RFP80RegClass;
20636       return Res;
20637     }
20638
20639     // GCC allows "st(0)" to be called just plain "st".
20640     if (StringRef("{st}").equals_lower(Constraint)) {
20641       Res.first = X86::ST0;
20642       Res.second = &X86::RFP80RegClass;
20643       return Res;
20644     }
20645
20646     // flags -> EFLAGS
20647     if (StringRef("{flags}").equals_lower(Constraint)) {
20648       Res.first = X86::EFLAGS;
20649       Res.second = &X86::CCRRegClass;
20650       return Res;
20651     }
20652
20653     // 'A' means EAX + EDX.
20654     if (Constraint == "A") {
20655       Res.first = X86::EAX;
20656       Res.second = &X86::GR32_ADRegClass;
20657       return Res;
20658     }
20659     return Res;
20660   }
20661
20662   // Otherwise, check to see if this is a register class of the wrong value
20663   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20664   // turn into {ax},{dx}.
20665   if (Res.second->hasType(VT))
20666     return Res;   // Correct type already, nothing to do.
20667
20668   // All of the single-register GCC register classes map their values onto
20669   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20670   // really want an 8-bit or 32-bit register, map to the appropriate register
20671   // class and return the appropriate register.
20672   if (Res.second == &X86::GR16RegClass) {
20673     if (VT == MVT::i8 || VT == MVT::i1) {
20674       unsigned DestReg = 0;
20675       switch (Res.first) {
20676       default: break;
20677       case X86::AX: DestReg = X86::AL; break;
20678       case X86::DX: DestReg = X86::DL; break;
20679       case X86::CX: DestReg = X86::CL; break;
20680       case X86::BX: DestReg = X86::BL; break;
20681       }
20682       if (DestReg) {
20683         Res.first = DestReg;
20684         Res.second = &X86::GR8RegClass;
20685       }
20686     } else if (VT == MVT::i32 || VT == MVT::f32) {
20687       unsigned DestReg = 0;
20688       switch (Res.first) {
20689       default: break;
20690       case X86::AX: DestReg = X86::EAX; break;
20691       case X86::DX: DestReg = X86::EDX; break;
20692       case X86::CX: DestReg = X86::ECX; break;
20693       case X86::BX: DestReg = X86::EBX; break;
20694       case X86::SI: DestReg = X86::ESI; break;
20695       case X86::DI: DestReg = X86::EDI; break;
20696       case X86::BP: DestReg = X86::EBP; break;
20697       case X86::SP: DestReg = X86::ESP; break;
20698       }
20699       if (DestReg) {
20700         Res.first = DestReg;
20701         Res.second = &X86::GR32RegClass;
20702       }
20703     } else if (VT == MVT::i64 || VT == MVT::f64) {
20704       unsigned DestReg = 0;
20705       switch (Res.first) {
20706       default: break;
20707       case X86::AX: DestReg = X86::RAX; break;
20708       case X86::DX: DestReg = X86::RDX; break;
20709       case X86::CX: DestReg = X86::RCX; break;
20710       case X86::BX: DestReg = X86::RBX; break;
20711       case X86::SI: DestReg = X86::RSI; break;
20712       case X86::DI: DestReg = X86::RDI; break;
20713       case X86::BP: DestReg = X86::RBP; break;
20714       case X86::SP: DestReg = X86::RSP; break;
20715       }
20716       if (DestReg) {
20717         Res.first = DestReg;
20718         Res.second = &X86::GR64RegClass;
20719       }
20720     }
20721   } else if (Res.second == &X86::FR32RegClass ||
20722              Res.second == &X86::FR64RegClass ||
20723              Res.second == &X86::VR128RegClass ||
20724              Res.second == &X86::VR256RegClass ||
20725              Res.second == &X86::FR32XRegClass ||
20726              Res.second == &X86::FR64XRegClass ||
20727              Res.second == &X86::VR128XRegClass ||
20728              Res.second == &X86::VR256XRegClass ||
20729              Res.second == &X86::VR512RegClass) {
20730     // Handle references to XMM physical registers that got mapped into the
20731     // wrong class.  This can happen with constraints like {xmm0} where the
20732     // target independent register mapper will just pick the first match it can
20733     // find, ignoring the required type.
20734
20735     if (VT == MVT::f32 || VT == MVT::i32)
20736       Res.second = &X86::FR32RegClass;
20737     else if (VT == MVT::f64 || VT == MVT::i64)
20738       Res.second = &X86::FR64RegClass;
20739     else if (X86::VR128RegClass.hasType(VT))
20740       Res.second = &X86::VR128RegClass;
20741     else if (X86::VR256RegClass.hasType(VT))
20742       Res.second = &X86::VR256RegClass;
20743     else if (X86::VR512RegClass.hasType(VT))
20744       Res.second = &X86::VR512RegClass;
20745   }
20746
20747   return Res;
20748 }