Rip out X86-specific vector SDIV lowering, make the corresponding DAGCombiner transfo...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <bitset>
51 #include <cctype>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "x86-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63                                 SelectionDAG &DAG, SDLoc dl,
64                                 unsigned vectorWidth) {
65   assert((vectorWidth == 128 || vectorWidth == 256) &&
66          "Unsupported vector width");
67   EVT VT = Vec.getValueType();
68   EVT ElVT = VT.getVectorElementType();
69   unsigned Factor = VT.getSizeInBits()/vectorWidth;
70   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71                                   VT.getVectorNumElements()/Factor);
72
73   // Extract from UNDEF is UNDEF.
74   if (Vec.getOpcode() == ISD::UNDEF)
75     return DAG.getUNDEF(ResultVT);
76
77   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
78   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79
80   // This is the index of the first element of the vectorWidth-bit chunk
81   // we want.
82   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
83                                * ElemsPerChunk);
84
85   // If the input is a buildvector just emit a smaller one.
86   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89
90   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
92                                VecIdx);
93
94   return Result;
95
96 }
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104                                    SelectionDAG &DAG, SDLoc dl) {
105   assert((Vec.getValueType().is256BitVector() ||
106           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
108 }
109
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112                                    SelectionDAG &DAG, SDLoc dl) {
113   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
115 }
116
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118                                unsigned IdxVal, SelectionDAG &DAG,
119                                SDLoc dl, unsigned vectorWidth) {
120   assert((vectorWidth == 128 || vectorWidth == 256) &&
121          "Unsupported vector width");
122   // Inserting UNDEF is Result
123   if (Vec.getOpcode() == ISD::UNDEF)
124     return Result;
125   EVT VT = Vec.getValueType();
126   EVT ElVT = VT.getVectorElementType();
127   EVT ResultVT = Result.getValueType();
128
129   // Insert the relevant vectorWidth bits.
130   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131
132   // This is the index of the first element of the vectorWidth-bit chunk
133   // we want.
134   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
135                                * ElemsPerChunk);
136
137   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
139                      VecIdx);
140 }
141 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference.  Idx is an index in the 128 bits
145 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148                                   unsigned IdxVal, SelectionDAG &DAG,
149                                   SDLoc dl) {
150   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
152 }
153
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155                                   unsigned IdxVal, SelectionDAG &DAG,
156                                   SDLoc dl) {
157   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
159 }
160
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166                                    unsigned NumElems, SelectionDAG &DAG,
167                                    SDLoc dl) {
168   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
170 }
171
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173                                    unsigned NumElems, SelectionDAG &DAG,
174                                    SDLoc dl) {
175   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
177 }
178
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181   bool is64Bit = Subtarget->is64Bit();
182
183   if (Subtarget->isTargetMacho()) {
184     if (is64Bit)
185       return new X86_64MachoTargetObjectFile();
186     return new TargetLoweringObjectFileMachO();
187   }
188
189   if (Subtarget->isTargetLinux())
190     return new X86LinuxTargetObjectFile();
191   if (Subtarget->isTargetELF())
192     return new TargetLoweringObjectFileELF();
193   if (Subtarget->isTargetKnownWindowsMSVC())
194     return new X86WindowsTargetObjectFile();
195   if (Subtarget->isTargetCOFF())
196     return new TargetLoweringObjectFileCOFF();
197   llvm_unreachable("unknown subtarget type");
198 }
199
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201   : TargetLowering(TM, createTLOF(TM)) {
202   Subtarget = &TM.getSubtarget<X86Subtarget>();
203   X86ScalarSSEf64 = Subtarget->hasSSE2();
204   X86ScalarSSEf32 = Subtarget->hasSSE1();
205   TD = getDataLayout();
206
207   resetOperationActions();
208 }
209
210 void X86TargetLowering::resetOperationActions() {
211   const TargetMachine &TM = getTargetMachine();
212   static bool FirstTimeThrough = true;
213
214   // If none of the target options have changed, then we don't need to reset the
215   // operation actions.
216   if (!FirstTimeThrough && TO == TM.Options) return;
217
218   if (!FirstTimeThrough) {
219     // Reinitialize the actions.
220     initActions();
221     FirstTimeThrough = false;
222   }
223
224   TO = TM.Options;
225
226   // Set up the TargetLowering object.
227   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228
229   // X86 is weird, it always uses i8 for shift amounts and setcc results.
230   setBooleanContents(ZeroOrOneBooleanContent);
231   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233
234   // For 64-bit since we have so many registers use the ILP scheduler, for
235   // 32-bit code use the register pressure specific scheduling.
236   // For Atom, always use ILP scheduling.
237   if (Subtarget->isAtom())
238     setSchedulingPreference(Sched::ILP);
239   else if (Subtarget->is64Bit())
240     setSchedulingPreference(Sched::ILP);
241   else
242     setSchedulingPreference(Sched::RegPressure);
243   const X86RegisterInfo *RegInfo =
244     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246
247   // Bypass expensive divides on Atom when compiling with O2
248   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249     addBypassSlowDiv(32, 8);
250     if (Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   // SETOEQ and SETUNE require checking two conditions.
306   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312
313   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314   // operation.
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
318
319   if (Subtarget->is64Bit()) {
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
322   } else if (!TM.Options.UseSoftFloat) {
323     // We have an algorithm for SSE2->double, and we turn this into a
324     // 64-bit FILD followed by conditional FADD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
326     // We have an algorithm for SSE2, and we turn this into a 64-bit
327     // FILD for other targets.
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
329   }
330
331   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332   // this operation.
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
334   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
335
336   if (!TM.Options.UseSoftFloat) {
337     // SSE has no i16 to fp conversion, only i32
338     if (X86ScalarSSEf32) {
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
340       // f32 and f64 cases are Legal, f80 case is not
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     } else {
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
344       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
345     }
346   } else {
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
349   }
350
351   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
352   // are Legal, f80 is custom lowered.
353   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
354   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
355
356   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357   // this operation.
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
359   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
360
361   if (X86ScalarSSEf32) {
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
363     // f32 and f64 cases are Legal, f80 case is not
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   } else {
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
367     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
368   }
369
370   // Handle FP_TO_UINT by promoting the destination to a larger signed
371   // conversion.
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
375
376   if (Subtarget->is64Bit()) {
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
378     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
379   } else if (!TM.Options.UseSoftFloat) {
380     // Since AVX is a superset of SSE3, only check for SSE here.
381     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382       // Expand FP_TO_UINT into a select.
383       // FIXME: We would like to use a Custom expander here eventually to do
384       // the optimal thing for SSE vs. the default expansion in the legalizer.
385       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
386     else
387       // With SSE3 we can use fisttpll to convert to a signed i64; without
388       // SSE, we're stuck with a fistpll.
389       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
390   }
391
392   if (isTargetFTOL()) {
393     // Use the _ftol2 runtime function, which has a pseudo-instruction
394     // to handle its weird calling convention.
395     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
396   }
397
398   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399   if (!X86ScalarSSEf64) {
400     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
401     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
402     if (Subtarget->is64Bit()) {
403       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
404       // Without SSE, i64->f64 goes through memory.
405       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
406     }
407   }
408
409   // Scalar integer divide and remainder are lowered to use operations that
410   // produce two results, to match the available instructions. This exposes
411   // the two-result form to trivial CSE, which is able to combine x/y and x%y
412   // into a single instruction.
413   //
414   // Scalar integer multiply-high is also lowered to use two-result
415   // operations, to match the available instructions. However, plain multiply
416   // (low) operations are left as Legal, as there are single-result
417   // instructions for this in x86. Using the two-result multiply instructions
418   // when both high and low results are needed must be arranged by dagcombine.
419   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420     MVT VT = IntVTs[i];
421     setOperationAction(ISD::MULHS, VT, Expand);
422     setOperationAction(ISD::MULHU, VT, Expand);
423     setOperationAction(ISD::SDIV, VT, Expand);
424     setOperationAction(ISD::UDIV, VT, Expand);
425     setOperationAction(ISD::SREM, VT, Expand);
426     setOperationAction(ISD::UREM, VT, Expand);
427
428     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429     setOperationAction(ISD::ADDC, VT, Custom);
430     setOperationAction(ISD::ADDE, VT, Custom);
431     setOperationAction(ISD::SUBC, VT, Custom);
432     setOperationAction(ISD::SUBE, VT, Custom);
433   }
434
435   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
436   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
437   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
444   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
445   if (Subtarget->is64Bit())
446     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
450   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
454   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
455
456   // Promote the i8 variants and force them on up to i32 which has a shorter
457   // encoding.
458   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
459   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
460   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
462   if (Subtarget->hasBMI()) {
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
464     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467   } else {
468     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
469     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
470     if (Subtarget->is64Bit())
471       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasLZCNT()) {
475     // When promoting the i8 variants, force them to i32 for a shorter
476     // encoding.
477     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
478     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
482     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
483     if (Subtarget->is64Bit())
484       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485   } else {
486     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
492     if (Subtarget->is64Bit()) {
493       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
494       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495     }
496   }
497
498   if (Subtarget->hasPOPCNT()) {
499     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
500   } else {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
503     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
506   }
507
508   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
509
510   if (!Subtarget->hasMOVBE())
511     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
512
513   // These should be promoted to a larger select which is supported.
514   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
515   // X86 wants to expand cmov itself.
516   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
528   if (Subtarget->is64Bit()) {
529     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
530     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
531   }
532   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
533   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535   // support continuation, user-level threading, and etc.. As a result, no
536   // other SjLj exception interfaces are implemented and please don't build
537   // your own exception handling based on them.
538   // LLVM/Clang supports zero-cost DWARF exception handling.
539   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
541
542   // Darwin ABI issue.
543   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
544   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
546   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
547   if (Subtarget->is64Bit())
548     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
550   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
551   if (Subtarget->is64Bit()) {
552     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
553     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
554     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
555     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
556     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
557   }
558   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
561   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
562   if (Subtarget->is64Bit()) {
563     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
565     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
566   }
567
568   if (Subtarget->hasSSE1())
569     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
570
571   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
572
573   // Expand certain atomics
574   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575     MVT VT = IntVTs[i];
576     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
579   }
580
581   if (!Subtarget->is64Bit()) {
582     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
594   }
595
596   if (Subtarget->hasCmpxchg16b()) {
597     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
598   }
599
600   // FIXME - use subtarget debug flags
601   if (!Subtarget->isTargetDarwin() &&
602       !Subtarget->isTargetELF() &&
603       !Subtarget->isTargetCygMing()) {
604     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
605   }
606
607   if (Subtarget->is64Bit()) {
608     setExceptionPointerRegister(X86::RAX);
609     setExceptionSelectorRegister(X86::RDX);
610   } else {
611     setExceptionPointerRegister(X86::EAX);
612     setExceptionSelectorRegister(X86::EDX);
613   }
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616
617   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619
620   setOperationAction(ISD::TRAP, MVT::Other, Legal);
621   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622
623   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
625   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
626   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627     // TargetInfo::X86_64ABIBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
630   } else {
631     // TargetInfo::CharPtrBuiltinVaList
632     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
633     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
634   }
635
636   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
637   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
638
639   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                      MVT::i64 : MVT::i32, Custom);
641
642   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643     // f32 and f64 use SSE.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f32, &X86::FR32RegClass);
646     addRegisterClass(MVT::f64, &X86::FR64RegClass);
647
648     // Use ANDPD to simulate FABS.
649     setOperationAction(ISD::FABS , MVT::f64, Custom);
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f64, Custom);
654     setOperationAction(ISD::FNEG , MVT::f32, Custom);
655
656     // Use ANDPD and ORPD to simulate FCOPYSIGN.
657     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659
660     // Lower this to FGETSIGNx86 plus an AND.
661     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
663
664     // We don't support sin/cos/fmod
665     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
666     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
667     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
669     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
670     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
671
672     // Expand FP immediates into loads from the stack, except for the special
673     // cases we handle.
674     addLegalFPImmediate(APFloat(+0.0)); // xorpd
675     addLegalFPImmediate(APFloat(+0.0f)); // xorps
676   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677     // Use SSE for f32, x87 for f64.
678     // Set up the FP register classes.
679     addRegisterClass(MVT::f32, &X86::FR32RegClass);
680     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681
682     // Use ANDPS to simulate FABS.
683     setOperationAction(ISD::FABS , MVT::f32, Custom);
684
685     // Use XORP to simulate FNEG.
686     setOperationAction(ISD::FNEG , MVT::f32, Custom);
687
688     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
689
690     // Use ANDPS and ORPS to simulate FCOPYSIGN.
691     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
693
694     // We don't support sin/cos/fmod
695     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
696     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
697     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698
699     // Special cases we handle for FP constants.
700     addLegalFPImmediate(APFloat(+0.0f)); // xorps
701     addLegalFPImmediate(APFloat(+0.0)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
705
706     if (!TM.Options.UnsafeFPMath) {
707       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
708       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
709       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
710     }
711   } else if (!TM.Options.UseSoftFloat) {
712     // f32 and f64 in x87.
713     // Set up the FP register classes.
714     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
716
717     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
718     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
721
722     if (!TM.Options.UnsafeFPMath) {
723       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
724       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
726       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
729     }
730     addLegalFPImmediate(APFloat(+0.0)); // FLD0
731     addLegalFPImmediate(APFloat(+1.0)); // FLD1
732     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
738   }
739
740   // We don't support FMA.
741   setOperationAction(ISD::FMA, MVT::f64, Expand);
742   setOperationAction(ISD::FMA, MVT::f32, Expand);
743
744   // Long double always uses X87.
745   if (!TM.Options.UseSoftFloat) {
746     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
748     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
749     {
750       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751       addLegalFPImmediate(TmpFlt);  // FLD0
752       TmpFlt.changeSign();
753       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
754
755       bool ignored;
756       APFloat TmpFlt2(+1.0);
757       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
758                       &ignored);
759       addLegalFPImmediate(TmpFlt2);  // FLD1
760       TmpFlt2.changeSign();
761       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
762     }
763
764     if (!TM.Options.UnsafeFPMath) {
765       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
766       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
767       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
768     }
769
770     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
772     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
774     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775     setOperationAction(ISD::FMA, MVT::f80, Expand);
776   }
777
778   // Always use a library call for pow.
779   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
781   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
782
783   setOperationAction(ISD::FLOG, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP, MVT::f80, Expand);
787   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
788
789   // First set operation action for all vector types to either promote
790   // (for widening) or expand (for scalarization). Then we will selectively
791   // turn on ones that can be effectively codegen'd.
792   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794     MVT VT = (MVT::SimpleValueType)i;
795     setOperationAction(ISD::ADD , VT, Expand);
796     setOperationAction(ISD::SUB , VT, Expand);
797     setOperationAction(ISD::FADD, VT, Expand);
798     setOperationAction(ISD::FNEG, VT, Expand);
799     setOperationAction(ISD::FSUB, VT, Expand);
800     setOperationAction(ISD::MUL , VT, Expand);
801     setOperationAction(ISD::FMUL, VT, Expand);
802     setOperationAction(ISD::SDIV, VT, Expand);
803     setOperationAction(ISD::UDIV, VT, Expand);
804     setOperationAction(ISD::FDIV, VT, Expand);
805     setOperationAction(ISD::SREM, VT, Expand);
806     setOperationAction(ISD::UREM, VT, Expand);
807     setOperationAction(ISD::LOAD, VT, Expand);
808     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813     setOperationAction(ISD::FABS, VT, Expand);
814     setOperationAction(ISD::FSIN, VT, Expand);
815     setOperationAction(ISD::FSINCOS, VT, Expand);
816     setOperationAction(ISD::FCOS, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FREM, VT, Expand);
819     setOperationAction(ISD::FMA,  VT, Expand);
820     setOperationAction(ISD::FPOWI, VT, Expand);
821     setOperationAction(ISD::FSQRT, VT, Expand);
822     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823     setOperationAction(ISD::FFLOOR, VT, Expand);
824     setOperationAction(ISD::FCEIL, VT, Expand);
825     setOperationAction(ISD::FTRUNC, VT, Expand);
826     setOperationAction(ISD::FRINT, VT, Expand);
827     setOperationAction(ISD::FNEARBYINT, VT, Expand);
828     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829     setOperationAction(ISD::MULHS, VT, Expand);
830     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::MULHU, VT, Expand);
832     setOperationAction(ISD::SDIVREM, VT, Expand);
833     setOperationAction(ISD::UDIVREM, VT, Expand);
834     setOperationAction(ISD::FPOW, VT, Expand);
835     setOperationAction(ISD::CTPOP, VT, Expand);
836     setOperationAction(ISD::CTTZ, VT, Expand);
837     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::CTLZ, VT, Expand);
839     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::SHL, VT, Expand);
841     setOperationAction(ISD::SRA, VT, Expand);
842     setOperationAction(ISD::SRL, VT, Expand);
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845     setOperationAction(ISD::BSWAP, VT, Expand);
846     setOperationAction(ISD::SETCC, VT, Expand);
847     setOperationAction(ISD::FLOG, VT, Expand);
848     setOperationAction(ISD::FLOG2, VT, Expand);
849     setOperationAction(ISD::FLOG10, VT, Expand);
850     setOperationAction(ISD::FEXP, VT, Expand);
851     setOperationAction(ISD::FEXP2, VT, Expand);
852     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857     setOperationAction(ISD::TRUNCATE, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861     setOperationAction(ISD::VSELECT, VT, Expand);
862     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864       setTruncStoreAction(VT,
865                           (MVT::SimpleValueType)InnerVT, Expand);
866     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869   }
870
871   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872   // with -msoft-float, disable use of MMX as well.
873   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875     // No operations on x86mmx supported, everything uses intrinsics.
876   }
877
878   // MMX-sized vectors (other than x86mmx) are expected to be expanded
879   // into smaller operations.
880   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
881   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
884   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
885   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
886   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
887   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
888   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
889   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
890   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
891   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
892   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
894   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
895   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
900   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
902   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
909
910   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912
913     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
919     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
920     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
922     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
925   }
926
927   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929
930     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931     // registers cannot be used even for integer operations.
932     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936
937     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
938     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
939     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
940     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
941     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
942     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
943     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
944     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
945     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
947     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
948     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
949     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
954     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
955     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
956
957     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
961
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
963     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
967
968     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
969     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
970       MVT VT = (MVT::SimpleValueType)i;
971       // Do not attempt to custom lower non-power-of-2 vectors
972       if (!isPowerOf2_32(VT.getVectorNumElements()))
973         continue;
974       // Do not attempt to custom lower non-128-bit vectors
975       if (!VT.is128BitVector())
976         continue;
977       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
978       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
979       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
980     }
981
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
983     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
985     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
988
989     if (Subtarget->is64Bit()) {
990       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
991       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
992     }
993
994     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
995     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996       MVT VT = (MVT::SimpleValueType)i;
997
998       // Do not attempt to promote non-128-bit vectors
999       if (!VT.is128BitVector())
1000         continue;
1001
1002       setOperationAction(ISD::AND,    VT, Promote);
1003       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1004       setOperationAction(ISD::OR,     VT, Promote);
1005       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1006       setOperationAction(ISD::XOR,    VT, Promote);
1007       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1008       setOperationAction(ISD::LOAD,   VT, Promote);
1009       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1010       setOperationAction(ISD::SELECT, VT, Promote);
1011       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1012     }
1013
1014     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1015
1016     // Custom lower v2i64 and v2f64 selects.
1017     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1019     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1020     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1021
1022     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1023     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1024
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1026     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1027     // As there is no 64-bit GPR available, we need build a special custom
1028     // sequence to convert from v2i32 to v2f32.
1029     if (!Subtarget->is64Bit())
1030       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1031
1032     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1033     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1034
1035     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1036   }
1037
1038   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1039     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1040     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1041     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1042     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1043     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1047     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1049
1050     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1051     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1052     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1053     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1054     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1055     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1056     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1057     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1058     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1059     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1060
1061     // FIXME: Do we need to handle scalar-to-vector here?
1062     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1063
1064     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1069
1070     // i8 and i16 vectors are custom , because the source register and source
1071     // source memory operand types are not the same width.  f32 vectors are
1072     // custom since the immediate controlling the insert encodes additional
1073     // information.
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1078
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1083
1084     // FIXME: these should be Legal but thats only for the case where
1085     // the index is constant.  For now custom expand to deal with that.
1086     if (Subtarget->is64Bit()) {
1087       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1088       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089     }
1090   }
1091
1092   if (Subtarget->hasSSE2()) {
1093     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1101
1102     // In the customized shift lowering, the legal cases in AVX2 will be
1103     // recognized.
1104     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1105     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1106
1107     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1111   }
1112
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::SETCC,             MVT::v32i8, Custom);
1176     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1177     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1179
1180     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1181     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1182     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1183
1184     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1185     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1186     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1188
1189     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1190     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1192     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1193     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1195     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1196     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1198     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1199     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1201
1202     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1203       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1204       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1207       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1208       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1209     }
1210
1211     if (Subtarget->hasInt256()) {
1212       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1213       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1216
1217       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1218       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1221
1222       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1223       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1224       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1225       // Don't lower v32i8 because there is no 128-bit byte mul
1226
1227       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1228
1229       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1230     } else {
1231       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1232       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1235
1236       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1237       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1240
1241       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1242       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1243       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1244       // Don't lower v32i8 because there is no 128-bit byte mul
1245     }
1246
1247     // In the customized shift lowering, the legal cases in AVX2 will be
1248     // recognized.
1249     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1250     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1251
1252     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1253     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1254
1255     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1256
1257     // Custom lower several nodes for 256-bit types.
1258     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1259              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1260       MVT VT = (MVT::SimpleValueType)i;
1261
1262       // Extract subvector is special because the value type
1263       // (result) is 128-bit but the source is 256-bit wide.
1264       if (VT.is128BitVector())
1265         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1266
1267       // Do not attempt to custom lower other non-256-bit vectors
1268       if (!VT.is256BitVector())
1269         continue;
1270
1271       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1272       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1273       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1274       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1275       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1276       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1277       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1278     }
1279
1280     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1281     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1282       MVT VT = (MVT::SimpleValueType)i;
1283
1284       // Do not attempt to promote non-256-bit vectors
1285       if (!VT.is256BitVector())
1286         continue;
1287
1288       setOperationAction(ISD::AND,    VT, Promote);
1289       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1290       setOperationAction(ISD::OR,     VT, Promote);
1291       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1292       setOperationAction(ISD::XOR,    VT, Promote);
1293       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1294       setOperationAction(ISD::LOAD,   VT, Promote);
1295       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1296       setOperationAction(ISD::SELECT, VT, Promote);
1297       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1298     }
1299   }
1300
1301   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1302     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1303     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1304     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1305     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1306
1307     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1308     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1309     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1310
1311     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1312     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1313     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1314     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1315     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1316     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1317     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1322
1323     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1329
1330     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1331     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1335     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1336     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1337     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1338
1339     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1340     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1342     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1343     if (Subtarget->is64Bit()) {
1344       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1345       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1346       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1347       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1348     }
1349     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1352     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1357     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1358     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1359
1360     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1361     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1362     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1363     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1366     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1367     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1370     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1373
1374     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1375     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1376     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1380
1381     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1382     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1383
1384     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1385
1386     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1387     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1388     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1389     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1390     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1391     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1392     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1393     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1394     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1395
1396     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1397     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1398
1399     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1400     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1403
1404     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1405     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1406
1407     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1408     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1409
1410     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1414     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1415     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1416     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1417     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1418     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1419
1420     // Custom lower several nodes.
1421     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1422              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1423       MVT VT = (MVT::SimpleValueType)i;
1424
1425       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1426       // Extract subvector is special because the value type
1427       // (result) is 256/128-bit but the source is 512-bit wide.
1428       if (VT.is128BitVector() || VT.is256BitVector())
1429         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1430
1431       if (VT.getVectorElementType() == MVT::i1)
1432         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1433
1434       // Do not attempt to custom lower other non-512-bit vectors
1435       if (!VT.is512BitVector())
1436         continue;
1437
1438       if ( EltSize >= 32) {
1439         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1440         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1441         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1442         setOperationAction(ISD::VSELECT,             VT, Legal);
1443         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1444         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1445         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1446       }
1447     }
1448     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1449       MVT VT = (MVT::SimpleValueType)i;
1450
1451       // Do not attempt to promote non-256-bit vectors
1452       if (!VT.is512BitVector())
1453         continue;
1454
1455       setOperationAction(ISD::SELECT, VT, Promote);
1456       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1457     }
1458   }// has  AVX-512
1459
1460   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1461   // of this type with custom code.
1462   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1463            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1464     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1465                        Custom);
1466   }
1467
1468   // We want to custom lower some of our intrinsics.
1469   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1470   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1471   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1472   if (!Subtarget->is64Bit())
1473     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1474
1475   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1476   // handle type legalization for these operations here.
1477   //
1478   // FIXME: We really should do custom legalization for addition and
1479   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1480   // than generic legalization for 64-bit multiplication-with-overflow, though.
1481   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1482     // Add/Sub/Mul with overflow operations are custom lowered.
1483     MVT VT = IntVTs[i];
1484     setOperationAction(ISD::SADDO, VT, Custom);
1485     setOperationAction(ISD::UADDO, VT, Custom);
1486     setOperationAction(ISD::SSUBO, VT, Custom);
1487     setOperationAction(ISD::USUBO, VT, Custom);
1488     setOperationAction(ISD::SMULO, VT, Custom);
1489     setOperationAction(ISD::UMULO, VT, Custom);
1490   }
1491
1492   // There are no 8-bit 3-address imul/mul instructions
1493   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1494   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1495
1496   if (!Subtarget->is64Bit()) {
1497     // These libcalls are not available in 32-bit.
1498     setLibcallName(RTLIB::SHL_I128, nullptr);
1499     setLibcallName(RTLIB::SRL_I128, nullptr);
1500     setLibcallName(RTLIB::SRA_I128, nullptr);
1501   }
1502
1503   // Combine sin / cos into one node or libcall if possible.
1504   if (Subtarget->hasSinCos()) {
1505     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1506     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1507     if (Subtarget->isTargetDarwin()) {
1508       // For MacOSX, we don't want to the normal expansion of a libcall to
1509       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1510       // traffic.
1511       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1512       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1513     }
1514   }
1515
1516   // We have target-specific dag combine patterns for the following nodes:
1517   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1518   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1519   setTargetDAGCombine(ISD::VSELECT);
1520   setTargetDAGCombine(ISD::SELECT);
1521   setTargetDAGCombine(ISD::SHL);
1522   setTargetDAGCombine(ISD::SRA);
1523   setTargetDAGCombine(ISD::SRL);
1524   setTargetDAGCombine(ISD::OR);
1525   setTargetDAGCombine(ISD::AND);
1526   setTargetDAGCombine(ISD::ADD);
1527   setTargetDAGCombine(ISD::FADD);
1528   setTargetDAGCombine(ISD::FSUB);
1529   setTargetDAGCombine(ISD::FMA);
1530   setTargetDAGCombine(ISD::SUB);
1531   setTargetDAGCombine(ISD::LOAD);
1532   setTargetDAGCombine(ISD::STORE);
1533   setTargetDAGCombine(ISD::ZERO_EXTEND);
1534   setTargetDAGCombine(ISD::ANY_EXTEND);
1535   setTargetDAGCombine(ISD::SIGN_EXTEND);
1536   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1537   setTargetDAGCombine(ISD::TRUNCATE);
1538   setTargetDAGCombine(ISD::SINT_TO_FP);
1539   setTargetDAGCombine(ISD::SETCC);
1540   if (Subtarget->is64Bit())
1541     setTargetDAGCombine(ISD::MUL);
1542   setTargetDAGCombine(ISD::XOR);
1543
1544   computeRegisterProperties();
1545
1546   // On Darwin, -Os means optimize for size without hurting performance,
1547   // do not reduce the limit.
1548   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1549   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1550   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1551   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1552   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1553   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1554   setPrefLoopAlignment(4); // 2^4 bytes.
1555
1556   // Predictable cmov don't hurt on atom because it's in-order.
1557   PredictableSelectIsExpensive = !Subtarget->isAtom();
1558
1559   setPrefFunctionAlignment(4); // 2^4 bytes.
1560 }
1561
1562 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1563   if (!VT.isVector())
1564     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1565
1566   if (Subtarget->hasAVX512())
1567     switch(VT.getVectorNumElements()) {
1568     case  8: return MVT::v8i1;
1569     case 16: return MVT::v16i1;
1570   }
1571
1572   return VT.changeVectorElementTypeToInteger();
1573 }
1574
1575 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1576 /// the desired ByVal argument alignment.
1577 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1578   if (MaxAlign == 16)
1579     return;
1580   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1581     if (VTy->getBitWidth() == 128)
1582       MaxAlign = 16;
1583   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1584     unsigned EltAlign = 0;
1585     getMaxByValAlign(ATy->getElementType(), EltAlign);
1586     if (EltAlign > MaxAlign)
1587       MaxAlign = EltAlign;
1588   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1589     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1590       unsigned EltAlign = 0;
1591       getMaxByValAlign(STy->getElementType(i), EltAlign);
1592       if (EltAlign > MaxAlign)
1593         MaxAlign = EltAlign;
1594       if (MaxAlign == 16)
1595         break;
1596     }
1597   }
1598 }
1599
1600 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1601 /// function arguments in the caller parameter area. For X86, aggregates
1602 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1603 /// are at 4-byte boundaries.
1604 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1605   if (Subtarget->is64Bit()) {
1606     // Max of 8 and alignment of type.
1607     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1608     if (TyAlign > 8)
1609       return TyAlign;
1610     return 8;
1611   }
1612
1613   unsigned Align = 4;
1614   if (Subtarget->hasSSE1())
1615     getMaxByValAlign(Ty, Align);
1616   return Align;
1617 }
1618
1619 /// getOptimalMemOpType - Returns the target specific optimal type for load
1620 /// and store operations as a result of memset, memcpy, and memmove
1621 /// lowering. If DstAlign is zero that means it's safe to destination
1622 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1623 /// means there isn't a need to check it against alignment requirement,
1624 /// probably because the source does not need to be loaded. If 'IsMemset' is
1625 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1626 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1627 /// source is constant so it does not need to be loaded.
1628 /// It returns EVT::Other if the type should be determined using generic
1629 /// target-independent logic.
1630 EVT
1631 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1632                                        unsigned DstAlign, unsigned SrcAlign,
1633                                        bool IsMemset, bool ZeroMemset,
1634                                        bool MemcpyStrSrc,
1635                                        MachineFunction &MF) const {
1636   const Function *F = MF.getFunction();
1637   if ((!IsMemset || ZeroMemset) &&
1638       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1639                                        Attribute::NoImplicitFloat)) {
1640     if (Size >= 16 &&
1641         (Subtarget->isUnalignedMemAccessFast() ||
1642          ((DstAlign == 0 || DstAlign >= 16) &&
1643           (SrcAlign == 0 || SrcAlign >= 16)))) {
1644       if (Size >= 32) {
1645         if (Subtarget->hasInt256())
1646           return MVT::v8i32;
1647         if (Subtarget->hasFp256())
1648           return MVT::v8f32;
1649       }
1650       if (Subtarget->hasSSE2())
1651         return MVT::v4i32;
1652       if (Subtarget->hasSSE1())
1653         return MVT::v4f32;
1654     } else if (!MemcpyStrSrc && Size >= 8 &&
1655                !Subtarget->is64Bit() &&
1656                Subtarget->hasSSE2()) {
1657       // Do not use f64 to lower memcpy if source is string constant. It's
1658       // better to use i32 to avoid the loads.
1659       return MVT::f64;
1660     }
1661   }
1662   if (Subtarget->is64Bit() && Size >= 8)
1663     return MVT::i64;
1664   return MVT::i32;
1665 }
1666
1667 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1668   if (VT == MVT::f32)
1669     return X86ScalarSSEf32;
1670   else if (VT == MVT::f64)
1671     return X86ScalarSSEf64;
1672   return true;
1673 }
1674
1675 bool
1676 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1677                                                  unsigned,
1678                                                  bool *Fast) const {
1679   if (Fast)
1680     *Fast = Subtarget->isUnalignedMemAccessFast();
1681   return true;
1682 }
1683
1684 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1685 /// current function.  The returned value is a member of the
1686 /// MachineJumpTableInfo::JTEntryKind enum.
1687 unsigned X86TargetLowering::getJumpTableEncoding() const {
1688   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1689   // symbol.
1690   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1691       Subtarget->isPICStyleGOT())
1692     return MachineJumpTableInfo::EK_Custom32;
1693
1694   // Otherwise, use the normal jump table encoding heuristics.
1695   return TargetLowering::getJumpTableEncoding();
1696 }
1697
1698 const MCExpr *
1699 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1700                                              const MachineBasicBlock *MBB,
1701                                              unsigned uid,MCContext &Ctx) const{
1702   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1703          Subtarget->isPICStyleGOT());
1704   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1705   // entries.
1706   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1707                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1708 }
1709
1710 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1711 /// jumptable.
1712 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1713                                                     SelectionDAG &DAG) const {
1714   if (!Subtarget->is64Bit())
1715     // This doesn't have SDLoc associated with it, but is not really the
1716     // same as a Register.
1717     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1718   return Table;
1719 }
1720
1721 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1722 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1723 /// MCExpr.
1724 const MCExpr *X86TargetLowering::
1725 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1726                              MCContext &Ctx) const {
1727   // X86-64 uses RIP relative addressing based on the jump table label.
1728   if (Subtarget->isPICStyleRIPRel())
1729     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1730
1731   // Otherwise, the reference is relative to the PIC base.
1732   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1733 }
1734
1735 // FIXME: Why this routine is here? Move to RegInfo!
1736 std::pair<const TargetRegisterClass*, uint8_t>
1737 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1738   const TargetRegisterClass *RRC = nullptr;
1739   uint8_t Cost = 1;
1740   switch (VT.SimpleTy) {
1741   default:
1742     return TargetLowering::findRepresentativeClass(VT);
1743   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1744     RRC = Subtarget->is64Bit() ?
1745       (const TargetRegisterClass*)&X86::GR64RegClass :
1746       (const TargetRegisterClass*)&X86::GR32RegClass;
1747     break;
1748   case MVT::x86mmx:
1749     RRC = &X86::VR64RegClass;
1750     break;
1751   case MVT::f32: case MVT::f64:
1752   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1753   case MVT::v4f32: case MVT::v2f64:
1754   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1755   case MVT::v4f64:
1756     RRC = &X86::VR128RegClass;
1757     break;
1758   }
1759   return std::make_pair(RRC, Cost);
1760 }
1761
1762 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1763                                                unsigned &Offset) const {
1764   if (!Subtarget->isTargetLinux())
1765     return false;
1766
1767   if (Subtarget->is64Bit()) {
1768     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1769     Offset = 0x28;
1770     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1771       AddressSpace = 256;
1772     else
1773       AddressSpace = 257;
1774   } else {
1775     // %gs:0x14 on i386
1776     Offset = 0x14;
1777     AddressSpace = 256;
1778   }
1779   return true;
1780 }
1781
1782 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1783                                             unsigned DestAS) const {
1784   assert(SrcAS != DestAS && "Expected different address spaces!");
1785
1786   return SrcAS < 256 && DestAS < 256;
1787 }
1788
1789 //===----------------------------------------------------------------------===//
1790 //               Return Value Calling Convention Implementation
1791 //===----------------------------------------------------------------------===//
1792
1793 #include "X86GenCallingConv.inc"
1794
1795 bool
1796 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1797                                   MachineFunction &MF, bool isVarArg,
1798                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1799                         LLVMContext &Context) const {
1800   SmallVector<CCValAssign, 16> RVLocs;
1801   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1802                  RVLocs, Context);
1803   return CCInfo.CheckReturn(Outs, RetCC_X86);
1804 }
1805
1806 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1807   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1808   return ScratchRegs;
1809 }
1810
1811 SDValue
1812 X86TargetLowering::LowerReturn(SDValue Chain,
1813                                CallingConv::ID CallConv, bool isVarArg,
1814                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1815                                const SmallVectorImpl<SDValue> &OutVals,
1816                                SDLoc dl, SelectionDAG &DAG) const {
1817   MachineFunction &MF = DAG.getMachineFunction();
1818   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1819
1820   SmallVector<CCValAssign, 16> RVLocs;
1821   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1822                  RVLocs, *DAG.getContext());
1823   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1824
1825   SDValue Flag;
1826   SmallVector<SDValue, 6> RetOps;
1827   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1828   // Operand #1 = Bytes To Pop
1829   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1830                    MVT::i16));
1831
1832   // Copy the result values into the output registers.
1833   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1834     CCValAssign &VA = RVLocs[i];
1835     assert(VA.isRegLoc() && "Can only return in registers!");
1836     SDValue ValToCopy = OutVals[i];
1837     EVT ValVT = ValToCopy.getValueType();
1838
1839     // Promote values to the appropriate types
1840     if (VA.getLocInfo() == CCValAssign::SExt)
1841       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1842     else if (VA.getLocInfo() == CCValAssign::ZExt)
1843       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1844     else if (VA.getLocInfo() == CCValAssign::AExt)
1845       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1846     else if (VA.getLocInfo() == CCValAssign::BCvt)
1847       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1848
1849     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1850            "Unexpected FP-extend for return value.");  
1851
1852     // If this is x86-64, and we disabled SSE, we can't return FP values,
1853     // or SSE or MMX vectors.
1854     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1855          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1856           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1857       report_fatal_error("SSE register return with SSE disabled");
1858     }
1859     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1860     // llvm-gcc has never done it right and no one has noticed, so this
1861     // should be OK for now.
1862     if (ValVT == MVT::f64 &&
1863         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1864       report_fatal_error("SSE2 register return with SSE2 disabled");
1865
1866     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1867     // the RET instruction and handled by the FP Stackifier.
1868     if (VA.getLocReg() == X86::ST0 ||
1869         VA.getLocReg() == X86::ST1) {
1870       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1871       // change the value to the FP stack register class.
1872       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1873         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1874       RetOps.push_back(ValToCopy);
1875       // Don't emit a copytoreg.
1876       continue;
1877     }
1878
1879     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1880     // which is returned in RAX / RDX.
1881     if (Subtarget->is64Bit()) {
1882       if (ValVT == MVT::x86mmx) {
1883         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1884           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1885           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1886                                   ValToCopy);
1887           // If we don't have SSE2 available, convert to v4f32 so the generated
1888           // register is legal.
1889           if (!Subtarget->hasSSE2())
1890             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1891         }
1892       }
1893     }
1894
1895     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1896     Flag = Chain.getValue(1);
1897     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1898   }
1899
1900   // The x86-64 ABIs require that for returning structs by value we copy
1901   // the sret argument into %rax/%eax (depending on ABI) for the return.
1902   // Win32 requires us to put the sret argument to %eax as well.
1903   // We saved the argument into a virtual register in the entry block,
1904   // so now we copy the value out and into %rax/%eax.
1905   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1906       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1907     MachineFunction &MF = DAG.getMachineFunction();
1908     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1909     unsigned Reg = FuncInfo->getSRetReturnReg();
1910     assert(Reg &&
1911            "SRetReturnReg should have been set in LowerFormalArguments().");
1912     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1913
1914     unsigned RetValReg
1915         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1916           X86::RAX : X86::EAX;
1917     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1918     Flag = Chain.getValue(1);
1919
1920     // RAX/EAX now acts like a return value.
1921     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1922   }
1923
1924   RetOps[0] = Chain;  // Update chain.
1925
1926   // Add the flag if we have it.
1927   if (Flag.getNode())
1928     RetOps.push_back(Flag);
1929
1930   return DAG.getNode(X86ISD::RET_FLAG, dl,
1931                      MVT::Other, &RetOps[0], RetOps.size());
1932 }
1933
1934 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1935   if (N->getNumValues() != 1)
1936     return false;
1937   if (!N->hasNUsesOfValue(1, 0))
1938     return false;
1939
1940   SDValue TCChain = Chain;
1941   SDNode *Copy = *N->use_begin();
1942   if (Copy->getOpcode() == ISD::CopyToReg) {
1943     // If the copy has a glue operand, we conservatively assume it isn't safe to
1944     // perform a tail call.
1945     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1946       return false;
1947     TCChain = Copy->getOperand(0);
1948   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1949     return false;
1950
1951   bool HasRet = false;
1952   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1953        UI != UE; ++UI) {
1954     if (UI->getOpcode() != X86ISD::RET_FLAG)
1955       return false;
1956     HasRet = true;
1957   }
1958
1959   if (!HasRet)
1960     return false;
1961
1962   Chain = TCChain;
1963   return true;
1964 }
1965
1966 MVT
1967 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1968                                             ISD::NodeType ExtendKind) const {
1969   MVT ReturnMVT;
1970   // TODO: Is this also valid on 32-bit?
1971   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1972     ReturnMVT = MVT::i8;
1973   else
1974     ReturnMVT = MVT::i32;
1975
1976   MVT MinVT = getRegisterType(ReturnMVT);
1977   return VT.bitsLT(MinVT) ? MinVT : VT;
1978 }
1979
1980 /// LowerCallResult - Lower the result values of a call into the
1981 /// appropriate copies out of appropriate physical registers.
1982 ///
1983 SDValue
1984 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1985                                    CallingConv::ID CallConv, bool isVarArg,
1986                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1987                                    SDLoc dl, SelectionDAG &DAG,
1988                                    SmallVectorImpl<SDValue> &InVals) const {
1989
1990   // Assign locations to each value returned by this call.
1991   SmallVector<CCValAssign, 16> RVLocs;
1992   bool Is64Bit = Subtarget->is64Bit();
1993   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1994                  getTargetMachine(), RVLocs, *DAG.getContext());
1995   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1996
1997   // Copy all of the result registers out of their specified physreg.
1998   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1999     CCValAssign &VA = RVLocs[i];
2000     EVT CopyVT = VA.getValVT();
2001
2002     // If this is x86-64, and we disabled SSE, we can't return FP values
2003     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2004         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2005       report_fatal_error("SSE register return with SSE disabled");
2006     }
2007
2008     SDValue Val;
2009
2010     // If this is a call to a function that returns an fp value on the floating
2011     // point stack, we must guarantee the value is popped from the stack, so
2012     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2013     // if the return value is not used. We use the FpPOP_RETVAL instruction
2014     // instead.
2015     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2016       // If we prefer to use the value in xmm registers, copy it out as f80 and
2017       // use a truncate to move it from fp stack reg to xmm reg.
2018       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2019       SDValue Ops[] = { Chain, InFlag };
2020       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2021                                          MVT::Other, MVT::Glue, Ops), 1);
2022       Val = Chain.getValue(0);
2023
2024       // Round the f80 to the right size, which also moves it to the appropriate
2025       // xmm register.
2026       if (CopyVT != VA.getValVT())
2027         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2028                           // This truncation won't change the value.
2029                           DAG.getIntPtrConstant(1));
2030     } else {
2031       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2032                                  CopyVT, InFlag).getValue(1);
2033       Val = Chain.getValue(0);
2034     }
2035     InFlag = Chain.getValue(2);
2036     InVals.push_back(Val);
2037   }
2038
2039   return Chain;
2040 }
2041
2042 //===----------------------------------------------------------------------===//
2043 //                C & StdCall & Fast Calling Convention implementation
2044 //===----------------------------------------------------------------------===//
2045 //  StdCall calling convention seems to be standard for many Windows' API
2046 //  routines and around. It differs from C calling convention just a little:
2047 //  callee should clean up the stack, not caller. Symbols should be also
2048 //  decorated in some fancy way :) It doesn't support any vector arguments.
2049 //  For info on fast calling convention see Fast Calling Convention (tail call)
2050 //  implementation LowerX86_32FastCCCallTo.
2051
2052 /// CallIsStructReturn - Determines whether a call uses struct return
2053 /// semantics.
2054 enum StructReturnType {
2055   NotStructReturn,
2056   RegStructReturn,
2057   StackStructReturn
2058 };
2059 static StructReturnType
2060 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2061   if (Outs.empty())
2062     return NotStructReturn;
2063
2064   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2065   if (!Flags.isSRet())
2066     return NotStructReturn;
2067   if (Flags.isInReg())
2068     return RegStructReturn;
2069   return StackStructReturn;
2070 }
2071
2072 /// ArgsAreStructReturn - Determines whether a function uses struct
2073 /// return semantics.
2074 static StructReturnType
2075 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2076   if (Ins.empty())
2077     return NotStructReturn;
2078
2079   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2080   if (!Flags.isSRet())
2081     return NotStructReturn;
2082   if (Flags.isInReg())
2083     return RegStructReturn;
2084   return StackStructReturn;
2085 }
2086
2087 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2088 /// by "Src" to address "Dst" with size and alignment information specified by
2089 /// the specific parameter attribute. The copy will be passed as a byval
2090 /// function parameter.
2091 static SDValue
2092 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2093                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2094                           SDLoc dl) {
2095   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2096
2097   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2098                        /*isVolatile*/false, /*AlwaysInline=*/true,
2099                        MachinePointerInfo(), MachinePointerInfo());
2100 }
2101
2102 /// IsTailCallConvention - Return true if the calling convention is one that
2103 /// supports tail call optimization.
2104 static bool IsTailCallConvention(CallingConv::ID CC) {
2105   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2106           CC == CallingConv::HiPE);
2107 }
2108
2109 /// \brief Return true if the calling convention is a C calling convention.
2110 static bool IsCCallConvention(CallingConv::ID CC) {
2111   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2112           CC == CallingConv::X86_64_SysV);
2113 }
2114
2115 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2116   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2117     return false;
2118
2119   CallSite CS(CI);
2120   CallingConv::ID CalleeCC = CS.getCallingConv();
2121   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2122     return false;
2123
2124   return true;
2125 }
2126
2127 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2128 /// a tailcall target by changing its ABI.
2129 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2130                                    bool GuaranteedTailCallOpt) {
2131   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2132 }
2133
2134 SDValue
2135 X86TargetLowering::LowerMemArgument(SDValue Chain,
2136                                     CallingConv::ID CallConv,
2137                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2138                                     SDLoc dl, SelectionDAG &DAG,
2139                                     const CCValAssign &VA,
2140                                     MachineFrameInfo *MFI,
2141                                     unsigned i) const {
2142   // Create the nodes corresponding to a load from this parameter slot.
2143   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2144   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2145                               getTargetMachine().Options.GuaranteedTailCallOpt);
2146   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2147   EVT ValVT;
2148
2149   // If value is passed by pointer we have address passed instead of the value
2150   // itself.
2151   if (VA.getLocInfo() == CCValAssign::Indirect)
2152     ValVT = VA.getLocVT();
2153   else
2154     ValVT = VA.getValVT();
2155
2156   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2157   // changed with more analysis.
2158   // In case of tail call optimization mark all arguments mutable. Since they
2159   // could be overwritten by lowering of arguments in case of a tail call.
2160   if (Flags.isByVal()) {
2161     unsigned Bytes = Flags.getByValSize();
2162     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2163     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2164     return DAG.getFrameIndex(FI, getPointerTy());
2165   } else {
2166     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2167                                     VA.getLocMemOffset(), isImmutable);
2168     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2169     return DAG.getLoad(ValVT, dl, Chain, FIN,
2170                        MachinePointerInfo::getFixedStack(FI),
2171                        false, false, false, 0);
2172   }
2173 }
2174
2175 SDValue
2176 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2177                                         CallingConv::ID CallConv,
2178                                         bool isVarArg,
2179                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2180                                         SDLoc dl,
2181                                         SelectionDAG &DAG,
2182                                         SmallVectorImpl<SDValue> &InVals)
2183                                           const {
2184   MachineFunction &MF = DAG.getMachineFunction();
2185   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2186
2187   const Function* Fn = MF.getFunction();
2188   if (Fn->hasExternalLinkage() &&
2189       Subtarget->isTargetCygMing() &&
2190       Fn->getName() == "main")
2191     FuncInfo->setForceFramePointer(true);
2192
2193   MachineFrameInfo *MFI = MF.getFrameInfo();
2194   bool Is64Bit = Subtarget->is64Bit();
2195   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2196
2197   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2198          "Var args not supported with calling convention fastcc, ghc or hipe");
2199
2200   // Assign locations to all of the incoming arguments.
2201   SmallVector<CCValAssign, 16> ArgLocs;
2202   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2203                  ArgLocs, *DAG.getContext());
2204
2205   // Allocate shadow area for Win64
2206   if (IsWin64)
2207     CCInfo.AllocateStack(32, 8);
2208
2209   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2210
2211   unsigned LastVal = ~0U;
2212   SDValue ArgValue;
2213   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2214     CCValAssign &VA = ArgLocs[i];
2215     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2216     // places.
2217     assert(VA.getValNo() != LastVal &&
2218            "Don't support value assigned to multiple locs yet");
2219     (void)LastVal;
2220     LastVal = VA.getValNo();
2221
2222     if (VA.isRegLoc()) {
2223       EVT RegVT = VA.getLocVT();
2224       const TargetRegisterClass *RC;
2225       if (RegVT == MVT::i32)
2226         RC = &X86::GR32RegClass;
2227       else if (Is64Bit && RegVT == MVT::i64)
2228         RC = &X86::GR64RegClass;
2229       else if (RegVT == MVT::f32)
2230         RC = &X86::FR32RegClass;
2231       else if (RegVT == MVT::f64)
2232         RC = &X86::FR64RegClass;
2233       else if (RegVT.is512BitVector())
2234         RC = &X86::VR512RegClass;
2235       else if (RegVT.is256BitVector())
2236         RC = &X86::VR256RegClass;
2237       else if (RegVT.is128BitVector())
2238         RC = &X86::VR128RegClass;
2239       else if (RegVT == MVT::x86mmx)
2240         RC = &X86::VR64RegClass;
2241       else if (RegVT == MVT::i1)
2242         RC = &X86::VK1RegClass;
2243       else if (RegVT == MVT::v8i1)
2244         RC = &X86::VK8RegClass;
2245       else if (RegVT == MVT::v16i1)
2246         RC = &X86::VK16RegClass;
2247       else
2248         llvm_unreachable("Unknown argument type!");
2249
2250       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2251       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2252
2253       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2254       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2255       // right size.
2256       if (VA.getLocInfo() == CCValAssign::SExt)
2257         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2258                                DAG.getValueType(VA.getValVT()));
2259       else if (VA.getLocInfo() == CCValAssign::ZExt)
2260         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2261                                DAG.getValueType(VA.getValVT()));
2262       else if (VA.getLocInfo() == CCValAssign::BCvt)
2263         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2264
2265       if (VA.isExtInLoc()) {
2266         // Handle MMX values passed in XMM regs.
2267         if (RegVT.isVector())
2268           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2269         else
2270           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2271       }
2272     } else {
2273       assert(VA.isMemLoc());
2274       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2275     }
2276
2277     // If value is passed via pointer - do a load.
2278     if (VA.getLocInfo() == CCValAssign::Indirect)
2279       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2280                              MachinePointerInfo(), false, false, false, 0);
2281
2282     InVals.push_back(ArgValue);
2283   }
2284
2285   // The x86-64 ABIs require that for returning structs by value we copy
2286   // the sret argument into %rax/%eax (depending on ABI) for the return.
2287   // Win32 requires us to put the sret argument to %eax as well.
2288   // Save the argument into a virtual register so that we can access it
2289   // from the return points.
2290   if (MF.getFunction()->hasStructRetAttr() &&
2291       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2292     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2293     unsigned Reg = FuncInfo->getSRetReturnReg();
2294     if (!Reg) {
2295       MVT PtrTy = getPointerTy();
2296       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2297       FuncInfo->setSRetReturnReg(Reg);
2298     }
2299     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2300     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2301   }
2302
2303   unsigned StackSize = CCInfo.getNextStackOffset();
2304   // Align stack specially for tail calls.
2305   if (FuncIsMadeTailCallSafe(CallConv,
2306                              MF.getTarget().Options.GuaranteedTailCallOpt))
2307     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2308
2309   // If the function takes variable number of arguments, make a frame index for
2310   // the start of the first vararg value... for expansion of llvm.va_start.
2311   if (isVarArg) {
2312     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2313                     CallConv != CallingConv::X86_ThisCall)) {
2314       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2315     }
2316     if (Is64Bit) {
2317       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2318
2319       // FIXME: We should really autogenerate these arrays
2320       static const MCPhysReg GPR64ArgRegsWin64[] = {
2321         X86::RCX, X86::RDX, X86::R8,  X86::R9
2322       };
2323       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2324         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2325       };
2326       static const MCPhysReg XMMArgRegs64Bit[] = {
2327         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2328         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2329       };
2330       const MCPhysReg *GPR64ArgRegs;
2331       unsigned NumXMMRegs = 0;
2332
2333       if (IsWin64) {
2334         // The XMM registers which might contain var arg parameters are shadowed
2335         // in their paired GPR.  So we only need to save the GPR to their home
2336         // slots.
2337         TotalNumIntRegs = 4;
2338         GPR64ArgRegs = GPR64ArgRegsWin64;
2339       } else {
2340         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2341         GPR64ArgRegs = GPR64ArgRegs64Bit;
2342
2343         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2344                                                 TotalNumXMMRegs);
2345       }
2346       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2347                                                        TotalNumIntRegs);
2348
2349       bool NoImplicitFloatOps = Fn->getAttributes().
2350         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2351       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2352              "SSE register cannot be used when SSE is disabled!");
2353       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2354                NoImplicitFloatOps) &&
2355              "SSE register cannot be used when SSE is disabled!");
2356       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2357           !Subtarget->hasSSE1())
2358         // Kernel mode asks for SSE to be disabled, so don't push them
2359         // on the stack.
2360         TotalNumXMMRegs = 0;
2361
2362       if (IsWin64) {
2363         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2364         // Get to the caller-allocated home save location.  Add 8 to account
2365         // for the return address.
2366         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2367         FuncInfo->setRegSaveFrameIndex(
2368           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2369         // Fixup to set vararg frame on shadow area (4 x i64).
2370         if (NumIntRegs < 4)
2371           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2372       } else {
2373         // For X86-64, if there are vararg parameters that are passed via
2374         // registers, then we must store them to their spots on the stack so
2375         // they may be loaded by deferencing the result of va_next.
2376         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2377         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2378         FuncInfo->setRegSaveFrameIndex(
2379           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2380                                false));
2381       }
2382
2383       // Store the integer parameter registers.
2384       SmallVector<SDValue, 8> MemOps;
2385       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2386                                         getPointerTy());
2387       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2388       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2389         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2390                                   DAG.getIntPtrConstant(Offset));
2391         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2392                                      &X86::GR64RegClass);
2393         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2394         SDValue Store =
2395           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2396                        MachinePointerInfo::getFixedStack(
2397                          FuncInfo->getRegSaveFrameIndex(), Offset),
2398                        false, false, 0);
2399         MemOps.push_back(Store);
2400         Offset += 8;
2401       }
2402
2403       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2404         // Now store the XMM (fp + vector) parameter registers.
2405         SmallVector<SDValue, 11> SaveXMMOps;
2406         SaveXMMOps.push_back(Chain);
2407
2408         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2409         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2410         SaveXMMOps.push_back(ALVal);
2411
2412         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2413                                FuncInfo->getRegSaveFrameIndex()));
2414         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2415                                FuncInfo->getVarArgsFPOffset()));
2416
2417         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2418           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2419                                        &X86::VR128RegClass);
2420           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2421           SaveXMMOps.push_back(Val);
2422         }
2423         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2424                                      MVT::Other,
2425                                      &SaveXMMOps[0], SaveXMMOps.size()));
2426       }
2427
2428       if (!MemOps.empty())
2429         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2430                             &MemOps[0], MemOps.size());
2431     }
2432   }
2433
2434   // Some CCs need callee pop.
2435   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2436                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2437     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2438   } else {
2439     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2440     // If this is an sret function, the return should pop the hidden pointer.
2441     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2442         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2443         argsAreStructReturn(Ins) == StackStructReturn)
2444       FuncInfo->setBytesToPopOnReturn(4);
2445   }
2446
2447   if (!Is64Bit) {
2448     // RegSaveFrameIndex is X86-64 only.
2449     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2450     if (CallConv == CallingConv::X86_FastCall ||
2451         CallConv == CallingConv::X86_ThisCall)
2452       // fastcc functions can't have varargs.
2453       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2454   }
2455
2456   FuncInfo->setArgumentStackSize(StackSize);
2457
2458   return Chain;
2459 }
2460
2461 SDValue
2462 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2463                                     SDValue StackPtr, SDValue Arg,
2464                                     SDLoc dl, SelectionDAG &DAG,
2465                                     const CCValAssign &VA,
2466                                     ISD::ArgFlagsTy Flags) const {
2467   unsigned LocMemOffset = VA.getLocMemOffset();
2468   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2469   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2470   if (Flags.isByVal())
2471     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2472
2473   return DAG.getStore(Chain, dl, Arg, PtrOff,
2474                       MachinePointerInfo::getStack(LocMemOffset),
2475                       false, false, 0);
2476 }
2477
2478 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2479 /// optimization is performed and it is required.
2480 SDValue
2481 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2482                                            SDValue &OutRetAddr, SDValue Chain,
2483                                            bool IsTailCall, bool Is64Bit,
2484                                            int FPDiff, SDLoc dl) const {
2485   // Adjust the Return address stack slot.
2486   EVT VT = getPointerTy();
2487   OutRetAddr = getReturnAddressFrameIndex(DAG);
2488
2489   // Load the "old" Return address.
2490   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2491                            false, false, false, 0);
2492   return SDValue(OutRetAddr.getNode(), 1);
2493 }
2494
2495 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2496 /// optimization is performed and it is required (FPDiff!=0).
2497 static SDValue
2498 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2499                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2500                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2501   // Store the return address to the appropriate stack slot.
2502   if (!FPDiff) return Chain;
2503   // Calculate the new stack slot for the return address.
2504   int NewReturnAddrFI =
2505     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2506                                          false);
2507   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2508   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2509                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2510                        false, false, 0);
2511   return Chain;
2512 }
2513
2514 SDValue
2515 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2516                              SmallVectorImpl<SDValue> &InVals) const {
2517   SelectionDAG &DAG                     = CLI.DAG;
2518   SDLoc &dl                             = CLI.DL;
2519   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2520   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2521   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2522   SDValue Chain                         = CLI.Chain;
2523   SDValue Callee                        = CLI.Callee;
2524   CallingConv::ID CallConv              = CLI.CallConv;
2525   bool &isTailCall                      = CLI.IsTailCall;
2526   bool isVarArg                         = CLI.IsVarArg;
2527
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   bool Is64Bit        = Subtarget->is64Bit();
2530   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2531   StructReturnType SR = callIsStructReturn(Outs);
2532   bool IsSibcall      = false;
2533
2534   if (MF.getTarget().Options.DisableTailCalls)
2535     isTailCall = false;
2536
2537   if (isTailCall) {
2538     // Check if it's really possible to do a tail call.
2539     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2540                     isVarArg, SR != NotStructReturn,
2541                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2542                     Outs, OutVals, Ins, DAG);
2543
2544     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2545       report_fatal_error("failed to perform tail call elimination on a call "
2546                          "site marked musttail");
2547
2548     // Sibcalls are automatically detected tailcalls which do not require
2549     // ABI changes.
2550     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2551       IsSibcall = true;
2552
2553     if (isTailCall)
2554       ++NumTailCalls;
2555   }
2556
2557   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2558          "Var args not supported with calling convention fastcc, ghc or hipe");
2559
2560   // Analyze operands of the call, assigning locations to each operand.
2561   SmallVector<CCValAssign, 16> ArgLocs;
2562   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2563                  ArgLocs, *DAG.getContext());
2564
2565   // Allocate shadow area for Win64
2566   if (IsWin64)
2567     CCInfo.AllocateStack(32, 8);
2568
2569   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2570
2571   // Get a count of how many bytes are to be pushed on the stack.
2572   unsigned NumBytes = CCInfo.getNextStackOffset();
2573   if (IsSibcall)
2574     // This is a sibcall. The memory operands are available in caller's
2575     // own caller's stack.
2576     NumBytes = 0;
2577   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2578            IsTailCallConvention(CallConv))
2579     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2580
2581   int FPDiff = 0;
2582   if (isTailCall && !IsSibcall) {
2583     // Lower arguments at fp - stackoffset + fpdiff.
2584     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2585     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2586
2587     FPDiff = NumBytesCallerPushed - NumBytes;
2588
2589     // Set the delta of movement of the returnaddr stackslot.
2590     // But only set if delta is greater than previous delta.
2591     if (FPDiff < X86Info->getTCReturnAddrDelta())
2592       X86Info->setTCReturnAddrDelta(FPDiff);
2593   }
2594
2595   unsigned NumBytesToPush = NumBytes;
2596   unsigned NumBytesToPop = NumBytes;
2597
2598   // If we have an inalloca argument, all stack space has already been allocated
2599   // for us and be right at the top of the stack.  We don't support multiple
2600   // arguments passed in memory when using inalloca.
2601   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2602     NumBytesToPush = 0;
2603     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2604            "an inalloca argument must be the only memory argument");
2605   }
2606
2607   if (!IsSibcall)
2608     Chain = DAG.getCALLSEQ_START(
2609         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2610
2611   SDValue RetAddrFrIdx;
2612   // Load return address for tail calls.
2613   if (isTailCall && FPDiff)
2614     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2615                                     Is64Bit, FPDiff, dl);
2616
2617   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2618   SmallVector<SDValue, 8> MemOpChains;
2619   SDValue StackPtr;
2620
2621   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2622   // of tail call optimization arguments are handle later.
2623   const X86RegisterInfo *RegInfo =
2624     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2625   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2626     // Skip inalloca arguments, they have already been written.
2627     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2628     if (Flags.isInAlloca())
2629       continue;
2630
2631     CCValAssign &VA = ArgLocs[i];
2632     EVT RegVT = VA.getLocVT();
2633     SDValue Arg = OutVals[i];
2634     bool isByVal = Flags.isByVal();
2635
2636     // Promote the value if needed.
2637     switch (VA.getLocInfo()) {
2638     default: llvm_unreachable("Unknown loc info!");
2639     case CCValAssign::Full: break;
2640     case CCValAssign::SExt:
2641       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2642       break;
2643     case CCValAssign::ZExt:
2644       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2645       break;
2646     case CCValAssign::AExt:
2647       if (RegVT.is128BitVector()) {
2648         // Special case: passing MMX values in XMM registers.
2649         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2650         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2651         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2652       } else
2653         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2654       break;
2655     case CCValAssign::BCvt:
2656       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2657       break;
2658     case CCValAssign::Indirect: {
2659       // Store the argument.
2660       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2661       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2662       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2663                            MachinePointerInfo::getFixedStack(FI),
2664                            false, false, 0);
2665       Arg = SpillSlot;
2666       break;
2667     }
2668     }
2669
2670     if (VA.isRegLoc()) {
2671       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2672       if (isVarArg && IsWin64) {
2673         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2674         // shadow reg if callee is a varargs function.
2675         unsigned ShadowReg = 0;
2676         switch (VA.getLocReg()) {
2677         case X86::XMM0: ShadowReg = X86::RCX; break;
2678         case X86::XMM1: ShadowReg = X86::RDX; break;
2679         case X86::XMM2: ShadowReg = X86::R8; break;
2680         case X86::XMM3: ShadowReg = X86::R9; break;
2681         }
2682         if (ShadowReg)
2683           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2684       }
2685     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2686       assert(VA.isMemLoc());
2687       if (!StackPtr.getNode())
2688         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2689                                       getPointerTy());
2690       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2691                                              dl, DAG, VA, Flags));
2692     }
2693   }
2694
2695   if (!MemOpChains.empty())
2696     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2697                         &MemOpChains[0], MemOpChains.size());
2698
2699   if (Subtarget->isPICStyleGOT()) {
2700     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2701     // GOT pointer.
2702     if (!isTailCall) {
2703       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2704                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2705     } else {
2706       // If we are tail calling and generating PIC/GOT style code load the
2707       // address of the callee into ECX. The value in ecx is used as target of
2708       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2709       // for tail calls on PIC/GOT architectures. Normally we would just put the
2710       // address of GOT into ebx and then call target@PLT. But for tail calls
2711       // ebx would be restored (since ebx is callee saved) before jumping to the
2712       // target@PLT.
2713
2714       // Note: The actual moving to ECX is done further down.
2715       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2716       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2717           !G->getGlobal()->hasProtectedVisibility())
2718         Callee = LowerGlobalAddress(Callee, DAG);
2719       else if (isa<ExternalSymbolSDNode>(Callee))
2720         Callee = LowerExternalSymbol(Callee, DAG);
2721     }
2722   }
2723
2724   if (Is64Bit && isVarArg && !IsWin64) {
2725     // From AMD64 ABI document:
2726     // For calls that may call functions that use varargs or stdargs
2727     // (prototype-less calls or calls to functions containing ellipsis (...) in
2728     // the declaration) %al is used as hidden argument to specify the number
2729     // of SSE registers used. The contents of %al do not need to match exactly
2730     // the number of registers, but must be an ubound on the number of SSE
2731     // registers used and is in the range 0 - 8 inclusive.
2732
2733     // Count the number of XMM registers allocated.
2734     static const MCPhysReg XMMArgRegs[] = {
2735       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2736       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2737     };
2738     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2739     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2740            && "SSE registers cannot be used when SSE is disabled");
2741
2742     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2743                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2744   }
2745
2746   // For tail calls lower the arguments to the 'real' stack slot.
2747   if (isTailCall) {
2748     // Force all the incoming stack arguments to be loaded from the stack
2749     // before any new outgoing arguments are stored to the stack, because the
2750     // outgoing stack slots may alias the incoming argument stack slots, and
2751     // the alias isn't otherwise explicit. This is slightly more conservative
2752     // than necessary, because it means that each store effectively depends
2753     // on every argument instead of just those arguments it would clobber.
2754     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2755
2756     SmallVector<SDValue, 8> MemOpChains2;
2757     SDValue FIN;
2758     int FI = 0;
2759     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2760       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2761         CCValAssign &VA = ArgLocs[i];
2762         if (VA.isRegLoc())
2763           continue;
2764         assert(VA.isMemLoc());
2765         SDValue Arg = OutVals[i];
2766         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2767         // Create frame index.
2768         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2769         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2770         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2771         FIN = DAG.getFrameIndex(FI, getPointerTy());
2772
2773         if (Flags.isByVal()) {
2774           // Copy relative to framepointer.
2775           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2776           if (!StackPtr.getNode())
2777             StackPtr = DAG.getCopyFromReg(Chain, dl,
2778                                           RegInfo->getStackRegister(),
2779                                           getPointerTy());
2780           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2781
2782           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2783                                                            ArgChain,
2784                                                            Flags, DAG, dl));
2785         } else {
2786           // Store relative to framepointer.
2787           MemOpChains2.push_back(
2788             DAG.getStore(ArgChain, dl, Arg, FIN,
2789                          MachinePointerInfo::getFixedStack(FI),
2790                          false, false, 0));
2791         }
2792       }
2793     }
2794
2795     if (!MemOpChains2.empty())
2796       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2797                           &MemOpChains2[0], MemOpChains2.size());
2798
2799     // Store the return address to the appropriate stack slot.
2800     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2801                                      getPointerTy(), RegInfo->getSlotSize(),
2802                                      FPDiff, dl);
2803   }
2804
2805   // Build a sequence of copy-to-reg nodes chained together with token chain
2806   // and flag operands which copy the outgoing args into registers.
2807   SDValue InFlag;
2808   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2809     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2810                              RegsToPass[i].second, InFlag);
2811     InFlag = Chain.getValue(1);
2812   }
2813
2814   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2815     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2816     // In the 64-bit large code model, we have to make all calls
2817     // through a register, since the call instruction's 32-bit
2818     // pc-relative offset may not be large enough to hold the whole
2819     // address.
2820   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2821     // If the callee is a GlobalAddress node (quite common, every direct call
2822     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2823     // it.
2824
2825     // We should use extra load for direct calls to dllimported functions in
2826     // non-JIT mode.
2827     const GlobalValue *GV = G->getGlobal();
2828     if (!GV->hasDLLImportStorageClass()) {
2829       unsigned char OpFlags = 0;
2830       bool ExtraLoad = false;
2831       unsigned WrapperKind = ISD::DELETED_NODE;
2832
2833       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2834       // external symbols most go through the PLT in PIC mode.  If the symbol
2835       // has hidden or protected visibility, or if it is static or local, then
2836       // we don't need to use the PLT - we can directly call it.
2837       if (Subtarget->isTargetELF() &&
2838           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2839           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2840         OpFlags = X86II::MO_PLT;
2841       } else if (Subtarget->isPICStyleStubAny() &&
2842                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2843                  (!Subtarget->getTargetTriple().isMacOSX() ||
2844                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2845         // PC-relative references to external symbols should go through $stub,
2846         // unless we're building with the leopard linker or later, which
2847         // automatically synthesizes these stubs.
2848         OpFlags = X86II::MO_DARWIN_STUB;
2849       } else if (Subtarget->isPICStyleRIPRel() &&
2850                  isa<Function>(GV) &&
2851                  cast<Function>(GV)->getAttributes().
2852                    hasAttribute(AttributeSet::FunctionIndex,
2853                                 Attribute::NonLazyBind)) {
2854         // If the function is marked as non-lazy, generate an indirect call
2855         // which loads from the GOT directly. This avoids runtime overhead
2856         // at the cost of eager binding (and one extra byte of encoding).
2857         OpFlags = X86II::MO_GOTPCREL;
2858         WrapperKind = X86ISD::WrapperRIP;
2859         ExtraLoad = true;
2860       }
2861
2862       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2863                                           G->getOffset(), OpFlags);
2864
2865       // Add a wrapper if needed.
2866       if (WrapperKind != ISD::DELETED_NODE)
2867         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2868       // Add extra indirection if needed.
2869       if (ExtraLoad)
2870         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2871                              MachinePointerInfo::getGOT(),
2872                              false, false, false, 0);
2873     }
2874   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2875     unsigned char OpFlags = 0;
2876
2877     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2878     // external symbols should go through the PLT.
2879     if (Subtarget->isTargetELF() &&
2880         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2881       OpFlags = X86II::MO_PLT;
2882     } else if (Subtarget->isPICStyleStubAny() &&
2883                (!Subtarget->getTargetTriple().isMacOSX() ||
2884                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2885       // PC-relative references to external symbols should go through $stub,
2886       // unless we're building with the leopard linker or later, which
2887       // automatically synthesizes these stubs.
2888       OpFlags = X86II::MO_DARWIN_STUB;
2889     }
2890
2891     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2892                                          OpFlags);
2893   }
2894
2895   // Returns a chain & a flag for retval copy to use.
2896   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2897   SmallVector<SDValue, 8> Ops;
2898
2899   if (!IsSibcall && isTailCall) {
2900     Chain = DAG.getCALLSEQ_END(Chain,
2901                                DAG.getIntPtrConstant(NumBytesToPop, true),
2902                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2903     InFlag = Chain.getValue(1);
2904   }
2905
2906   Ops.push_back(Chain);
2907   Ops.push_back(Callee);
2908
2909   if (isTailCall)
2910     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2911
2912   // Add argument registers to the end of the list so that they are known live
2913   // into the call.
2914   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2915     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2916                                   RegsToPass[i].second.getValueType()));
2917
2918   // Add a register mask operand representing the call-preserved registers.
2919   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2920   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2921   assert(Mask && "Missing call preserved mask for calling convention");
2922   Ops.push_back(DAG.getRegisterMask(Mask));
2923
2924   if (InFlag.getNode())
2925     Ops.push_back(InFlag);
2926
2927   if (isTailCall) {
2928     // We used to do:
2929     //// If this is the first return lowered for this function, add the regs
2930     //// to the liveout set for the function.
2931     // This isn't right, although it's probably harmless on x86; liveouts
2932     // should be computed from returns not tail calls.  Consider a void
2933     // function making a tail call to a function returning int.
2934     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2935   }
2936
2937   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2938   InFlag = Chain.getValue(1);
2939
2940   // Create the CALLSEQ_END node.
2941   unsigned NumBytesForCalleeToPop;
2942   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2943                        getTargetMachine().Options.GuaranteedTailCallOpt))
2944     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2945   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2946            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2947            SR == StackStructReturn)
2948     // If this is a call to a struct-return function, the callee
2949     // pops the hidden struct pointer, so we have to push it back.
2950     // This is common for Darwin/X86, Linux & Mingw32 targets.
2951     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2952     NumBytesForCalleeToPop = 4;
2953   else
2954     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2955
2956   // Returns a flag for retval copy to use.
2957   if (!IsSibcall) {
2958     Chain = DAG.getCALLSEQ_END(Chain,
2959                                DAG.getIntPtrConstant(NumBytesToPop, true),
2960                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2961                                                      true),
2962                                InFlag, dl);
2963     InFlag = Chain.getValue(1);
2964   }
2965
2966   // Handle result values, copying them out of physregs into vregs that we
2967   // return.
2968   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2969                          Ins, dl, DAG, InVals);
2970 }
2971
2972 //===----------------------------------------------------------------------===//
2973 //                Fast Calling Convention (tail call) implementation
2974 //===----------------------------------------------------------------------===//
2975
2976 //  Like std call, callee cleans arguments, convention except that ECX is
2977 //  reserved for storing the tail called function address. Only 2 registers are
2978 //  free for argument passing (inreg). Tail call optimization is performed
2979 //  provided:
2980 //                * tailcallopt is enabled
2981 //                * caller/callee are fastcc
2982 //  On X86_64 architecture with GOT-style position independent code only local
2983 //  (within module) calls are supported at the moment.
2984 //  To keep the stack aligned according to platform abi the function
2985 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2986 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2987 //  If a tail called function callee has more arguments than the caller the
2988 //  caller needs to make sure that there is room to move the RETADDR to. This is
2989 //  achieved by reserving an area the size of the argument delta right after the
2990 //  original REtADDR, but before the saved framepointer or the spilled registers
2991 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2992 //  stack layout:
2993 //    arg1
2994 //    arg2
2995 //    RETADDR
2996 //    [ new RETADDR
2997 //      move area ]
2998 //    (possible EBP)
2999 //    ESI
3000 //    EDI
3001 //    local1 ..
3002
3003 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3004 /// for a 16 byte align requirement.
3005 unsigned
3006 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3007                                                SelectionDAG& DAG) const {
3008   MachineFunction &MF = DAG.getMachineFunction();
3009   const TargetMachine &TM = MF.getTarget();
3010   const X86RegisterInfo *RegInfo =
3011     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3012   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3013   unsigned StackAlignment = TFI.getStackAlignment();
3014   uint64_t AlignMask = StackAlignment - 1;
3015   int64_t Offset = StackSize;
3016   unsigned SlotSize = RegInfo->getSlotSize();
3017   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3018     // Number smaller than 12 so just add the difference.
3019     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3020   } else {
3021     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3022     Offset = ((~AlignMask) & Offset) + StackAlignment +
3023       (StackAlignment-SlotSize);
3024   }
3025   return Offset;
3026 }
3027
3028 /// MatchingStackOffset - Return true if the given stack call argument is
3029 /// already available in the same position (relatively) of the caller's
3030 /// incoming argument stack.
3031 static
3032 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3033                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3034                          const X86InstrInfo *TII) {
3035   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3036   int FI = INT_MAX;
3037   if (Arg.getOpcode() == ISD::CopyFromReg) {
3038     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3039     if (!TargetRegisterInfo::isVirtualRegister(VR))
3040       return false;
3041     MachineInstr *Def = MRI->getVRegDef(VR);
3042     if (!Def)
3043       return false;
3044     if (!Flags.isByVal()) {
3045       if (!TII->isLoadFromStackSlot(Def, FI))
3046         return false;
3047     } else {
3048       unsigned Opcode = Def->getOpcode();
3049       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3050           Def->getOperand(1).isFI()) {
3051         FI = Def->getOperand(1).getIndex();
3052         Bytes = Flags.getByValSize();
3053       } else
3054         return false;
3055     }
3056   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3057     if (Flags.isByVal())
3058       // ByVal argument is passed in as a pointer but it's now being
3059       // dereferenced. e.g.
3060       // define @foo(%struct.X* %A) {
3061       //   tail call @bar(%struct.X* byval %A)
3062       // }
3063       return false;
3064     SDValue Ptr = Ld->getBasePtr();
3065     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3066     if (!FINode)
3067       return false;
3068     FI = FINode->getIndex();
3069   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3070     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3071     FI = FINode->getIndex();
3072     Bytes = Flags.getByValSize();
3073   } else
3074     return false;
3075
3076   assert(FI != INT_MAX);
3077   if (!MFI->isFixedObjectIndex(FI))
3078     return false;
3079   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3080 }
3081
3082 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3083 /// for tail call optimization. Targets which want to do tail call
3084 /// optimization should implement this function.
3085 bool
3086 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3087                                                      CallingConv::ID CalleeCC,
3088                                                      bool isVarArg,
3089                                                      bool isCalleeStructRet,
3090                                                      bool isCallerStructRet,
3091                                                      Type *RetTy,
3092                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3093                                     const SmallVectorImpl<SDValue> &OutVals,
3094                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3095                                                      SelectionDAG &DAG) const {
3096   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3097     return false;
3098
3099   // If -tailcallopt is specified, make fastcc functions tail-callable.
3100   const MachineFunction &MF = DAG.getMachineFunction();
3101   const Function *CallerF = MF.getFunction();
3102
3103   // If the function return type is x86_fp80 and the callee return type is not,
3104   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3105   // perform a tailcall optimization here.
3106   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3107     return false;
3108
3109   CallingConv::ID CallerCC = CallerF->getCallingConv();
3110   bool CCMatch = CallerCC == CalleeCC;
3111   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3112   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3113
3114   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3115     if (IsTailCallConvention(CalleeCC) && CCMatch)
3116       return true;
3117     return false;
3118   }
3119
3120   // Look for obvious safe cases to perform tail call optimization that do not
3121   // require ABI changes. This is what gcc calls sibcall.
3122
3123   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3124   // emit a special epilogue.
3125   const X86RegisterInfo *RegInfo =
3126     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3127   if (RegInfo->needsStackRealignment(MF))
3128     return false;
3129
3130   // Also avoid sibcall optimization if either caller or callee uses struct
3131   // return semantics.
3132   if (isCalleeStructRet || isCallerStructRet)
3133     return false;
3134
3135   // An stdcall/thiscall caller is expected to clean up its arguments; the
3136   // callee isn't going to do that.
3137   // FIXME: this is more restrictive than needed. We could produce a tailcall
3138   // when the stack adjustment matches. For example, with a thiscall that takes
3139   // only one argument.
3140   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3141                    CallerCC == CallingConv::X86_ThisCall))
3142     return false;
3143
3144   // Do not sibcall optimize vararg calls unless all arguments are passed via
3145   // registers.
3146   if (isVarArg && !Outs.empty()) {
3147
3148     // Optimizing for varargs on Win64 is unlikely to be safe without
3149     // additional testing.
3150     if (IsCalleeWin64 || IsCallerWin64)
3151       return false;
3152
3153     SmallVector<CCValAssign, 16> ArgLocs;
3154     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3155                    getTargetMachine(), ArgLocs, *DAG.getContext());
3156
3157     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3159       if (!ArgLocs[i].isRegLoc())
3160         return false;
3161   }
3162
3163   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3164   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3165   // this into a sibcall.
3166   bool Unused = false;
3167   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3168     if (!Ins[i].Used) {
3169       Unused = true;
3170       break;
3171     }
3172   }
3173   if (Unused) {
3174     SmallVector<CCValAssign, 16> RVLocs;
3175     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3176                    getTargetMachine(), RVLocs, *DAG.getContext());
3177     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3178     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3179       CCValAssign &VA = RVLocs[i];
3180       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3181         return false;
3182     }
3183   }
3184
3185   // If the calling conventions do not match, then we'd better make sure the
3186   // results are returned in the same way as what the caller expects.
3187   if (!CCMatch) {
3188     SmallVector<CCValAssign, 16> RVLocs1;
3189     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3190                     getTargetMachine(), RVLocs1, *DAG.getContext());
3191     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3192
3193     SmallVector<CCValAssign, 16> RVLocs2;
3194     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3195                     getTargetMachine(), RVLocs2, *DAG.getContext());
3196     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3197
3198     if (RVLocs1.size() != RVLocs2.size())
3199       return false;
3200     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3201       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3202         return false;
3203       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3204         return false;
3205       if (RVLocs1[i].isRegLoc()) {
3206         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3207           return false;
3208       } else {
3209         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3210           return false;
3211       }
3212     }
3213   }
3214
3215   // If the callee takes no arguments then go on to check the results of the
3216   // call.
3217   if (!Outs.empty()) {
3218     // Check if stack adjustment is needed. For now, do not do this if any
3219     // argument is passed on the stack.
3220     SmallVector<CCValAssign, 16> ArgLocs;
3221     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3222                    getTargetMachine(), ArgLocs, *DAG.getContext());
3223
3224     // Allocate shadow area for Win64
3225     if (IsCalleeWin64)
3226       CCInfo.AllocateStack(32, 8);
3227
3228     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3229     if (CCInfo.getNextStackOffset()) {
3230       MachineFunction &MF = DAG.getMachineFunction();
3231       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3232         return false;
3233
3234       // Check if the arguments are already laid out in the right way as
3235       // the caller's fixed stack objects.
3236       MachineFrameInfo *MFI = MF.getFrameInfo();
3237       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3238       const X86InstrInfo *TII =
3239         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3240       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3241         CCValAssign &VA = ArgLocs[i];
3242         SDValue Arg = OutVals[i];
3243         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3244         if (VA.getLocInfo() == CCValAssign::Indirect)
3245           return false;
3246         if (!VA.isRegLoc()) {
3247           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3248                                    MFI, MRI, TII))
3249             return false;
3250         }
3251       }
3252     }
3253
3254     // If the tailcall address may be in a register, then make sure it's
3255     // possible to register allocate for it. In 32-bit, the call address can
3256     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3257     // callee-saved registers are restored. These happen to be the same
3258     // registers used to pass 'inreg' arguments so watch out for those.
3259     if (!Subtarget->is64Bit() &&
3260         ((!isa<GlobalAddressSDNode>(Callee) &&
3261           !isa<ExternalSymbolSDNode>(Callee)) ||
3262          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3263       unsigned NumInRegs = 0;
3264       // In PIC we need an extra register to formulate the address computation
3265       // for the callee.
3266       unsigned MaxInRegs =
3267           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3268
3269       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3270         CCValAssign &VA = ArgLocs[i];
3271         if (!VA.isRegLoc())
3272           continue;
3273         unsigned Reg = VA.getLocReg();
3274         switch (Reg) {
3275         default: break;
3276         case X86::EAX: case X86::EDX: case X86::ECX:
3277           if (++NumInRegs == MaxInRegs)
3278             return false;
3279           break;
3280         }
3281       }
3282     }
3283   }
3284
3285   return true;
3286 }
3287
3288 FastISel *
3289 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3290                                   const TargetLibraryInfo *libInfo) const {
3291   return X86::createFastISel(funcInfo, libInfo);
3292 }
3293
3294 //===----------------------------------------------------------------------===//
3295 //                           Other Lowering Hooks
3296 //===----------------------------------------------------------------------===//
3297
3298 static bool MayFoldLoad(SDValue Op) {
3299   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3300 }
3301
3302 static bool MayFoldIntoStore(SDValue Op) {
3303   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3304 }
3305
3306 static bool isTargetShuffle(unsigned Opcode) {
3307   switch(Opcode) {
3308   default: return false;
3309   case X86ISD::PSHUFD:
3310   case X86ISD::PSHUFHW:
3311   case X86ISD::PSHUFLW:
3312   case X86ISD::SHUFP:
3313   case X86ISD::PALIGNR:
3314   case X86ISD::MOVLHPS:
3315   case X86ISD::MOVLHPD:
3316   case X86ISD::MOVHLPS:
3317   case X86ISD::MOVLPS:
3318   case X86ISD::MOVLPD:
3319   case X86ISD::MOVSHDUP:
3320   case X86ISD::MOVSLDUP:
3321   case X86ISD::MOVDDUP:
3322   case X86ISD::MOVSS:
3323   case X86ISD::MOVSD:
3324   case X86ISD::UNPCKL:
3325   case X86ISD::UNPCKH:
3326   case X86ISD::VPERMILP:
3327   case X86ISD::VPERM2X128:
3328   case X86ISD::VPERMI:
3329     return true;
3330   }
3331 }
3332
3333 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3334                                     SDValue V1, SelectionDAG &DAG) {
3335   switch(Opc) {
3336   default: llvm_unreachable("Unknown x86 shuffle node");
3337   case X86ISD::MOVSHDUP:
3338   case X86ISD::MOVSLDUP:
3339   case X86ISD::MOVDDUP:
3340     return DAG.getNode(Opc, dl, VT, V1);
3341   }
3342 }
3343
3344 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3345                                     SDValue V1, unsigned TargetMask,
3346                                     SelectionDAG &DAG) {
3347   switch(Opc) {
3348   default: llvm_unreachable("Unknown x86 shuffle node");
3349   case X86ISD::PSHUFD:
3350   case X86ISD::PSHUFHW:
3351   case X86ISD::PSHUFLW:
3352   case X86ISD::VPERMILP:
3353   case X86ISD::VPERMI:
3354     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3355   }
3356 }
3357
3358 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3359                                     SDValue V1, SDValue V2, unsigned TargetMask,
3360                                     SelectionDAG &DAG) {
3361   switch(Opc) {
3362   default: llvm_unreachable("Unknown x86 shuffle node");
3363   case X86ISD::PALIGNR:
3364   case X86ISD::SHUFP:
3365   case X86ISD::VPERM2X128:
3366     return DAG.getNode(Opc, dl, VT, V1, V2,
3367                        DAG.getConstant(TargetMask, MVT::i8));
3368   }
3369 }
3370
3371 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3372                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3373   switch(Opc) {
3374   default: llvm_unreachable("Unknown x86 shuffle node");
3375   case X86ISD::MOVLHPS:
3376   case X86ISD::MOVLHPD:
3377   case X86ISD::MOVHLPS:
3378   case X86ISD::MOVLPS:
3379   case X86ISD::MOVLPD:
3380   case X86ISD::MOVSS:
3381   case X86ISD::MOVSD:
3382   case X86ISD::UNPCKL:
3383   case X86ISD::UNPCKH:
3384     return DAG.getNode(Opc, dl, VT, V1, V2);
3385   }
3386 }
3387
3388 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3389   MachineFunction &MF = DAG.getMachineFunction();
3390   const X86RegisterInfo *RegInfo =
3391     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3392   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3393   int ReturnAddrIndex = FuncInfo->getRAIndex();
3394
3395   if (ReturnAddrIndex == 0) {
3396     // Set up a frame object for the return address.
3397     unsigned SlotSize = RegInfo->getSlotSize();
3398     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3399                                                            -(int64_t)SlotSize,
3400                                                            false);
3401     FuncInfo->setRAIndex(ReturnAddrIndex);
3402   }
3403
3404   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3405 }
3406
3407 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3408                                        bool hasSymbolicDisplacement) {
3409   // Offset should fit into 32 bit immediate field.
3410   if (!isInt<32>(Offset))
3411     return false;
3412
3413   // If we don't have a symbolic displacement - we don't have any extra
3414   // restrictions.
3415   if (!hasSymbolicDisplacement)
3416     return true;
3417
3418   // FIXME: Some tweaks might be needed for medium code model.
3419   if (M != CodeModel::Small && M != CodeModel::Kernel)
3420     return false;
3421
3422   // For small code model we assume that latest object is 16MB before end of 31
3423   // bits boundary. We may also accept pretty large negative constants knowing
3424   // that all objects are in the positive half of address space.
3425   if (M == CodeModel::Small && Offset < 16*1024*1024)
3426     return true;
3427
3428   // For kernel code model we know that all object resist in the negative half
3429   // of 32bits address space. We may not accept negative offsets, since they may
3430   // be just off and we may accept pretty large positive ones.
3431   if (M == CodeModel::Kernel && Offset > 0)
3432     return true;
3433
3434   return false;
3435 }
3436
3437 /// isCalleePop - Determines whether the callee is required to pop its
3438 /// own arguments. Callee pop is necessary to support tail calls.
3439 bool X86::isCalleePop(CallingConv::ID CallingConv,
3440                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3441   if (IsVarArg)
3442     return false;
3443
3444   switch (CallingConv) {
3445   default:
3446     return false;
3447   case CallingConv::X86_StdCall:
3448     return !is64Bit;
3449   case CallingConv::X86_FastCall:
3450     return !is64Bit;
3451   case CallingConv::X86_ThisCall:
3452     return !is64Bit;
3453   case CallingConv::Fast:
3454     return TailCallOpt;
3455   case CallingConv::GHC:
3456     return TailCallOpt;
3457   case CallingConv::HiPE:
3458     return TailCallOpt;
3459   }
3460 }
3461
3462 /// \brief Return true if the condition is an unsigned comparison operation.
3463 static bool isX86CCUnsigned(unsigned X86CC) {
3464   switch (X86CC) {
3465   default: llvm_unreachable("Invalid integer condition!");
3466   case X86::COND_E:     return true;
3467   case X86::COND_G:     return false;
3468   case X86::COND_GE:    return false;
3469   case X86::COND_L:     return false;
3470   case X86::COND_LE:    return false;
3471   case X86::COND_NE:    return true;
3472   case X86::COND_B:     return true;
3473   case X86::COND_A:     return true;
3474   case X86::COND_BE:    return true;
3475   case X86::COND_AE:    return true;
3476   }
3477   llvm_unreachable("covered switch fell through?!");
3478 }
3479
3480 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3481 /// specific condition code, returning the condition code and the LHS/RHS of the
3482 /// comparison to make.
3483 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3484                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3485   if (!isFP) {
3486     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3487       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3488         // X > -1   -> X == 0, jump !sign.
3489         RHS = DAG.getConstant(0, RHS.getValueType());
3490         return X86::COND_NS;
3491       }
3492       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3493         // X < 0   -> X == 0, jump on sign.
3494         return X86::COND_S;
3495       }
3496       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3497         // X < 1   -> X <= 0
3498         RHS = DAG.getConstant(0, RHS.getValueType());
3499         return X86::COND_LE;
3500       }
3501     }
3502
3503     switch (SetCCOpcode) {
3504     default: llvm_unreachable("Invalid integer condition!");
3505     case ISD::SETEQ:  return X86::COND_E;
3506     case ISD::SETGT:  return X86::COND_G;
3507     case ISD::SETGE:  return X86::COND_GE;
3508     case ISD::SETLT:  return X86::COND_L;
3509     case ISD::SETLE:  return X86::COND_LE;
3510     case ISD::SETNE:  return X86::COND_NE;
3511     case ISD::SETULT: return X86::COND_B;
3512     case ISD::SETUGT: return X86::COND_A;
3513     case ISD::SETULE: return X86::COND_BE;
3514     case ISD::SETUGE: return X86::COND_AE;
3515     }
3516   }
3517
3518   // First determine if it is required or is profitable to flip the operands.
3519
3520   // If LHS is a foldable load, but RHS is not, flip the condition.
3521   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3522       !ISD::isNON_EXTLoad(RHS.getNode())) {
3523     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3524     std::swap(LHS, RHS);
3525   }
3526
3527   switch (SetCCOpcode) {
3528   default: break;
3529   case ISD::SETOLT:
3530   case ISD::SETOLE:
3531   case ISD::SETUGT:
3532   case ISD::SETUGE:
3533     std::swap(LHS, RHS);
3534     break;
3535   }
3536
3537   // On a floating point condition, the flags are set as follows:
3538   // ZF  PF  CF   op
3539   //  0 | 0 | 0 | X > Y
3540   //  0 | 0 | 1 | X < Y
3541   //  1 | 0 | 0 | X == Y
3542   //  1 | 1 | 1 | unordered
3543   switch (SetCCOpcode) {
3544   default: llvm_unreachable("Condcode should be pre-legalized away");
3545   case ISD::SETUEQ:
3546   case ISD::SETEQ:   return X86::COND_E;
3547   case ISD::SETOLT:              // flipped
3548   case ISD::SETOGT:
3549   case ISD::SETGT:   return X86::COND_A;
3550   case ISD::SETOLE:              // flipped
3551   case ISD::SETOGE:
3552   case ISD::SETGE:   return X86::COND_AE;
3553   case ISD::SETUGT:              // flipped
3554   case ISD::SETULT:
3555   case ISD::SETLT:   return X86::COND_B;
3556   case ISD::SETUGE:              // flipped
3557   case ISD::SETULE:
3558   case ISD::SETLE:   return X86::COND_BE;
3559   case ISD::SETONE:
3560   case ISD::SETNE:   return X86::COND_NE;
3561   case ISD::SETUO:   return X86::COND_P;
3562   case ISD::SETO:    return X86::COND_NP;
3563   case ISD::SETOEQ:
3564   case ISD::SETUNE:  return X86::COND_INVALID;
3565   }
3566 }
3567
3568 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3569 /// code. Current x86 isa includes the following FP cmov instructions:
3570 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3571 static bool hasFPCMov(unsigned X86CC) {
3572   switch (X86CC) {
3573   default:
3574     return false;
3575   case X86::COND_B:
3576   case X86::COND_BE:
3577   case X86::COND_E:
3578   case X86::COND_P:
3579   case X86::COND_A:
3580   case X86::COND_AE:
3581   case X86::COND_NE:
3582   case X86::COND_NP:
3583     return true;
3584   }
3585 }
3586
3587 /// isFPImmLegal - Returns true if the target can instruction select the
3588 /// specified FP immediate natively. If false, the legalizer will
3589 /// materialize the FP immediate as a load from a constant pool.
3590 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3591   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3592     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3593       return true;
3594   }
3595   return false;
3596 }
3597
3598 /// \brief Returns true if it is beneficial to convert a load of a constant
3599 /// to just the constant itself.
3600 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3601                                                           Type *Ty) const {
3602   assert(Ty->isIntegerTy());
3603
3604   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3605   if (BitSize == 0 || BitSize > 64)
3606     return false;
3607   return true;
3608 }
3609
3610 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3611 /// the specified range (L, H].
3612 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3613   return (Val < 0) || (Val >= Low && Val < Hi);
3614 }
3615
3616 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3617 /// specified value.
3618 static bool isUndefOrEqual(int Val, int CmpVal) {
3619   return (Val < 0 || Val == CmpVal);
3620 }
3621
3622 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3623 /// from position Pos and ending in Pos+Size, falls within the specified
3624 /// sequential range (L, L+Pos]. or is undef.
3625 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3626                                        unsigned Pos, unsigned Size, int Low) {
3627   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3628     if (!isUndefOrEqual(Mask[i], Low))
3629       return false;
3630   return true;
3631 }
3632
3633 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3634 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3635 /// the second operand.
3636 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3637   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3638     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3639   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3640     return (Mask[0] < 2 && Mask[1] < 2);
3641   return false;
3642 }
3643
3644 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3645 /// is suitable for input to PSHUFHW.
3646 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3647   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3648     return false;
3649
3650   // Lower quadword copied in order or undef.
3651   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3652     return false;
3653
3654   // Upper quadword shuffled.
3655   for (unsigned i = 4; i != 8; ++i)
3656     if (!isUndefOrInRange(Mask[i], 4, 8))
3657       return false;
3658
3659   if (VT == MVT::v16i16) {
3660     // Lower quadword copied in order or undef.
3661     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3662       return false;
3663
3664     // Upper quadword shuffled.
3665     for (unsigned i = 12; i != 16; ++i)
3666       if (!isUndefOrInRange(Mask[i], 12, 16))
3667         return false;
3668   }
3669
3670   return true;
3671 }
3672
3673 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3674 /// is suitable for input to PSHUFLW.
3675 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3676   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3677     return false;
3678
3679   // Upper quadword copied in order.
3680   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3681     return false;
3682
3683   // Lower quadword shuffled.
3684   for (unsigned i = 0; i != 4; ++i)
3685     if (!isUndefOrInRange(Mask[i], 0, 4))
3686       return false;
3687
3688   if (VT == MVT::v16i16) {
3689     // Upper quadword copied in order.
3690     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3691       return false;
3692
3693     // Lower quadword shuffled.
3694     for (unsigned i = 8; i != 12; ++i)
3695       if (!isUndefOrInRange(Mask[i], 8, 12))
3696         return false;
3697   }
3698
3699   return true;
3700 }
3701
3702 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3703 /// is suitable for input to PALIGNR.
3704 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3705                           const X86Subtarget *Subtarget) {
3706   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3707       (VT.is256BitVector() && !Subtarget->hasInt256()))
3708     return false;
3709
3710   unsigned NumElts = VT.getVectorNumElements();
3711   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3712   unsigned NumLaneElts = NumElts/NumLanes;
3713
3714   // Do not handle 64-bit element shuffles with palignr.
3715   if (NumLaneElts == 2)
3716     return false;
3717
3718   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3719     unsigned i;
3720     for (i = 0; i != NumLaneElts; ++i) {
3721       if (Mask[i+l] >= 0)
3722         break;
3723     }
3724
3725     // Lane is all undef, go to next lane
3726     if (i == NumLaneElts)
3727       continue;
3728
3729     int Start = Mask[i+l];
3730
3731     // Make sure its in this lane in one of the sources
3732     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3733         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3734       return false;
3735
3736     // If not lane 0, then we must match lane 0
3737     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3738       return false;
3739
3740     // Correct second source to be contiguous with first source
3741     if (Start >= (int)NumElts)
3742       Start -= NumElts - NumLaneElts;
3743
3744     // Make sure we're shifting in the right direction.
3745     if (Start <= (int)(i+l))
3746       return false;
3747
3748     Start -= i;
3749
3750     // Check the rest of the elements to see if they are consecutive.
3751     for (++i; i != NumLaneElts; ++i) {
3752       int Idx = Mask[i+l];
3753
3754       // Make sure its in this lane
3755       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3756           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3757         return false;
3758
3759       // If not lane 0, then we must match lane 0
3760       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3761         return false;
3762
3763       if (Idx >= (int)NumElts)
3764         Idx -= NumElts - NumLaneElts;
3765
3766       if (!isUndefOrEqual(Idx, Start+i))
3767         return false;
3768
3769     }
3770   }
3771
3772   return true;
3773 }
3774
3775 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3776 /// the two vector operands have swapped position.
3777 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3778                                      unsigned NumElems) {
3779   for (unsigned i = 0; i != NumElems; ++i) {
3780     int idx = Mask[i];
3781     if (idx < 0)
3782       continue;
3783     else if (idx < (int)NumElems)
3784       Mask[i] = idx + NumElems;
3785     else
3786       Mask[i] = idx - NumElems;
3787   }
3788 }
3789
3790 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3791 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3792 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3793 /// reverse of what x86 shuffles want.
3794 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3795
3796   unsigned NumElems = VT.getVectorNumElements();
3797   unsigned NumLanes = VT.getSizeInBits()/128;
3798   unsigned NumLaneElems = NumElems/NumLanes;
3799
3800   if (NumLaneElems != 2 && NumLaneElems != 4)
3801     return false;
3802
3803   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3804   bool symetricMaskRequired =
3805     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3806
3807   // VSHUFPSY divides the resulting vector into 4 chunks.
3808   // The sources are also splitted into 4 chunks, and each destination
3809   // chunk must come from a different source chunk.
3810   //
3811   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3812   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3813   //
3814   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3815   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3816   //
3817   // VSHUFPDY divides the resulting vector into 4 chunks.
3818   // The sources are also splitted into 4 chunks, and each destination
3819   // chunk must come from a different source chunk.
3820   //
3821   //  SRC1 =>      X3       X2       X1       X0
3822   //  SRC2 =>      Y3       Y2       Y1       Y0
3823   //
3824   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3825   //
3826   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3827   unsigned HalfLaneElems = NumLaneElems/2;
3828   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3829     for (unsigned i = 0; i != NumLaneElems; ++i) {
3830       int Idx = Mask[i+l];
3831       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3832       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3833         return false;
3834       // For VSHUFPSY, the mask of the second half must be the same as the
3835       // first but with the appropriate offsets. This works in the same way as
3836       // VPERMILPS works with masks.
3837       if (!symetricMaskRequired || Idx < 0)
3838         continue;
3839       if (MaskVal[i] < 0) {
3840         MaskVal[i] = Idx - l;
3841         continue;
3842       }
3843       if ((signed)(Idx - l) != MaskVal[i])
3844         return false;
3845     }
3846   }
3847
3848   return true;
3849 }
3850
3851 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3852 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3853 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3854   if (!VT.is128BitVector())
3855     return false;
3856
3857   unsigned NumElems = VT.getVectorNumElements();
3858
3859   if (NumElems != 4)
3860     return false;
3861
3862   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3863   return isUndefOrEqual(Mask[0], 6) &&
3864          isUndefOrEqual(Mask[1], 7) &&
3865          isUndefOrEqual(Mask[2], 2) &&
3866          isUndefOrEqual(Mask[3], 3);
3867 }
3868
3869 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3870 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3871 /// <2, 3, 2, 3>
3872 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3873   if (!VT.is128BitVector())
3874     return false;
3875
3876   unsigned NumElems = VT.getVectorNumElements();
3877
3878   if (NumElems != 4)
3879     return false;
3880
3881   return isUndefOrEqual(Mask[0], 2) &&
3882          isUndefOrEqual(Mask[1], 3) &&
3883          isUndefOrEqual(Mask[2], 2) &&
3884          isUndefOrEqual(Mask[3], 3);
3885 }
3886
3887 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3888 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3889 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3890   if (!VT.is128BitVector())
3891     return false;
3892
3893   unsigned NumElems = VT.getVectorNumElements();
3894
3895   if (NumElems != 2 && NumElems != 4)
3896     return false;
3897
3898   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3899     if (!isUndefOrEqual(Mask[i], i + NumElems))
3900       return false;
3901
3902   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3903     if (!isUndefOrEqual(Mask[i], i))
3904       return false;
3905
3906   return true;
3907 }
3908
3909 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3910 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3911 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3912   if (!VT.is128BitVector())
3913     return false;
3914
3915   unsigned NumElems = VT.getVectorNumElements();
3916
3917   if (NumElems != 2 && NumElems != 4)
3918     return false;
3919
3920   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3921     if (!isUndefOrEqual(Mask[i], i))
3922       return false;
3923
3924   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3925     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3926       return false;
3927
3928   return true;
3929 }
3930
3931 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3932 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3933 /// i. e: If all but one element come from the same vector.
3934 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3935   // TODO: Deal with AVX's VINSERTPS
3936   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3937     return false;
3938
3939   unsigned CorrectPosV1 = 0;
3940   unsigned CorrectPosV2 = 0;
3941   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3942     if (Mask[i] == i)
3943       ++CorrectPosV1;
3944     else if (Mask[i] == i + 4)
3945       ++CorrectPosV2;
3946
3947   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3948     // We have 3 elements from one vector, and one from another.
3949     return true;
3950
3951   return false;
3952 }
3953
3954 //
3955 // Some special combinations that can be optimized.
3956 //
3957 static
3958 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3959                                SelectionDAG &DAG) {
3960   MVT VT = SVOp->getSimpleValueType(0);
3961   SDLoc dl(SVOp);
3962
3963   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3964     return SDValue();
3965
3966   ArrayRef<int> Mask = SVOp->getMask();
3967
3968   // These are the special masks that may be optimized.
3969   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3970   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3971   bool MatchEvenMask = true;
3972   bool MatchOddMask  = true;
3973   for (int i=0; i<8; ++i) {
3974     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3975       MatchEvenMask = false;
3976     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3977       MatchOddMask = false;
3978   }
3979
3980   if (!MatchEvenMask && !MatchOddMask)
3981     return SDValue();
3982
3983   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3984
3985   SDValue Op0 = SVOp->getOperand(0);
3986   SDValue Op1 = SVOp->getOperand(1);
3987
3988   if (MatchEvenMask) {
3989     // Shift the second operand right to 32 bits.
3990     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3991     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3992   } else {
3993     // Shift the first operand left to 32 bits.
3994     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3995     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3996   }
3997   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3998   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3999 }
4000
4001 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4002 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4003 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4004                          bool HasInt256, bool V2IsSplat = false) {
4005
4006   assert(VT.getSizeInBits() >= 128 &&
4007          "Unsupported vector type for unpckl");
4008
4009   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4010   unsigned NumLanes;
4011   unsigned NumOf256BitLanes;
4012   unsigned NumElts = VT.getVectorNumElements();
4013   if (VT.is256BitVector()) {
4014     if (NumElts != 4 && NumElts != 8 &&
4015         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4016     return false;
4017     NumLanes = 2;
4018     NumOf256BitLanes = 1;
4019   } else if (VT.is512BitVector()) {
4020     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4021            "Unsupported vector type for unpckh");
4022     NumLanes = 2;
4023     NumOf256BitLanes = 2;
4024   } else {
4025     NumLanes = 1;
4026     NumOf256BitLanes = 1;
4027   }
4028
4029   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4030   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4031
4032   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4033     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4034       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4035         int BitI  = Mask[l256*NumEltsInStride+l+i];
4036         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4037         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4038           return false;
4039         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4040           return false;
4041         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4042           return false;
4043       }
4044     }
4045   }
4046   return true;
4047 }
4048
4049 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4050 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4051 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4052                          bool HasInt256, bool V2IsSplat = false) {
4053   assert(VT.getSizeInBits() >= 128 &&
4054          "Unsupported vector type for unpckh");
4055
4056   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4057   unsigned NumLanes;
4058   unsigned NumOf256BitLanes;
4059   unsigned NumElts = VT.getVectorNumElements();
4060   if (VT.is256BitVector()) {
4061     if (NumElts != 4 && NumElts != 8 &&
4062         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4063     return false;
4064     NumLanes = 2;
4065     NumOf256BitLanes = 1;
4066   } else if (VT.is512BitVector()) {
4067     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4068            "Unsupported vector type for unpckh");
4069     NumLanes = 2;
4070     NumOf256BitLanes = 2;
4071   } else {
4072     NumLanes = 1;
4073     NumOf256BitLanes = 1;
4074   }
4075
4076   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4077   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4078
4079   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4080     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4081       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4082         int BitI  = Mask[l256*NumEltsInStride+l+i];
4083         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4084         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4085           return false;
4086         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4087           return false;
4088         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4089           return false;
4090       }
4091     }
4092   }
4093   return true;
4094 }
4095
4096 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4097 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4098 /// <0, 0, 1, 1>
4099 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4100   unsigned NumElts = VT.getVectorNumElements();
4101   bool Is256BitVec = VT.is256BitVector();
4102
4103   if (VT.is512BitVector())
4104     return false;
4105   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4106          "Unsupported vector type for unpckh");
4107
4108   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4109       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4110     return false;
4111
4112   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4113   // FIXME: Need a better way to get rid of this, there's no latency difference
4114   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4115   // the former later. We should also remove the "_undef" special mask.
4116   if (NumElts == 4 && Is256BitVec)
4117     return false;
4118
4119   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4120   // independently on 128-bit lanes.
4121   unsigned NumLanes = VT.getSizeInBits()/128;
4122   unsigned NumLaneElts = NumElts/NumLanes;
4123
4124   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4125     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4126       int BitI  = Mask[l+i];
4127       int BitI1 = Mask[l+i+1];
4128
4129       if (!isUndefOrEqual(BitI, j))
4130         return false;
4131       if (!isUndefOrEqual(BitI1, j))
4132         return false;
4133     }
4134   }
4135
4136   return true;
4137 }
4138
4139 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4140 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4141 /// <2, 2, 3, 3>
4142 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4143   unsigned NumElts = VT.getVectorNumElements();
4144
4145   if (VT.is512BitVector())
4146     return false;
4147
4148   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4149          "Unsupported vector type for unpckh");
4150
4151   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4152       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4153     return false;
4154
4155   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4156   // independently on 128-bit lanes.
4157   unsigned NumLanes = VT.getSizeInBits()/128;
4158   unsigned NumLaneElts = NumElts/NumLanes;
4159
4160   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4161     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4162       int BitI  = Mask[l+i];
4163       int BitI1 = Mask[l+i+1];
4164       if (!isUndefOrEqual(BitI, j))
4165         return false;
4166       if (!isUndefOrEqual(BitI1, j))
4167         return false;
4168     }
4169   }
4170   return true;
4171 }
4172
4173 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4174 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4175 /// MOVSD, and MOVD, i.e. setting the lowest element.
4176 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4177   if (VT.getVectorElementType().getSizeInBits() < 32)
4178     return false;
4179   if (!VT.is128BitVector())
4180     return false;
4181
4182   unsigned NumElts = VT.getVectorNumElements();
4183
4184   if (!isUndefOrEqual(Mask[0], NumElts))
4185     return false;
4186
4187   for (unsigned i = 1; i != NumElts; ++i)
4188     if (!isUndefOrEqual(Mask[i], i))
4189       return false;
4190
4191   return true;
4192 }
4193
4194 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4195 /// as permutations between 128-bit chunks or halves. As an example: this
4196 /// shuffle bellow:
4197 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4198 /// The first half comes from the second half of V1 and the second half from the
4199 /// the second half of V2.
4200 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4201   if (!HasFp256 || !VT.is256BitVector())
4202     return false;
4203
4204   // The shuffle result is divided into half A and half B. In total the two
4205   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4206   // B must come from C, D, E or F.
4207   unsigned HalfSize = VT.getVectorNumElements()/2;
4208   bool MatchA = false, MatchB = false;
4209
4210   // Check if A comes from one of C, D, E, F.
4211   for (unsigned Half = 0; Half != 4; ++Half) {
4212     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4213       MatchA = true;
4214       break;
4215     }
4216   }
4217
4218   // Check if B comes from one of C, D, E, F.
4219   for (unsigned Half = 0; Half != 4; ++Half) {
4220     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4221       MatchB = true;
4222       break;
4223     }
4224   }
4225
4226   return MatchA && MatchB;
4227 }
4228
4229 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4230 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4231 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4232   MVT VT = SVOp->getSimpleValueType(0);
4233
4234   unsigned HalfSize = VT.getVectorNumElements()/2;
4235
4236   unsigned FstHalf = 0, SndHalf = 0;
4237   for (unsigned i = 0; i < HalfSize; ++i) {
4238     if (SVOp->getMaskElt(i) > 0) {
4239       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4240       break;
4241     }
4242   }
4243   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4244     if (SVOp->getMaskElt(i) > 0) {
4245       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4246       break;
4247     }
4248   }
4249
4250   return (FstHalf | (SndHalf << 4));
4251 }
4252
4253 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4254 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4255   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4256   if (EltSize < 32)
4257     return false;
4258
4259   unsigned NumElts = VT.getVectorNumElements();
4260   Imm8 = 0;
4261   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4262     for (unsigned i = 0; i != NumElts; ++i) {
4263       if (Mask[i] < 0)
4264         continue;
4265       Imm8 |= Mask[i] << (i*2);
4266     }
4267     return true;
4268   }
4269
4270   unsigned LaneSize = 4;
4271   SmallVector<int, 4> MaskVal(LaneSize, -1);
4272
4273   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4274     for (unsigned i = 0; i != LaneSize; ++i) {
4275       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4276         return false;
4277       if (Mask[i+l] < 0)
4278         continue;
4279       if (MaskVal[i] < 0) {
4280         MaskVal[i] = Mask[i+l] - l;
4281         Imm8 |= MaskVal[i] << (i*2);
4282         continue;
4283       }
4284       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4285         return false;
4286     }
4287   }
4288   return true;
4289 }
4290
4291 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4292 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4293 /// Note that VPERMIL mask matching is different depending whether theunderlying
4294 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4295 /// to the same elements of the low, but to the higher half of the source.
4296 /// In VPERMILPD the two lanes could be shuffled independently of each other
4297 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4298 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4299   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4300   if (VT.getSizeInBits() < 256 || EltSize < 32)
4301     return false;
4302   bool symetricMaskRequired = (EltSize == 32);
4303   unsigned NumElts = VT.getVectorNumElements();
4304
4305   unsigned NumLanes = VT.getSizeInBits()/128;
4306   unsigned LaneSize = NumElts/NumLanes;
4307   // 2 or 4 elements in one lane
4308
4309   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4310   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4311     for (unsigned i = 0; i != LaneSize; ++i) {
4312       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4313         return false;
4314       if (symetricMaskRequired) {
4315         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4316           ExpectedMaskVal[i] = Mask[i+l] - l;
4317           continue;
4318         }
4319         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4320           return false;
4321       }
4322     }
4323   }
4324   return true;
4325 }
4326
4327 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4328 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4329 /// element of vector 2 and the other elements to come from vector 1 in order.
4330 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4331                                bool V2IsSplat = false, bool V2IsUndef = false) {
4332   if (!VT.is128BitVector())
4333     return false;
4334
4335   unsigned NumOps = VT.getVectorNumElements();
4336   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4337     return false;
4338
4339   if (!isUndefOrEqual(Mask[0], 0))
4340     return false;
4341
4342   for (unsigned i = 1; i != NumOps; ++i)
4343     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4344           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4345           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4346       return false;
4347
4348   return true;
4349 }
4350
4351 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4352 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4353 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4354 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4355                            const X86Subtarget *Subtarget) {
4356   if (!Subtarget->hasSSE3())
4357     return false;
4358
4359   unsigned NumElems = VT.getVectorNumElements();
4360
4361   if ((VT.is128BitVector() && NumElems != 4) ||
4362       (VT.is256BitVector() && NumElems != 8) ||
4363       (VT.is512BitVector() && NumElems != 16))
4364     return false;
4365
4366   // "i+1" is the value the indexed mask element must have
4367   for (unsigned i = 0; i != NumElems; i += 2)
4368     if (!isUndefOrEqual(Mask[i], i+1) ||
4369         !isUndefOrEqual(Mask[i+1], i+1))
4370       return false;
4371
4372   return true;
4373 }
4374
4375 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4376 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4377 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4378 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4379                            const X86Subtarget *Subtarget) {
4380   if (!Subtarget->hasSSE3())
4381     return false;
4382
4383   unsigned NumElems = VT.getVectorNumElements();
4384
4385   if ((VT.is128BitVector() && NumElems != 4) ||
4386       (VT.is256BitVector() && NumElems != 8) ||
4387       (VT.is512BitVector() && NumElems != 16))
4388     return false;
4389
4390   // "i" is the value the indexed mask element must have
4391   for (unsigned i = 0; i != NumElems; i += 2)
4392     if (!isUndefOrEqual(Mask[i], i) ||
4393         !isUndefOrEqual(Mask[i+1], i))
4394       return false;
4395
4396   return true;
4397 }
4398
4399 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4400 /// specifies a shuffle of elements that is suitable for input to 256-bit
4401 /// version of MOVDDUP.
4402 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4403   if (!HasFp256 || !VT.is256BitVector())
4404     return false;
4405
4406   unsigned NumElts = VT.getVectorNumElements();
4407   if (NumElts != 4)
4408     return false;
4409
4410   for (unsigned i = 0; i != NumElts/2; ++i)
4411     if (!isUndefOrEqual(Mask[i], 0))
4412       return false;
4413   for (unsigned i = NumElts/2; i != NumElts; ++i)
4414     if (!isUndefOrEqual(Mask[i], NumElts/2))
4415       return false;
4416   return true;
4417 }
4418
4419 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4420 /// specifies a shuffle of elements that is suitable for input to 128-bit
4421 /// version of MOVDDUP.
4422 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4423   if (!VT.is128BitVector())
4424     return false;
4425
4426   unsigned e = VT.getVectorNumElements() / 2;
4427   for (unsigned i = 0; i != e; ++i)
4428     if (!isUndefOrEqual(Mask[i], i))
4429       return false;
4430   for (unsigned i = 0; i != e; ++i)
4431     if (!isUndefOrEqual(Mask[e+i], i))
4432       return false;
4433   return true;
4434 }
4435
4436 /// isVEXTRACTIndex - Return true if the specified
4437 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4438 /// suitable for instruction that extract 128 or 256 bit vectors
4439 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4440   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4441   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4442     return false;
4443
4444   // The index should be aligned on a vecWidth-bit boundary.
4445   uint64_t Index =
4446     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4447
4448   MVT VT = N->getSimpleValueType(0);
4449   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4450   bool Result = (Index * ElSize) % vecWidth == 0;
4451
4452   return Result;
4453 }
4454
4455 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4456 /// operand specifies a subvector insert that is suitable for input to
4457 /// insertion of 128 or 256-bit subvectors
4458 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4459   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4460   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4461     return false;
4462   // The index should be aligned on a vecWidth-bit boundary.
4463   uint64_t Index =
4464     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4465
4466   MVT VT = N->getSimpleValueType(0);
4467   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4468   bool Result = (Index * ElSize) % vecWidth == 0;
4469
4470   return Result;
4471 }
4472
4473 bool X86::isVINSERT128Index(SDNode *N) {
4474   return isVINSERTIndex(N, 128);
4475 }
4476
4477 bool X86::isVINSERT256Index(SDNode *N) {
4478   return isVINSERTIndex(N, 256);
4479 }
4480
4481 bool X86::isVEXTRACT128Index(SDNode *N) {
4482   return isVEXTRACTIndex(N, 128);
4483 }
4484
4485 bool X86::isVEXTRACT256Index(SDNode *N) {
4486   return isVEXTRACTIndex(N, 256);
4487 }
4488
4489 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4490 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4491 /// Handles 128-bit and 256-bit.
4492 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4493   MVT VT = N->getSimpleValueType(0);
4494
4495   assert((VT.getSizeInBits() >= 128) &&
4496          "Unsupported vector type for PSHUF/SHUFP");
4497
4498   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4499   // independently on 128-bit lanes.
4500   unsigned NumElts = VT.getVectorNumElements();
4501   unsigned NumLanes = VT.getSizeInBits()/128;
4502   unsigned NumLaneElts = NumElts/NumLanes;
4503
4504   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4505          "Only supports 2, 4 or 8 elements per lane");
4506
4507   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4508   unsigned Mask = 0;
4509   for (unsigned i = 0; i != NumElts; ++i) {
4510     int Elt = N->getMaskElt(i);
4511     if (Elt < 0) continue;
4512     Elt &= NumLaneElts - 1;
4513     unsigned ShAmt = (i << Shift) % 8;
4514     Mask |= Elt << ShAmt;
4515   }
4516
4517   return Mask;
4518 }
4519
4520 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4521 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4522 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4523   MVT VT = N->getSimpleValueType(0);
4524
4525   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4526          "Unsupported vector type for PSHUFHW");
4527
4528   unsigned NumElts = VT.getVectorNumElements();
4529
4530   unsigned Mask = 0;
4531   for (unsigned l = 0; l != NumElts; l += 8) {
4532     // 8 nodes per lane, but we only care about the last 4.
4533     for (unsigned i = 0; i < 4; ++i) {
4534       int Elt = N->getMaskElt(l+i+4);
4535       if (Elt < 0) continue;
4536       Elt &= 0x3; // only 2-bits.
4537       Mask |= Elt << (i * 2);
4538     }
4539   }
4540
4541   return Mask;
4542 }
4543
4544 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4545 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4546 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4547   MVT VT = N->getSimpleValueType(0);
4548
4549   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4550          "Unsupported vector type for PSHUFHW");
4551
4552   unsigned NumElts = VT.getVectorNumElements();
4553
4554   unsigned Mask = 0;
4555   for (unsigned l = 0; l != NumElts; l += 8) {
4556     // 8 nodes per lane, but we only care about the first 4.
4557     for (unsigned i = 0; i < 4; ++i) {
4558       int Elt = N->getMaskElt(l+i);
4559       if (Elt < 0) continue;
4560       Elt &= 0x3; // only 2-bits
4561       Mask |= Elt << (i * 2);
4562     }
4563   }
4564
4565   return Mask;
4566 }
4567
4568 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4569 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4570 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4571   MVT VT = SVOp->getSimpleValueType(0);
4572   unsigned EltSize = VT.is512BitVector() ? 1 :
4573     VT.getVectorElementType().getSizeInBits() >> 3;
4574
4575   unsigned NumElts = VT.getVectorNumElements();
4576   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4577   unsigned NumLaneElts = NumElts/NumLanes;
4578
4579   int Val = 0;
4580   unsigned i;
4581   for (i = 0; i != NumElts; ++i) {
4582     Val = SVOp->getMaskElt(i);
4583     if (Val >= 0)
4584       break;
4585   }
4586   if (Val >= (int)NumElts)
4587     Val -= NumElts - NumLaneElts;
4588
4589   assert(Val - i > 0 && "PALIGNR imm should be positive");
4590   return (Val - i) * EltSize;
4591 }
4592
4593 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4594   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4595   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4596     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4597
4598   uint64_t Index =
4599     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4600
4601   MVT VecVT = N->getOperand(0).getSimpleValueType();
4602   MVT ElVT = VecVT.getVectorElementType();
4603
4604   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4605   return Index / NumElemsPerChunk;
4606 }
4607
4608 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4609   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4610   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4611     llvm_unreachable("Illegal insert subvector for VINSERT");
4612
4613   uint64_t Index =
4614     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4615
4616   MVT VecVT = N->getSimpleValueType(0);
4617   MVT ElVT = VecVT.getVectorElementType();
4618
4619   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4620   return Index / NumElemsPerChunk;
4621 }
4622
4623 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4624 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4625 /// and VINSERTI128 instructions.
4626 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4627   return getExtractVEXTRACTImmediate(N, 128);
4628 }
4629
4630 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4631 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4632 /// and VINSERTI64x4 instructions.
4633 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4634   return getExtractVEXTRACTImmediate(N, 256);
4635 }
4636
4637 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4638 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4639 /// and VINSERTI128 instructions.
4640 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4641   return getInsertVINSERTImmediate(N, 128);
4642 }
4643
4644 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4645 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4646 /// and VINSERTI64x4 instructions.
4647 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4648   return getInsertVINSERTImmediate(N, 256);
4649 }
4650
4651 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4652 /// constant +0.0.
4653 bool X86::isZeroNode(SDValue Elt) {
4654   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4655     return CN->isNullValue();
4656   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4657     return CFP->getValueAPF().isPosZero();
4658   return false;
4659 }
4660
4661 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4662 /// their permute mask.
4663 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4664                                     SelectionDAG &DAG) {
4665   MVT VT = SVOp->getSimpleValueType(0);
4666   unsigned NumElems = VT.getVectorNumElements();
4667   SmallVector<int, 8> MaskVec;
4668
4669   for (unsigned i = 0; i != NumElems; ++i) {
4670     int Idx = SVOp->getMaskElt(i);
4671     if (Idx >= 0) {
4672       if (Idx < (int)NumElems)
4673         Idx += NumElems;
4674       else
4675         Idx -= NumElems;
4676     }
4677     MaskVec.push_back(Idx);
4678   }
4679   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4680                               SVOp->getOperand(0), &MaskVec[0]);
4681 }
4682
4683 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4684 /// match movhlps. The lower half elements should come from upper half of
4685 /// V1 (and in order), and the upper half elements should come from the upper
4686 /// half of V2 (and in order).
4687 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4688   if (!VT.is128BitVector())
4689     return false;
4690   if (VT.getVectorNumElements() != 4)
4691     return false;
4692   for (unsigned i = 0, e = 2; i != e; ++i)
4693     if (!isUndefOrEqual(Mask[i], i+2))
4694       return false;
4695   for (unsigned i = 2; i != 4; ++i)
4696     if (!isUndefOrEqual(Mask[i], i+4))
4697       return false;
4698   return true;
4699 }
4700
4701 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4702 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4703 /// required.
4704 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4705   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4706     return false;
4707   N = N->getOperand(0).getNode();
4708   if (!ISD::isNON_EXTLoad(N))
4709     return false;
4710   if (LD)
4711     *LD = cast<LoadSDNode>(N);
4712   return true;
4713 }
4714
4715 // Test whether the given value is a vector value which will be legalized
4716 // into a load.
4717 static bool WillBeConstantPoolLoad(SDNode *N) {
4718   if (N->getOpcode() != ISD::BUILD_VECTOR)
4719     return false;
4720
4721   // Check for any non-constant elements.
4722   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4723     switch (N->getOperand(i).getNode()->getOpcode()) {
4724     case ISD::UNDEF:
4725     case ISD::ConstantFP:
4726     case ISD::Constant:
4727       break;
4728     default:
4729       return false;
4730     }
4731
4732   // Vectors of all-zeros and all-ones are materialized with special
4733   // instructions rather than being loaded.
4734   return !ISD::isBuildVectorAllZeros(N) &&
4735          !ISD::isBuildVectorAllOnes(N);
4736 }
4737
4738 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4739 /// match movlp{s|d}. The lower half elements should come from lower half of
4740 /// V1 (and in order), and the upper half elements should come from the upper
4741 /// half of V2 (and in order). And since V1 will become the source of the
4742 /// MOVLP, it must be either a vector load or a scalar load to vector.
4743 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4744                                ArrayRef<int> Mask, MVT VT) {
4745   if (!VT.is128BitVector())
4746     return false;
4747
4748   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4749     return false;
4750   // Is V2 is a vector load, don't do this transformation. We will try to use
4751   // load folding shufps op.
4752   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4753     return false;
4754
4755   unsigned NumElems = VT.getVectorNumElements();
4756
4757   if (NumElems != 2 && NumElems != 4)
4758     return false;
4759   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4760     if (!isUndefOrEqual(Mask[i], i))
4761       return false;
4762   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4763     if (!isUndefOrEqual(Mask[i], i+NumElems))
4764       return false;
4765   return true;
4766 }
4767
4768 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4769 /// all the same.
4770 static bool isSplatVector(SDNode *N) {
4771   if (N->getOpcode() != ISD::BUILD_VECTOR)
4772     return false;
4773
4774   SDValue SplatValue = N->getOperand(0);
4775   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4776     if (N->getOperand(i) != SplatValue)
4777       return false;
4778   return true;
4779 }
4780
4781 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4782 /// to an zero vector.
4783 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4784 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4785   SDValue V1 = N->getOperand(0);
4786   SDValue V2 = N->getOperand(1);
4787   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4788   for (unsigned i = 0; i != NumElems; ++i) {
4789     int Idx = N->getMaskElt(i);
4790     if (Idx >= (int)NumElems) {
4791       unsigned Opc = V2.getOpcode();
4792       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4793         continue;
4794       if (Opc != ISD::BUILD_VECTOR ||
4795           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4796         return false;
4797     } else if (Idx >= 0) {
4798       unsigned Opc = V1.getOpcode();
4799       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4800         continue;
4801       if (Opc != ISD::BUILD_VECTOR ||
4802           !X86::isZeroNode(V1.getOperand(Idx)))
4803         return false;
4804     }
4805   }
4806   return true;
4807 }
4808
4809 /// getZeroVector - Returns a vector of specified type with all zero elements.
4810 ///
4811 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4812                              SelectionDAG &DAG, SDLoc dl) {
4813   assert(VT.isVector() && "Expected a vector type");
4814
4815   // Always build SSE zero vectors as <4 x i32> bitcasted
4816   // to their dest type. This ensures they get CSE'd.
4817   SDValue Vec;
4818   if (VT.is128BitVector()) {  // SSE
4819     if (Subtarget->hasSSE2()) {  // SSE2
4820       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4821       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4822     } else { // SSE1
4823       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4824       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4825     }
4826   } else if (VT.is256BitVector()) { // AVX
4827     if (Subtarget->hasInt256()) { // AVX2
4828       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4829       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4830       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4831                         array_lengthof(Ops));
4832     } else {
4833       // 256-bit logic and arithmetic instructions in AVX are all
4834       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4835       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4836       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4837       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4838                         array_lengthof(Ops));
4839     }
4840   } else if (VT.is512BitVector()) { // AVX-512
4841       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4842       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4843                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4844       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4845   } else if (VT.getScalarType() == MVT::i1) {
4846     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4847     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4848     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4849                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4850     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4851                        Ops, VT.getVectorNumElements());
4852   } else
4853     llvm_unreachable("Unexpected vector type");
4854
4855   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4856 }
4857
4858 /// getOnesVector - Returns a vector of specified type with all bits set.
4859 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4860 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4861 /// Then bitcast to their original type, ensuring they get CSE'd.
4862 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4863                              SDLoc dl) {
4864   assert(VT.isVector() && "Expected a vector type");
4865
4866   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4867   SDValue Vec;
4868   if (VT.is256BitVector()) {
4869     if (HasInt256) { // AVX2
4870       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4871       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4872                         array_lengthof(Ops));
4873     } else { // AVX
4874       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4875       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4876     }
4877   } else if (VT.is128BitVector()) {
4878     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4879   } else
4880     llvm_unreachable("Unexpected vector type");
4881
4882   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4883 }
4884
4885 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4886 /// that point to V2 points to its first element.
4887 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4888   for (unsigned i = 0; i != NumElems; ++i) {
4889     if (Mask[i] > (int)NumElems) {
4890       Mask[i] = NumElems;
4891     }
4892   }
4893 }
4894
4895 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4896 /// operation of specified width.
4897 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4898                        SDValue V2) {
4899   unsigned NumElems = VT.getVectorNumElements();
4900   SmallVector<int, 8> Mask;
4901   Mask.push_back(NumElems);
4902   for (unsigned i = 1; i != NumElems; ++i)
4903     Mask.push_back(i);
4904   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4905 }
4906
4907 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4908 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4909                           SDValue V2) {
4910   unsigned NumElems = VT.getVectorNumElements();
4911   SmallVector<int, 8> Mask;
4912   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4913     Mask.push_back(i);
4914     Mask.push_back(i + NumElems);
4915   }
4916   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4917 }
4918
4919 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4920 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4921                           SDValue V2) {
4922   unsigned NumElems = VT.getVectorNumElements();
4923   SmallVector<int, 8> Mask;
4924   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4925     Mask.push_back(i + Half);
4926     Mask.push_back(i + NumElems + Half);
4927   }
4928   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4929 }
4930
4931 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4932 // a generic shuffle instruction because the target has no such instructions.
4933 // Generate shuffles which repeat i16 and i8 several times until they can be
4934 // represented by v4f32 and then be manipulated by target suported shuffles.
4935 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4936   MVT VT = V.getSimpleValueType();
4937   int NumElems = VT.getVectorNumElements();
4938   SDLoc dl(V);
4939
4940   while (NumElems > 4) {
4941     if (EltNo < NumElems/2) {
4942       V = getUnpackl(DAG, dl, VT, V, V);
4943     } else {
4944       V = getUnpackh(DAG, dl, VT, V, V);
4945       EltNo -= NumElems/2;
4946     }
4947     NumElems >>= 1;
4948   }
4949   return V;
4950 }
4951
4952 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4953 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4954   MVT VT = V.getSimpleValueType();
4955   SDLoc dl(V);
4956
4957   if (VT.is128BitVector()) {
4958     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4959     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4960     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4961                              &SplatMask[0]);
4962   } else if (VT.is256BitVector()) {
4963     // To use VPERMILPS to splat scalars, the second half of indicies must
4964     // refer to the higher part, which is a duplication of the lower one,
4965     // because VPERMILPS can only handle in-lane permutations.
4966     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4967                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4968
4969     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4970     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4971                              &SplatMask[0]);
4972   } else
4973     llvm_unreachable("Vector size not supported");
4974
4975   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4976 }
4977
4978 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4979 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4980   MVT SrcVT = SV->getSimpleValueType(0);
4981   SDValue V1 = SV->getOperand(0);
4982   SDLoc dl(SV);
4983
4984   int EltNo = SV->getSplatIndex();
4985   int NumElems = SrcVT.getVectorNumElements();
4986   bool Is256BitVec = SrcVT.is256BitVector();
4987
4988   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4989          "Unknown how to promote splat for type");
4990
4991   // Extract the 128-bit part containing the splat element and update
4992   // the splat element index when it refers to the higher register.
4993   if (Is256BitVec) {
4994     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4995     if (EltNo >= NumElems/2)
4996       EltNo -= NumElems/2;
4997   }
4998
4999   // All i16 and i8 vector types can't be used directly by a generic shuffle
5000   // instruction because the target has no such instruction. Generate shuffles
5001   // which repeat i16 and i8 several times until they fit in i32, and then can
5002   // be manipulated by target suported shuffles.
5003   MVT EltVT = SrcVT.getVectorElementType();
5004   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5005     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5006
5007   // Recreate the 256-bit vector and place the same 128-bit vector
5008   // into the low and high part. This is necessary because we want
5009   // to use VPERM* to shuffle the vectors
5010   if (Is256BitVec) {
5011     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5012   }
5013
5014   return getLegalSplat(DAG, V1, EltNo);
5015 }
5016
5017 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5018 /// vector of zero or undef vector.  This produces a shuffle where the low
5019 /// element of V2 is swizzled into the zero/undef vector, landing at element
5020 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5021 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5022                                            bool IsZero,
5023                                            const X86Subtarget *Subtarget,
5024                                            SelectionDAG &DAG) {
5025   MVT VT = V2.getSimpleValueType();
5026   SDValue V1 = IsZero
5027     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5028   unsigned NumElems = VT.getVectorNumElements();
5029   SmallVector<int, 16> MaskVec;
5030   for (unsigned i = 0; i != NumElems; ++i)
5031     // If this is the insertion idx, put the low elt of V2 here.
5032     MaskVec.push_back(i == Idx ? NumElems : i);
5033   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5034 }
5035
5036 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5037 /// target specific opcode. Returns true if the Mask could be calculated.
5038 /// Sets IsUnary to true if only uses one source.
5039 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5040                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5041   unsigned NumElems = VT.getVectorNumElements();
5042   SDValue ImmN;
5043
5044   IsUnary = false;
5045   switch(N->getOpcode()) {
5046   case X86ISD::SHUFP:
5047     ImmN = N->getOperand(N->getNumOperands()-1);
5048     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5049     break;
5050   case X86ISD::UNPCKH:
5051     DecodeUNPCKHMask(VT, Mask);
5052     break;
5053   case X86ISD::UNPCKL:
5054     DecodeUNPCKLMask(VT, Mask);
5055     break;
5056   case X86ISD::MOVHLPS:
5057     DecodeMOVHLPSMask(NumElems, Mask);
5058     break;
5059   case X86ISD::MOVLHPS:
5060     DecodeMOVLHPSMask(NumElems, Mask);
5061     break;
5062   case X86ISD::PALIGNR:
5063     ImmN = N->getOperand(N->getNumOperands()-1);
5064     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5065     break;
5066   case X86ISD::PSHUFD:
5067   case X86ISD::VPERMILP:
5068     ImmN = N->getOperand(N->getNumOperands()-1);
5069     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5070     IsUnary = true;
5071     break;
5072   case X86ISD::PSHUFHW:
5073     ImmN = N->getOperand(N->getNumOperands()-1);
5074     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5075     IsUnary = true;
5076     break;
5077   case X86ISD::PSHUFLW:
5078     ImmN = N->getOperand(N->getNumOperands()-1);
5079     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5080     IsUnary = true;
5081     break;
5082   case X86ISD::VPERMI:
5083     ImmN = N->getOperand(N->getNumOperands()-1);
5084     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5085     IsUnary = true;
5086     break;
5087   case X86ISD::MOVSS:
5088   case X86ISD::MOVSD: {
5089     // The index 0 always comes from the first element of the second source,
5090     // this is why MOVSS and MOVSD are used in the first place. The other
5091     // elements come from the other positions of the first source vector
5092     Mask.push_back(NumElems);
5093     for (unsigned i = 1; i != NumElems; ++i) {
5094       Mask.push_back(i);
5095     }
5096     break;
5097   }
5098   case X86ISD::VPERM2X128:
5099     ImmN = N->getOperand(N->getNumOperands()-1);
5100     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5101     if (Mask.empty()) return false;
5102     break;
5103   case X86ISD::MOVDDUP:
5104   case X86ISD::MOVLHPD:
5105   case X86ISD::MOVLPD:
5106   case X86ISD::MOVLPS:
5107   case X86ISD::MOVSHDUP:
5108   case X86ISD::MOVSLDUP:
5109     // Not yet implemented
5110     return false;
5111   default: llvm_unreachable("unknown target shuffle node");
5112   }
5113
5114   return true;
5115 }
5116
5117 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5118 /// element of the result of the vector shuffle.
5119 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5120                                    unsigned Depth) {
5121   if (Depth == 6)
5122     return SDValue();  // Limit search depth.
5123
5124   SDValue V = SDValue(N, 0);
5125   EVT VT = V.getValueType();
5126   unsigned Opcode = V.getOpcode();
5127
5128   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5129   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5130     int Elt = SV->getMaskElt(Index);
5131
5132     if (Elt < 0)
5133       return DAG.getUNDEF(VT.getVectorElementType());
5134
5135     unsigned NumElems = VT.getVectorNumElements();
5136     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5137                                          : SV->getOperand(1);
5138     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5139   }
5140
5141   // Recurse into target specific vector shuffles to find scalars.
5142   if (isTargetShuffle(Opcode)) {
5143     MVT ShufVT = V.getSimpleValueType();
5144     unsigned NumElems = ShufVT.getVectorNumElements();
5145     SmallVector<int, 16> ShuffleMask;
5146     bool IsUnary;
5147
5148     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5149       return SDValue();
5150
5151     int Elt = ShuffleMask[Index];
5152     if (Elt < 0)
5153       return DAG.getUNDEF(ShufVT.getVectorElementType());
5154
5155     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5156                                          : N->getOperand(1);
5157     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5158                                Depth+1);
5159   }
5160
5161   // Actual nodes that may contain scalar elements
5162   if (Opcode == ISD::BITCAST) {
5163     V = V.getOperand(0);
5164     EVT SrcVT = V.getValueType();
5165     unsigned NumElems = VT.getVectorNumElements();
5166
5167     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5168       return SDValue();
5169   }
5170
5171   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5172     return (Index == 0) ? V.getOperand(0)
5173                         : DAG.getUNDEF(VT.getVectorElementType());
5174
5175   if (V.getOpcode() == ISD::BUILD_VECTOR)
5176     return V.getOperand(Index);
5177
5178   return SDValue();
5179 }
5180
5181 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5182 /// shuffle operation which come from a consecutively from a zero. The
5183 /// search can start in two different directions, from left or right.
5184 /// We count undefs as zeros until PreferredNum is reached.
5185 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5186                                          unsigned NumElems, bool ZerosFromLeft,
5187                                          SelectionDAG &DAG,
5188                                          unsigned PreferredNum = -1U) {
5189   unsigned NumZeros = 0;
5190   for (unsigned i = 0; i != NumElems; ++i) {
5191     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5192     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5193     if (!Elt.getNode())
5194       break;
5195
5196     if (X86::isZeroNode(Elt))
5197       ++NumZeros;
5198     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5199       NumZeros = std::min(NumZeros + 1, PreferredNum);
5200     else
5201       break;
5202   }
5203
5204   return NumZeros;
5205 }
5206
5207 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5208 /// correspond consecutively to elements from one of the vector operands,
5209 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5210 static
5211 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5212                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5213                               unsigned NumElems, unsigned &OpNum) {
5214   bool SeenV1 = false;
5215   bool SeenV2 = false;
5216
5217   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5218     int Idx = SVOp->getMaskElt(i);
5219     // Ignore undef indicies
5220     if (Idx < 0)
5221       continue;
5222
5223     if (Idx < (int)NumElems)
5224       SeenV1 = true;
5225     else
5226       SeenV2 = true;
5227
5228     // Only accept consecutive elements from the same vector
5229     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5230       return false;
5231   }
5232
5233   OpNum = SeenV1 ? 0 : 1;
5234   return true;
5235 }
5236
5237 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5238 /// logical left shift of a vector.
5239 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5240                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5241   unsigned NumElems =
5242     SVOp->getSimpleValueType(0).getVectorNumElements();
5243   unsigned NumZeros = getNumOfConsecutiveZeros(
5244       SVOp, NumElems, false /* check zeros from right */, DAG,
5245       SVOp->getMaskElt(0));
5246   unsigned OpSrc;
5247
5248   if (!NumZeros)
5249     return false;
5250
5251   // Considering the elements in the mask that are not consecutive zeros,
5252   // check if they consecutively come from only one of the source vectors.
5253   //
5254   //               V1 = {X, A, B, C}     0
5255   //                         \  \  \    /
5256   //   vector_shuffle V1, V2 <1, 2, 3, X>
5257   //
5258   if (!isShuffleMaskConsecutive(SVOp,
5259             0,                   // Mask Start Index
5260             NumElems-NumZeros,   // Mask End Index(exclusive)
5261             NumZeros,            // Where to start looking in the src vector
5262             NumElems,            // Number of elements in vector
5263             OpSrc))              // Which source operand ?
5264     return false;
5265
5266   isLeft = false;
5267   ShAmt = NumZeros;
5268   ShVal = SVOp->getOperand(OpSrc);
5269   return true;
5270 }
5271
5272 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5273 /// logical left shift of a vector.
5274 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5275                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5276   unsigned NumElems =
5277     SVOp->getSimpleValueType(0).getVectorNumElements();
5278   unsigned NumZeros = getNumOfConsecutiveZeros(
5279       SVOp, NumElems, true /* check zeros from left */, DAG,
5280       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5281   unsigned OpSrc;
5282
5283   if (!NumZeros)
5284     return false;
5285
5286   // Considering the elements in the mask that are not consecutive zeros,
5287   // check if they consecutively come from only one of the source vectors.
5288   //
5289   //                           0    { A, B, X, X } = V2
5290   //                          / \    /  /
5291   //   vector_shuffle V1, V2 <X, X, 4, 5>
5292   //
5293   if (!isShuffleMaskConsecutive(SVOp,
5294             NumZeros,     // Mask Start Index
5295             NumElems,     // Mask End Index(exclusive)
5296             0,            // Where to start looking in the src vector
5297             NumElems,     // Number of elements in vector
5298             OpSrc))       // Which source operand ?
5299     return false;
5300
5301   isLeft = true;
5302   ShAmt = NumZeros;
5303   ShVal = SVOp->getOperand(OpSrc);
5304   return true;
5305 }
5306
5307 /// isVectorShift - Returns true if the shuffle can be implemented as a
5308 /// logical left or right shift of a vector.
5309 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5310                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5311   // Although the logic below support any bitwidth size, there are no
5312   // shift instructions which handle more than 128-bit vectors.
5313   if (!SVOp->getSimpleValueType(0).is128BitVector())
5314     return false;
5315
5316   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5317       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5318     return true;
5319
5320   return false;
5321 }
5322
5323 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5324 ///
5325 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5326                                        unsigned NumNonZero, unsigned NumZero,
5327                                        SelectionDAG &DAG,
5328                                        const X86Subtarget* Subtarget,
5329                                        const TargetLowering &TLI) {
5330   if (NumNonZero > 8)
5331     return SDValue();
5332
5333   SDLoc dl(Op);
5334   SDValue V;
5335   bool First = true;
5336   for (unsigned i = 0; i < 16; ++i) {
5337     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5338     if (ThisIsNonZero && First) {
5339       if (NumZero)
5340         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5341       else
5342         V = DAG.getUNDEF(MVT::v8i16);
5343       First = false;
5344     }
5345
5346     if ((i & 1) != 0) {
5347       SDValue ThisElt, LastElt;
5348       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5349       if (LastIsNonZero) {
5350         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5351                               MVT::i16, Op.getOperand(i-1));
5352       }
5353       if (ThisIsNonZero) {
5354         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5355         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5356                               ThisElt, DAG.getConstant(8, MVT::i8));
5357         if (LastIsNonZero)
5358           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5359       } else
5360         ThisElt = LastElt;
5361
5362       if (ThisElt.getNode())
5363         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5364                         DAG.getIntPtrConstant(i/2));
5365     }
5366   }
5367
5368   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5369 }
5370
5371 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5372 ///
5373 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5374                                      unsigned NumNonZero, unsigned NumZero,
5375                                      SelectionDAG &DAG,
5376                                      const X86Subtarget* Subtarget,
5377                                      const TargetLowering &TLI) {
5378   if (NumNonZero > 4)
5379     return SDValue();
5380
5381   SDLoc dl(Op);
5382   SDValue V;
5383   bool First = true;
5384   for (unsigned i = 0; i < 8; ++i) {
5385     bool isNonZero = (NonZeros & (1 << i)) != 0;
5386     if (isNonZero) {
5387       if (First) {
5388         if (NumZero)
5389           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5390         else
5391           V = DAG.getUNDEF(MVT::v8i16);
5392         First = false;
5393       }
5394       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5395                       MVT::v8i16, V, Op.getOperand(i),
5396                       DAG.getIntPtrConstant(i));
5397     }
5398   }
5399
5400   return V;
5401 }
5402
5403 /// getVShift - Return a vector logical shift node.
5404 ///
5405 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5406                          unsigned NumBits, SelectionDAG &DAG,
5407                          const TargetLowering &TLI, SDLoc dl) {
5408   assert(VT.is128BitVector() && "Unknown type for VShift");
5409   EVT ShVT = MVT::v2i64;
5410   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5411   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5412   return DAG.getNode(ISD::BITCAST, dl, VT,
5413                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5414                              DAG.getConstant(NumBits,
5415                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5416 }
5417
5418 static SDValue
5419 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5420
5421   // Check if the scalar load can be widened into a vector load. And if
5422   // the address is "base + cst" see if the cst can be "absorbed" into
5423   // the shuffle mask.
5424   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5425     SDValue Ptr = LD->getBasePtr();
5426     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5427       return SDValue();
5428     EVT PVT = LD->getValueType(0);
5429     if (PVT != MVT::i32 && PVT != MVT::f32)
5430       return SDValue();
5431
5432     int FI = -1;
5433     int64_t Offset = 0;
5434     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5435       FI = FINode->getIndex();
5436       Offset = 0;
5437     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5438                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5439       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5440       Offset = Ptr.getConstantOperandVal(1);
5441       Ptr = Ptr.getOperand(0);
5442     } else {
5443       return SDValue();
5444     }
5445
5446     // FIXME: 256-bit vector instructions don't require a strict alignment,
5447     // improve this code to support it better.
5448     unsigned RequiredAlign = VT.getSizeInBits()/8;
5449     SDValue Chain = LD->getChain();
5450     // Make sure the stack object alignment is at least 16 or 32.
5451     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5452     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5453       if (MFI->isFixedObjectIndex(FI)) {
5454         // Can't change the alignment. FIXME: It's possible to compute
5455         // the exact stack offset and reference FI + adjust offset instead.
5456         // If someone *really* cares about this. That's the way to implement it.
5457         return SDValue();
5458       } else {
5459         MFI->setObjectAlignment(FI, RequiredAlign);
5460       }
5461     }
5462
5463     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5464     // Ptr + (Offset & ~15).
5465     if (Offset < 0)
5466       return SDValue();
5467     if ((Offset % RequiredAlign) & 3)
5468       return SDValue();
5469     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5470     if (StartOffset)
5471       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5472                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5473
5474     int EltNo = (Offset - StartOffset) >> 2;
5475     unsigned NumElems = VT.getVectorNumElements();
5476
5477     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5478     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5479                              LD->getPointerInfo().getWithOffset(StartOffset),
5480                              false, false, false, 0);
5481
5482     SmallVector<int, 8> Mask;
5483     for (unsigned i = 0; i != NumElems; ++i)
5484       Mask.push_back(EltNo);
5485
5486     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5487   }
5488
5489   return SDValue();
5490 }
5491
5492 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5493 /// vector of type 'VT', see if the elements can be replaced by a single large
5494 /// load which has the same value as a build_vector whose operands are 'elts'.
5495 ///
5496 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5497 ///
5498 /// FIXME: we'd also like to handle the case where the last elements are zero
5499 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5500 /// There's even a handy isZeroNode for that purpose.
5501 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5502                                         SDLoc &DL, SelectionDAG &DAG,
5503                                         bool isAfterLegalize) {
5504   EVT EltVT = VT.getVectorElementType();
5505   unsigned NumElems = Elts.size();
5506
5507   LoadSDNode *LDBase = nullptr;
5508   unsigned LastLoadedElt = -1U;
5509
5510   // For each element in the initializer, see if we've found a load or an undef.
5511   // If we don't find an initial load element, or later load elements are
5512   // non-consecutive, bail out.
5513   for (unsigned i = 0; i < NumElems; ++i) {
5514     SDValue Elt = Elts[i];
5515
5516     if (!Elt.getNode() ||
5517         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5518       return SDValue();
5519     if (!LDBase) {
5520       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5521         return SDValue();
5522       LDBase = cast<LoadSDNode>(Elt.getNode());
5523       LastLoadedElt = i;
5524       continue;
5525     }
5526     if (Elt.getOpcode() == ISD::UNDEF)
5527       continue;
5528
5529     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5530     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5531       return SDValue();
5532     LastLoadedElt = i;
5533   }
5534
5535   // If we have found an entire vector of loads and undefs, then return a large
5536   // load of the entire vector width starting at the base pointer.  If we found
5537   // consecutive loads for the low half, generate a vzext_load node.
5538   if (LastLoadedElt == NumElems - 1) {
5539
5540     if (isAfterLegalize &&
5541         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5542       return SDValue();
5543
5544     SDValue NewLd = SDValue();
5545
5546     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5547       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5548                           LDBase->getPointerInfo(),
5549                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5550                           LDBase->isInvariant(), 0);
5551     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5552                         LDBase->getPointerInfo(),
5553                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5554                         LDBase->isInvariant(), LDBase->getAlignment());
5555
5556     if (LDBase->hasAnyUseOfValue(1)) {
5557       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5558                                      SDValue(LDBase, 1),
5559                                      SDValue(NewLd.getNode(), 1));
5560       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5561       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5562                              SDValue(NewLd.getNode(), 1));
5563     }
5564
5565     return NewLd;
5566   }
5567   if (NumElems == 4 && LastLoadedElt == 1 &&
5568       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5569     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5570     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5571     SDValue ResNode =
5572         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5573                                 array_lengthof(Ops), MVT::i64,
5574                                 LDBase->getPointerInfo(),
5575                                 LDBase->getAlignment(),
5576                                 false/*isVolatile*/, true/*ReadMem*/,
5577                                 false/*WriteMem*/);
5578
5579     // Make sure the newly-created LOAD is in the same position as LDBase in
5580     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5581     // update uses of LDBase's output chain to use the TokenFactor.
5582     if (LDBase->hasAnyUseOfValue(1)) {
5583       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5584                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5585       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5586       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5587                              SDValue(ResNode.getNode(), 1));
5588     }
5589
5590     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5591   }
5592   return SDValue();
5593 }
5594
5595 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5596 /// to generate a splat value for the following cases:
5597 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5598 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5599 /// a scalar load, or a constant.
5600 /// The VBROADCAST node is returned when a pattern is found,
5601 /// or SDValue() otherwise.
5602 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5603                                     SelectionDAG &DAG) {
5604   if (!Subtarget->hasFp256())
5605     return SDValue();
5606
5607   MVT VT = Op.getSimpleValueType();
5608   SDLoc dl(Op);
5609
5610   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5611          "Unsupported vector type for broadcast.");
5612
5613   SDValue Ld;
5614   bool ConstSplatVal;
5615
5616   switch (Op.getOpcode()) {
5617     default:
5618       // Unknown pattern found.
5619       return SDValue();
5620
5621     case ISD::BUILD_VECTOR: {
5622       // The BUILD_VECTOR node must be a splat.
5623       if (!isSplatVector(Op.getNode()))
5624         return SDValue();
5625
5626       Ld = Op.getOperand(0);
5627       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5628                      Ld.getOpcode() == ISD::ConstantFP);
5629
5630       // The suspected load node has several users. Make sure that all
5631       // of its users are from the BUILD_VECTOR node.
5632       // Constants may have multiple users.
5633       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5634         return SDValue();
5635       break;
5636     }
5637
5638     case ISD::VECTOR_SHUFFLE: {
5639       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5640
5641       // Shuffles must have a splat mask where the first element is
5642       // broadcasted.
5643       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5644         return SDValue();
5645
5646       SDValue Sc = Op.getOperand(0);
5647       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5648           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5649
5650         if (!Subtarget->hasInt256())
5651           return SDValue();
5652
5653         // Use the register form of the broadcast instruction available on AVX2.
5654         if (VT.getSizeInBits() >= 256)
5655           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5656         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5657       }
5658
5659       Ld = Sc.getOperand(0);
5660       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5661                        Ld.getOpcode() == ISD::ConstantFP);
5662
5663       // The scalar_to_vector node and the suspected
5664       // load node must have exactly one user.
5665       // Constants may have multiple users.
5666
5667       // AVX-512 has register version of the broadcast
5668       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5669         Ld.getValueType().getSizeInBits() >= 32;
5670       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5671           !hasRegVer))
5672         return SDValue();
5673       break;
5674     }
5675   }
5676
5677   bool IsGE256 = (VT.getSizeInBits() >= 256);
5678
5679   // Handle the broadcasting a single constant scalar from the constant pool
5680   // into a vector. On Sandybridge it is still better to load a constant vector
5681   // from the constant pool and not to broadcast it from a scalar.
5682   if (ConstSplatVal && Subtarget->hasInt256()) {
5683     EVT CVT = Ld.getValueType();
5684     assert(!CVT.isVector() && "Must not broadcast a vector type");
5685     unsigned ScalarSize = CVT.getSizeInBits();
5686
5687     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5688       const Constant *C = nullptr;
5689       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5690         C = CI->getConstantIntValue();
5691       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5692         C = CF->getConstantFPValue();
5693
5694       assert(C && "Invalid constant type");
5695
5696       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5697       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5698       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5699       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5700                        MachinePointerInfo::getConstantPool(),
5701                        false, false, false, Alignment);
5702
5703       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5704     }
5705   }
5706
5707   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5708   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5709
5710   // Handle AVX2 in-register broadcasts.
5711   if (!IsLoad && Subtarget->hasInt256() &&
5712       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5713     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5714
5715   // The scalar source must be a normal load.
5716   if (!IsLoad)
5717     return SDValue();
5718
5719   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5720     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5721
5722   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5723   // double since there is no vbroadcastsd xmm
5724   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5725     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5726       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5727   }
5728
5729   // Unsupported broadcast.
5730   return SDValue();
5731 }
5732
5733 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5734 /// underlying vector and index.
5735 ///
5736 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5737 /// index.
5738 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5739                                          SDValue ExtIdx) {
5740   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5741   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5742     return Idx;
5743
5744   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5745   // lowered this:
5746   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5747   // to:
5748   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5749   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5750   //                           undef)
5751   //                       Constant<0>)
5752   // In this case the vector is the extract_subvector expression and the index
5753   // is 2, as specified by the shuffle.
5754   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5755   SDValue ShuffleVec = SVOp->getOperand(0);
5756   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5757   assert(ShuffleVecVT.getVectorElementType() ==
5758          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5759
5760   int ShuffleIdx = SVOp->getMaskElt(Idx);
5761   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5762     ExtractedFromVec = ShuffleVec;
5763     return ShuffleIdx;
5764   }
5765   return Idx;
5766 }
5767
5768 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5769   MVT VT = Op.getSimpleValueType();
5770
5771   // Skip if insert_vec_elt is not supported.
5772   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5773   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5774     return SDValue();
5775
5776   SDLoc DL(Op);
5777   unsigned NumElems = Op.getNumOperands();
5778
5779   SDValue VecIn1;
5780   SDValue VecIn2;
5781   SmallVector<unsigned, 4> InsertIndices;
5782   SmallVector<int, 8> Mask(NumElems, -1);
5783
5784   for (unsigned i = 0; i != NumElems; ++i) {
5785     unsigned Opc = Op.getOperand(i).getOpcode();
5786
5787     if (Opc == ISD::UNDEF)
5788       continue;
5789
5790     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5791       // Quit if more than 1 elements need inserting.
5792       if (InsertIndices.size() > 1)
5793         return SDValue();
5794
5795       InsertIndices.push_back(i);
5796       continue;
5797     }
5798
5799     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5800     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5801     // Quit if non-constant index.
5802     if (!isa<ConstantSDNode>(ExtIdx))
5803       return SDValue();
5804     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5805
5806     // Quit if extracted from vector of different type.
5807     if (ExtractedFromVec.getValueType() != VT)
5808       return SDValue();
5809
5810     if (!VecIn1.getNode())
5811       VecIn1 = ExtractedFromVec;
5812     else if (VecIn1 != ExtractedFromVec) {
5813       if (!VecIn2.getNode())
5814         VecIn2 = ExtractedFromVec;
5815       else if (VecIn2 != ExtractedFromVec)
5816         // Quit if more than 2 vectors to shuffle
5817         return SDValue();
5818     }
5819
5820     if (ExtractedFromVec == VecIn1)
5821       Mask[i] = Idx;
5822     else if (ExtractedFromVec == VecIn2)
5823       Mask[i] = Idx + NumElems;
5824   }
5825
5826   if (!VecIn1.getNode())
5827     return SDValue();
5828
5829   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5830   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5831   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5832     unsigned Idx = InsertIndices[i];
5833     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5834                      DAG.getIntPtrConstant(Idx));
5835   }
5836
5837   return NV;
5838 }
5839
5840 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5841 SDValue
5842 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5843
5844   MVT VT = Op.getSimpleValueType();
5845   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5846          "Unexpected type in LowerBUILD_VECTORvXi1!");
5847
5848   SDLoc dl(Op);
5849   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5850     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5851     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5852                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5853     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5854                        Ops, VT.getVectorNumElements());
5855   }
5856
5857   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5858     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5859     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5860                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5861     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5862                        Ops, VT.getVectorNumElements());
5863   }
5864
5865   bool AllContants = true;
5866   uint64_t Immediate = 0;
5867   int NonConstIdx = -1;
5868   bool IsSplat = true;
5869   unsigned NumNonConsts = 0;
5870   unsigned NumConsts = 0;
5871   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5872     SDValue In = Op.getOperand(idx);
5873     if (In.getOpcode() == ISD::UNDEF)
5874       continue;
5875     if (!isa<ConstantSDNode>(In)) {
5876       AllContants = false;
5877       NonConstIdx = idx;
5878       NumNonConsts++;
5879     }
5880     else {
5881       NumConsts++;
5882       if (cast<ConstantSDNode>(In)->getZExtValue())
5883       Immediate |= (1ULL << idx);
5884     }
5885     if (In != Op.getOperand(0))
5886       IsSplat = false;
5887   }
5888
5889   if (AllContants) {
5890     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5891       DAG.getConstant(Immediate, MVT::i16));
5892     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5893                        DAG.getIntPtrConstant(0));
5894   }
5895
5896   if (NumNonConsts == 1 && NonConstIdx != 0) {
5897     SDValue DstVec;
5898     if (NumConsts) {
5899       SDValue VecAsImm = DAG.getConstant(Immediate,
5900                                          MVT::getIntegerVT(VT.getSizeInBits()));
5901       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5902     }
5903     else 
5904       DstVec = DAG.getUNDEF(VT);
5905     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5906                        Op.getOperand(NonConstIdx),
5907                        DAG.getIntPtrConstant(NonConstIdx));
5908   }
5909   if (!IsSplat && (NonConstIdx != 0))
5910     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5911   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5912   SDValue Select;
5913   if (IsSplat)
5914     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5915                           DAG.getConstant(-1, SelectVT),
5916                           DAG.getConstant(0, SelectVT));
5917   else
5918     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5919                          DAG.getConstant((Immediate | 1), SelectVT),
5920                          DAG.getConstant(Immediate, SelectVT));
5921   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5922 }
5923
5924 SDValue
5925 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5926   SDLoc dl(Op);
5927
5928   MVT VT = Op.getSimpleValueType();
5929   MVT ExtVT = VT.getVectorElementType();
5930   unsigned NumElems = Op.getNumOperands();
5931
5932   // Generate vectors for predicate vectors.
5933   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5934     return LowerBUILD_VECTORvXi1(Op, DAG);
5935
5936   // Vectors containing all zeros can be matched by pxor and xorps later
5937   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5938     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5939     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5940     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5941       return Op;
5942
5943     return getZeroVector(VT, Subtarget, DAG, dl);
5944   }
5945
5946   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5947   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5948   // vpcmpeqd on 256-bit vectors.
5949   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5950     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5951       return Op;
5952
5953     if (!VT.is512BitVector())
5954       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5955   }
5956
5957   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5958   if (Broadcast.getNode())
5959     return Broadcast;
5960
5961   unsigned EVTBits = ExtVT.getSizeInBits();
5962
5963   unsigned NumZero  = 0;
5964   unsigned NumNonZero = 0;
5965   unsigned NonZeros = 0;
5966   bool IsAllConstants = true;
5967   SmallSet<SDValue, 8> Values;
5968   for (unsigned i = 0; i < NumElems; ++i) {
5969     SDValue Elt = Op.getOperand(i);
5970     if (Elt.getOpcode() == ISD::UNDEF)
5971       continue;
5972     Values.insert(Elt);
5973     if (Elt.getOpcode() != ISD::Constant &&
5974         Elt.getOpcode() != ISD::ConstantFP)
5975       IsAllConstants = false;
5976     if (X86::isZeroNode(Elt))
5977       NumZero++;
5978     else {
5979       NonZeros |= (1 << i);
5980       NumNonZero++;
5981     }
5982   }
5983
5984   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5985   if (NumNonZero == 0)
5986     return DAG.getUNDEF(VT);
5987
5988   // Special case for single non-zero, non-undef, element.
5989   if (NumNonZero == 1) {
5990     unsigned Idx = countTrailingZeros(NonZeros);
5991     SDValue Item = Op.getOperand(Idx);
5992
5993     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5994     // the value are obviously zero, truncate the value to i32 and do the
5995     // insertion that way.  Only do this if the value is non-constant or if the
5996     // value is a constant being inserted into element 0.  It is cheaper to do
5997     // a constant pool load than it is to do a movd + shuffle.
5998     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5999         (!IsAllConstants || Idx == 0)) {
6000       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6001         // Handle SSE only.
6002         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6003         EVT VecVT = MVT::v4i32;
6004         unsigned VecElts = 4;
6005
6006         // Truncate the value (which may itself be a constant) to i32, and
6007         // convert it to a vector with movd (S2V+shuffle to zero extend).
6008         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6009         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6010         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6011
6012         // Now we have our 32-bit value zero extended in the low element of
6013         // a vector.  If Idx != 0, swizzle it into place.
6014         if (Idx != 0) {
6015           SmallVector<int, 4> Mask;
6016           Mask.push_back(Idx);
6017           for (unsigned i = 1; i != VecElts; ++i)
6018             Mask.push_back(i);
6019           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6020                                       &Mask[0]);
6021         }
6022         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6023       }
6024     }
6025
6026     // If we have a constant or non-constant insertion into the low element of
6027     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6028     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6029     // depending on what the source datatype is.
6030     if (Idx == 0) {
6031       if (NumZero == 0)
6032         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6033
6034       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6035           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6036         if (VT.is256BitVector() || VT.is512BitVector()) {
6037           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6038           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6039                              Item, DAG.getIntPtrConstant(0));
6040         }
6041         assert(VT.is128BitVector() && "Expected an SSE value type!");
6042         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6043         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6044         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6045       }
6046
6047       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6048         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6049         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6050         if (VT.is256BitVector()) {
6051           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6052           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6053         } else {
6054           assert(VT.is128BitVector() && "Expected an SSE value type!");
6055           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6056         }
6057         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6058       }
6059     }
6060
6061     // Is it a vector logical left shift?
6062     if (NumElems == 2 && Idx == 1 &&
6063         X86::isZeroNode(Op.getOperand(0)) &&
6064         !X86::isZeroNode(Op.getOperand(1))) {
6065       unsigned NumBits = VT.getSizeInBits();
6066       return getVShift(true, VT,
6067                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6068                                    VT, Op.getOperand(1)),
6069                        NumBits/2, DAG, *this, dl);
6070     }
6071
6072     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6073       return SDValue();
6074
6075     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6076     // is a non-constant being inserted into an element other than the low one,
6077     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6078     // movd/movss) to move this into the low element, then shuffle it into
6079     // place.
6080     if (EVTBits == 32) {
6081       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6082
6083       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6084       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6085       SmallVector<int, 8> MaskVec;
6086       for (unsigned i = 0; i != NumElems; ++i)
6087         MaskVec.push_back(i == Idx ? 0 : 1);
6088       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6089     }
6090   }
6091
6092   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6093   if (Values.size() == 1) {
6094     if (EVTBits == 32) {
6095       // Instead of a shuffle like this:
6096       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6097       // Check if it's possible to issue this instead.
6098       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6099       unsigned Idx = countTrailingZeros(NonZeros);
6100       SDValue Item = Op.getOperand(Idx);
6101       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6102         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6103     }
6104     return SDValue();
6105   }
6106
6107   // A vector full of immediates; various special cases are already
6108   // handled, so this is best done with a single constant-pool load.
6109   if (IsAllConstants)
6110     return SDValue();
6111
6112   // For AVX-length vectors, build the individual 128-bit pieces and use
6113   // shuffles to put them in place.
6114   if (VT.is256BitVector() || VT.is512BitVector()) {
6115     SmallVector<SDValue, 64> V;
6116     for (unsigned i = 0; i != NumElems; ++i)
6117       V.push_back(Op.getOperand(i));
6118
6119     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6120
6121     // Build both the lower and upper subvector.
6122     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6123     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6124                                 NumElems/2);
6125
6126     // Recreate the wider vector with the lower and upper part.
6127     if (VT.is256BitVector())
6128       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6129     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6130   }
6131
6132   // Let legalizer expand 2-wide build_vectors.
6133   if (EVTBits == 64) {
6134     if (NumNonZero == 1) {
6135       // One half is zero or undef.
6136       unsigned Idx = countTrailingZeros(NonZeros);
6137       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6138                                  Op.getOperand(Idx));
6139       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6140     }
6141     return SDValue();
6142   }
6143
6144   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6145   if (EVTBits == 8 && NumElems == 16) {
6146     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6147                                         Subtarget, *this);
6148     if (V.getNode()) return V;
6149   }
6150
6151   if (EVTBits == 16 && NumElems == 8) {
6152     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6153                                       Subtarget, *this);
6154     if (V.getNode()) return V;
6155   }
6156
6157   // If element VT is == 32 bits, turn it into a number of shuffles.
6158   SmallVector<SDValue, 8> V(NumElems);
6159   if (NumElems == 4 && NumZero > 0) {
6160     for (unsigned i = 0; i < 4; ++i) {
6161       bool isZero = !(NonZeros & (1 << i));
6162       if (isZero)
6163         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6164       else
6165         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6166     }
6167
6168     for (unsigned i = 0; i < 2; ++i) {
6169       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6170         default: break;
6171         case 0:
6172           V[i] = V[i*2];  // Must be a zero vector.
6173           break;
6174         case 1:
6175           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6176           break;
6177         case 2:
6178           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6179           break;
6180         case 3:
6181           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6182           break;
6183       }
6184     }
6185
6186     bool Reverse1 = (NonZeros & 0x3) == 2;
6187     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6188     int MaskVec[] = {
6189       Reverse1 ? 1 : 0,
6190       Reverse1 ? 0 : 1,
6191       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6192       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6193     };
6194     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6195   }
6196
6197   if (Values.size() > 1 && VT.is128BitVector()) {
6198     // Check for a build vector of consecutive loads.
6199     for (unsigned i = 0; i < NumElems; ++i)
6200       V[i] = Op.getOperand(i);
6201
6202     // Check for elements which are consecutive loads.
6203     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6204     if (LD.getNode())
6205       return LD;
6206
6207     // Check for a build vector from mostly shuffle plus few inserting.
6208     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6209     if (Sh.getNode())
6210       return Sh;
6211
6212     // For SSE 4.1, use insertps to put the high elements into the low element.
6213     if (getSubtarget()->hasSSE41()) {
6214       SDValue Result;
6215       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6216         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6217       else
6218         Result = DAG.getUNDEF(VT);
6219
6220       for (unsigned i = 1; i < NumElems; ++i) {
6221         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6222         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6223                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6224       }
6225       return Result;
6226     }
6227
6228     // Otherwise, expand into a number of unpckl*, start by extending each of
6229     // our (non-undef) elements to the full vector width with the element in the
6230     // bottom slot of the vector (which generates no code for SSE).
6231     for (unsigned i = 0; i < NumElems; ++i) {
6232       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6233         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6234       else
6235         V[i] = DAG.getUNDEF(VT);
6236     }
6237
6238     // Next, we iteratively mix elements, e.g. for v4f32:
6239     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6240     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6241     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6242     unsigned EltStride = NumElems >> 1;
6243     while (EltStride != 0) {
6244       for (unsigned i = 0; i < EltStride; ++i) {
6245         // If V[i+EltStride] is undef and this is the first round of mixing,
6246         // then it is safe to just drop this shuffle: V[i] is already in the
6247         // right place, the one element (since it's the first round) being
6248         // inserted as undef can be dropped.  This isn't safe for successive
6249         // rounds because they will permute elements within both vectors.
6250         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6251             EltStride == NumElems/2)
6252           continue;
6253
6254         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6255       }
6256       EltStride >>= 1;
6257     }
6258     return V[0];
6259   }
6260   return SDValue();
6261 }
6262
6263 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6264 // to create 256-bit vectors from two other 128-bit ones.
6265 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6266   SDLoc dl(Op);
6267   MVT ResVT = Op.getSimpleValueType();
6268
6269   assert((ResVT.is256BitVector() ||
6270           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6271
6272   SDValue V1 = Op.getOperand(0);
6273   SDValue V2 = Op.getOperand(1);
6274   unsigned NumElems = ResVT.getVectorNumElements();
6275   if(ResVT.is256BitVector())
6276     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6277
6278   if (Op.getNumOperands() == 4) {
6279     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6280                                 ResVT.getVectorNumElements()/2);
6281     SDValue V3 = Op.getOperand(2);
6282     SDValue V4 = Op.getOperand(3);
6283     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6284       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6285   }
6286   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6287 }
6288
6289 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6290   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6291   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6292          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6293           Op.getNumOperands() == 4)));
6294
6295   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6296   // from two other 128-bit ones.
6297
6298   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6299   return LowerAVXCONCAT_VECTORS(Op, DAG);
6300 }
6301
6302 // Try to lower a shuffle node into a simple blend instruction.
6303 static SDValue
6304 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6305                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6306   SDValue V1 = SVOp->getOperand(0);
6307   SDValue V2 = SVOp->getOperand(1);
6308   SDLoc dl(SVOp);
6309   MVT VT = SVOp->getSimpleValueType(0);
6310   MVT EltVT = VT.getVectorElementType();
6311   unsigned NumElems = VT.getVectorNumElements();
6312
6313   // There is no blend with immediate in AVX-512.
6314   if (VT.is512BitVector())
6315     return SDValue();
6316
6317   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6318     return SDValue();
6319   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6320     return SDValue();
6321
6322   // Check the mask for BLEND and build the value.
6323   unsigned MaskValue = 0;
6324   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6325   unsigned NumLanes = (NumElems-1)/8 + 1;
6326   unsigned NumElemsInLane = NumElems / NumLanes;
6327
6328   // Blend for v16i16 should be symetric for the both lanes.
6329   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6330
6331     int SndLaneEltIdx = (NumLanes == 2) ?
6332       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6333     int EltIdx = SVOp->getMaskElt(i);
6334
6335     if ((EltIdx < 0 || EltIdx == (int)i) &&
6336         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6337       continue;
6338
6339     if (((unsigned)EltIdx == (i + NumElems)) &&
6340         (SndLaneEltIdx < 0 ||
6341          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6342       MaskValue |= (1<<i);
6343     else
6344       return SDValue();
6345   }
6346
6347   // Convert i32 vectors to floating point if it is not AVX2.
6348   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6349   MVT BlendVT = VT;
6350   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6351     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6352                                NumElems);
6353     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6354     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6355   }
6356
6357   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6358                             DAG.getConstant(MaskValue, MVT::i32));
6359   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6360 }
6361
6362 /// In vector type \p VT, return true if the element at index \p InputIdx
6363 /// falls on a different 128-bit lane than \p OutputIdx.
6364 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6365                                      unsigned OutputIdx) {
6366   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6367   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6368 }
6369
6370 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6371 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6372 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6373 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6374 /// zero.
6375 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6376                          SelectionDAG &DAG) {
6377   MVT VT = V1.getSimpleValueType();
6378   assert(VT.is128BitVector() || VT.is256BitVector());
6379
6380   MVT EltVT = VT.getVectorElementType();
6381   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6382   unsigned NumElts = VT.getVectorNumElements();
6383
6384   SmallVector<SDValue, 32> PshufbMask;
6385   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6386     int InputIdx = MaskVals[OutputIdx];
6387     unsigned InputByteIdx;
6388
6389     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6390       InputByteIdx = 0x80;
6391     else {
6392       // Cross lane is not allowed.
6393       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6394         return SDValue();
6395       InputByteIdx = InputIdx * EltSizeInBytes;
6396       // Index is an byte offset within the 128-bit lane.
6397       InputByteIdx &= 0xf;
6398     }
6399
6400     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6401       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6402       if (InputByteIdx != 0x80)
6403         ++InputByteIdx;
6404     }
6405   }
6406
6407   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6408   if (ShufVT != VT)
6409     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6410   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6411                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6412                                  PshufbMask.data(), PshufbMask.size()));
6413 }
6414
6415 // v8i16 shuffles - Prefer shuffles in the following order:
6416 // 1. [all]   pshuflw, pshufhw, optional move
6417 // 2. [ssse3] 1 x pshufb
6418 // 3. [ssse3] 2 x pshufb + 1 x por
6419 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6420 static SDValue
6421 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6422                          SelectionDAG &DAG) {
6423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6424   SDValue V1 = SVOp->getOperand(0);
6425   SDValue V2 = SVOp->getOperand(1);
6426   SDLoc dl(SVOp);
6427   SmallVector<int, 8> MaskVals;
6428
6429   // Determine if more than 1 of the words in each of the low and high quadwords
6430   // of the result come from the same quadword of one of the two inputs.  Undef
6431   // mask values count as coming from any quadword, for better codegen.
6432   //
6433   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6434   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6435   unsigned LoQuad[] = { 0, 0, 0, 0 };
6436   unsigned HiQuad[] = { 0, 0, 0, 0 };
6437   // Indices of quads used.
6438   std::bitset<4> InputQuads;
6439   for (unsigned i = 0; i < 8; ++i) {
6440     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6441     int EltIdx = SVOp->getMaskElt(i);
6442     MaskVals.push_back(EltIdx);
6443     if (EltIdx < 0) {
6444       ++Quad[0];
6445       ++Quad[1];
6446       ++Quad[2];
6447       ++Quad[3];
6448       continue;
6449     }
6450     ++Quad[EltIdx / 4];
6451     InputQuads.set(EltIdx / 4);
6452   }
6453
6454   int BestLoQuad = -1;
6455   unsigned MaxQuad = 1;
6456   for (unsigned i = 0; i < 4; ++i) {
6457     if (LoQuad[i] > MaxQuad) {
6458       BestLoQuad = i;
6459       MaxQuad = LoQuad[i];
6460     }
6461   }
6462
6463   int BestHiQuad = -1;
6464   MaxQuad = 1;
6465   for (unsigned i = 0; i < 4; ++i) {
6466     if (HiQuad[i] > MaxQuad) {
6467       BestHiQuad = i;
6468       MaxQuad = HiQuad[i];
6469     }
6470   }
6471
6472   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6473   // of the two input vectors, shuffle them into one input vector so only a
6474   // single pshufb instruction is necessary. If there are more than 2 input
6475   // quads, disable the next transformation since it does not help SSSE3.
6476   bool V1Used = InputQuads[0] || InputQuads[1];
6477   bool V2Used = InputQuads[2] || InputQuads[3];
6478   if (Subtarget->hasSSSE3()) {
6479     if (InputQuads.count() == 2 && V1Used && V2Used) {
6480       BestLoQuad = InputQuads[0] ? 0 : 1;
6481       BestHiQuad = InputQuads[2] ? 2 : 3;
6482     }
6483     if (InputQuads.count() > 2) {
6484       BestLoQuad = -1;
6485       BestHiQuad = -1;
6486     }
6487   }
6488
6489   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6490   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6491   // words from all 4 input quadwords.
6492   SDValue NewV;
6493   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6494     int MaskV[] = {
6495       BestLoQuad < 0 ? 0 : BestLoQuad,
6496       BestHiQuad < 0 ? 1 : BestHiQuad
6497     };
6498     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6499                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6500                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6501     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6502
6503     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6504     // source words for the shuffle, to aid later transformations.
6505     bool AllWordsInNewV = true;
6506     bool InOrder[2] = { true, true };
6507     for (unsigned i = 0; i != 8; ++i) {
6508       int idx = MaskVals[i];
6509       if (idx != (int)i)
6510         InOrder[i/4] = false;
6511       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6512         continue;
6513       AllWordsInNewV = false;
6514       break;
6515     }
6516
6517     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6518     if (AllWordsInNewV) {
6519       for (int i = 0; i != 8; ++i) {
6520         int idx = MaskVals[i];
6521         if (idx < 0)
6522           continue;
6523         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6524         if ((idx != i) && idx < 4)
6525           pshufhw = false;
6526         if ((idx != i) && idx > 3)
6527           pshuflw = false;
6528       }
6529       V1 = NewV;
6530       V2Used = false;
6531       BestLoQuad = 0;
6532       BestHiQuad = 1;
6533     }
6534
6535     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6536     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6537     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6538       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6539       unsigned TargetMask = 0;
6540       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6541                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6542       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6543       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6544                              getShufflePSHUFLWImmediate(SVOp);
6545       V1 = NewV.getOperand(0);
6546       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6547     }
6548   }
6549
6550   // Promote splats to a larger type which usually leads to more efficient code.
6551   // FIXME: Is this true if pshufb is available?
6552   if (SVOp->isSplat())
6553     return PromoteSplat(SVOp, DAG);
6554
6555   // If we have SSSE3, and all words of the result are from 1 input vector,
6556   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6557   // is present, fall back to case 4.
6558   if (Subtarget->hasSSSE3()) {
6559     SmallVector<SDValue,16> pshufbMask;
6560
6561     // If we have elements from both input vectors, set the high bit of the
6562     // shuffle mask element to zero out elements that come from V2 in the V1
6563     // mask, and elements that come from V1 in the V2 mask, so that the two
6564     // results can be OR'd together.
6565     bool TwoInputs = V1Used && V2Used;
6566     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6567     if (!TwoInputs)
6568       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6569
6570     // Calculate the shuffle mask for the second input, shuffle it, and
6571     // OR it with the first shuffled input.
6572     CommuteVectorShuffleMask(MaskVals, 8);
6573     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6574     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6575     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6576   }
6577
6578   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6579   // and update MaskVals with new element order.
6580   std::bitset<8> InOrder;
6581   if (BestLoQuad >= 0) {
6582     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6583     for (int i = 0; i != 4; ++i) {
6584       int idx = MaskVals[i];
6585       if (idx < 0) {
6586         InOrder.set(i);
6587       } else if ((idx / 4) == BestLoQuad) {
6588         MaskV[i] = idx & 3;
6589         InOrder.set(i);
6590       }
6591     }
6592     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6593                                 &MaskV[0]);
6594
6595     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6596       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6597       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6598                                   NewV.getOperand(0),
6599                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6600     }
6601   }
6602
6603   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6604   // and update MaskVals with the new element order.
6605   if (BestHiQuad >= 0) {
6606     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6607     for (unsigned i = 4; i != 8; ++i) {
6608       int idx = MaskVals[i];
6609       if (idx < 0) {
6610         InOrder.set(i);
6611       } else if ((idx / 4) == BestHiQuad) {
6612         MaskV[i] = (idx & 3) + 4;
6613         InOrder.set(i);
6614       }
6615     }
6616     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6617                                 &MaskV[0]);
6618
6619     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6620       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6621       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6622                                   NewV.getOperand(0),
6623                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6624     }
6625   }
6626
6627   // In case BestHi & BestLo were both -1, which means each quadword has a word
6628   // from each of the four input quadwords, calculate the InOrder bitvector now
6629   // before falling through to the insert/extract cleanup.
6630   if (BestLoQuad == -1 && BestHiQuad == -1) {
6631     NewV = V1;
6632     for (int i = 0; i != 8; ++i)
6633       if (MaskVals[i] < 0 || MaskVals[i] == i)
6634         InOrder.set(i);
6635   }
6636
6637   // The other elements are put in the right place using pextrw and pinsrw.
6638   for (unsigned i = 0; i != 8; ++i) {
6639     if (InOrder[i])
6640       continue;
6641     int EltIdx = MaskVals[i];
6642     if (EltIdx < 0)
6643       continue;
6644     SDValue ExtOp = (EltIdx < 8) ?
6645       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6646                   DAG.getIntPtrConstant(EltIdx)) :
6647       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6648                   DAG.getIntPtrConstant(EltIdx - 8));
6649     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6650                        DAG.getIntPtrConstant(i));
6651   }
6652   return NewV;
6653 }
6654
6655 /// \brief v16i16 shuffles
6656 ///
6657 /// FIXME: We only support generation of a single pshufb currently.  We can
6658 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6659 /// well (e.g 2 x pshufb + 1 x por).
6660 static SDValue
6661 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6663   SDValue V1 = SVOp->getOperand(0);
6664   SDValue V2 = SVOp->getOperand(1);
6665   SDLoc dl(SVOp);
6666
6667   if (V2.getOpcode() != ISD::UNDEF)
6668     return SDValue();
6669
6670   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6671   return getPSHUFB(MaskVals, V1, dl, DAG);
6672 }
6673
6674 // v16i8 shuffles - Prefer shuffles in the following order:
6675 // 1. [ssse3] 1 x pshufb
6676 // 2. [ssse3] 2 x pshufb + 1 x por
6677 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6678 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6679                                         const X86Subtarget* Subtarget,
6680                                         SelectionDAG &DAG) {
6681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6682   SDValue V1 = SVOp->getOperand(0);
6683   SDValue V2 = SVOp->getOperand(1);
6684   SDLoc dl(SVOp);
6685   ArrayRef<int> MaskVals = SVOp->getMask();
6686
6687   // Promote splats to a larger type which usually leads to more efficient code.
6688   // FIXME: Is this true if pshufb is available?
6689   if (SVOp->isSplat())
6690     return PromoteSplat(SVOp, DAG);
6691
6692   // If we have SSSE3, case 1 is generated when all result bytes come from
6693   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6694   // present, fall back to case 3.
6695
6696   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6697   if (Subtarget->hasSSSE3()) {
6698     SmallVector<SDValue,16> pshufbMask;
6699
6700     // If all result elements are from one input vector, then only translate
6701     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6702     //
6703     // Otherwise, we have elements from both input vectors, and must zero out
6704     // elements that come from V2 in the first mask, and V1 in the second mask
6705     // so that we can OR them together.
6706     for (unsigned i = 0; i != 16; ++i) {
6707       int EltIdx = MaskVals[i];
6708       if (EltIdx < 0 || EltIdx >= 16)
6709         EltIdx = 0x80;
6710       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6711     }
6712     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6713                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6714                                  MVT::v16i8, &pshufbMask[0], 16));
6715
6716     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6717     // the 2nd operand if it's undefined or zero.
6718     if (V2.getOpcode() == ISD::UNDEF ||
6719         ISD::isBuildVectorAllZeros(V2.getNode()))
6720       return V1;
6721
6722     // Calculate the shuffle mask for the second input, shuffle it, and
6723     // OR it with the first shuffled input.
6724     pshufbMask.clear();
6725     for (unsigned i = 0; i != 16; ++i) {
6726       int EltIdx = MaskVals[i];
6727       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6728       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6729     }
6730     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6731                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6732                                  MVT::v16i8, &pshufbMask[0], 16));
6733     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6734   }
6735
6736   // No SSSE3 - Calculate in place words and then fix all out of place words
6737   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6738   // the 16 different words that comprise the two doublequadword input vectors.
6739   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6740   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6741   SDValue NewV = V1;
6742   for (int i = 0; i != 8; ++i) {
6743     int Elt0 = MaskVals[i*2];
6744     int Elt1 = MaskVals[i*2+1];
6745
6746     // This word of the result is all undef, skip it.
6747     if (Elt0 < 0 && Elt1 < 0)
6748       continue;
6749
6750     // This word of the result is already in the correct place, skip it.
6751     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6752       continue;
6753
6754     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6755     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6756     SDValue InsElt;
6757
6758     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6759     // using a single extract together, load it and store it.
6760     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6761       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6762                            DAG.getIntPtrConstant(Elt1 / 2));
6763       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6764                         DAG.getIntPtrConstant(i));
6765       continue;
6766     }
6767
6768     // If Elt1 is defined, extract it from the appropriate source.  If the
6769     // source byte is not also odd, shift the extracted word left 8 bits
6770     // otherwise clear the bottom 8 bits if we need to do an or.
6771     if (Elt1 >= 0) {
6772       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6773                            DAG.getIntPtrConstant(Elt1 / 2));
6774       if ((Elt1 & 1) == 0)
6775         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6776                              DAG.getConstant(8,
6777                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6778       else if (Elt0 >= 0)
6779         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6780                              DAG.getConstant(0xFF00, MVT::i16));
6781     }
6782     // If Elt0 is defined, extract it from the appropriate source.  If the
6783     // source byte is not also even, shift the extracted word right 8 bits. If
6784     // Elt1 was also defined, OR the extracted values together before
6785     // inserting them in the result.
6786     if (Elt0 >= 0) {
6787       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6788                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6789       if ((Elt0 & 1) != 0)
6790         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6791                               DAG.getConstant(8,
6792                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6793       else if (Elt1 >= 0)
6794         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6795                              DAG.getConstant(0x00FF, MVT::i16));
6796       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6797                          : InsElt0;
6798     }
6799     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6800                        DAG.getIntPtrConstant(i));
6801   }
6802   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6803 }
6804
6805 // v32i8 shuffles - Translate to VPSHUFB if possible.
6806 static
6807 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6808                                  const X86Subtarget *Subtarget,
6809                                  SelectionDAG &DAG) {
6810   MVT VT = SVOp->getSimpleValueType(0);
6811   SDValue V1 = SVOp->getOperand(0);
6812   SDValue V2 = SVOp->getOperand(1);
6813   SDLoc dl(SVOp);
6814   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6815
6816   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6817   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6818   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6819
6820   // VPSHUFB may be generated if
6821   // (1) one of input vector is undefined or zeroinitializer.
6822   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6823   // And (2) the mask indexes don't cross the 128-bit lane.
6824   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6825       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6826     return SDValue();
6827
6828   if (V1IsAllZero && !V2IsAllZero) {
6829     CommuteVectorShuffleMask(MaskVals, 32);
6830     V1 = V2;
6831   }
6832   return getPSHUFB(MaskVals, V1, dl, DAG);
6833 }
6834
6835 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6836 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6837 /// done when every pair / quad of shuffle mask elements point to elements in
6838 /// the right sequence. e.g.
6839 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6840 static
6841 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6842                                  SelectionDAG &DAG) {
6843   MVT VT = SVOp->getSimpleValueType(0);
6844   SDLoc dl(SVOp);
6845   unsigned NumElems = VT.getVectorNumElements();
6846   MVT NewVT;
6847   unsigned Scale;
6848   switch (VT.SimpleTy) {
6849   default: llvm_unreachable("Unexpected!");
6850   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6851   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6852   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6853   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6854   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6855   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6856   }
6857
6858   SmallVector<int, 8> MaskVec;
6859   for (unsigned i = 0; i != NumElems; i += Scale) {
6860     int StartIdx = -1;
6861     for (unsigned j = 0; j != Scale; ++j) {
6862       int EltIdx = SVOp->getMaskElt(i+j);
6863       if (EltIdx < 0)
6864         continue;
6865       if (StartIdx < 0)
6866         StartIdx = (EltIdx / Scale);
6867       if (EltIdx != (int)(StartIdx*Scale + j))
6868         return SDValue();
6869     }
6870     MaskVec.push_back(StartIdx);
6871   }
6872
6873   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6874   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6875   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6876 }
6877
6878 /// getVZextMovL - Return a zero-extending vector move low node.
6879 ///
6880 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6881                             SDValue SrcOp, SelectionDAG &DAG,
6882                             const X86Subtarget *Subtarget, SDLoc dl) {
6883   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6884     LoadSDNode *LD = nullptr;
6885     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6886       LD = dyn_cast<LoadSDNode>(SrcOp);
6887     if (!LD) {
6888       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6889       // instead.
6890       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6891       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6892           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6893           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6894           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6895         // PR2108
6896         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6897         return DAG.getNode(ISD::BITCAST, dl, VT,
6898                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6899                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6900                                                    OpVT,
6901                                                    SrcOp.getOperand(0)
6902                                                           .getOperand(0))));
6903       }
6904     }
6905   }
6906
6907   return DAG.getNode(ISD::BITCAST, dl, VT,
6908                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6909                                  DAG.getNode(ISD::BITCAST, dl,
6910                                              OpVT, SrcOp)));
6911 }
6912
6913 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6914 /// which could not be matched by any known target speficic shuffle
6915 static SDValue
6916 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6917
6918   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6919   if (NewOp.getNode())
6920     return NewOp;
6921
6922   MVT VT = SVOp->getSimpleValueType(0);
6923
6924   unsigned NumElems = VT.getVectorNumElements();
6925   unsigned NumLaneElems = NumElems / 2;
6926
6927   SDLoc dl(SVOp);
6928   MVT EltVT = VT.getVectorElementType();
6929   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6930   SDValue Output[2];
6931
6932   SmallVector<int, 16> Mask;
6933   for (unsigned l = 0; l < 2; ++l) {
6934     // Build a shuffle mask for the output, discovering on the fly which
6935     // input vectors to use as shuffle operands (recorded in InputUsed).
6936     // If building a suitable shuffle vector proves too hard, then bail
6937     // out with UseBuildVector set.
6938     bool UseBuildVector = false;
6939     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6940     unsigned LaneStart = l * NumLaneElems;
6941     for (unsigned i = 0; i != NumLaneElems; ++i) {
6942       // The mask element.  This indexes into the input.
6943       int Idx = SVOp->getMaskElt(i+LaneStart);
6944       if (Idx < 0) {
6945         // the mask element does not index into any input vector.
6946         Mask.push_back(-1);
6947         continue;
6948       }
6949
6950       // The input vector this mask element indexes into.
6951       int Input = Idx / NumLaneElems;
6952
6953       // Turn the index into an offset from the start of the input vector.
6954       Idx -= Input * NumLaneElems;
6955
6956       // Find or create a shuffle vector operand to hold this input.
6957       unsigned OpNo;
6958       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6959         if (InputUsed[OpNo] == Input)
6960           // This input vector is already an operand.
6961           break;
6962         if (InputUsed[OpNo] < 0) {
6963           // Create a new operand for this input vector.
6964           InputUsed[OpNo] = Input;
6965           break;
6966         }
6967       }
6968
6969       if (OpNo >= array_lengthof(InputUsed)) {
6970         // More than two input vectors used!  Give up on trying to create a
6971         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6972         UseBuildVector = true;
6973         break;
6974       }
6975
6976       // Add the mask index for the new shuffle vector.
6977       Mask.push_back(Idx + OpNo * NumLaneElems);
6978     }
6979
6980     if (UseBuildVector) {
6981       SmallVector<SDValue, 16> SVOps;
6982       for (unsigned i = 0; i != NumLaneElems; ++i) {
6983         // The mask element.  This indexes into the input.
6984         int Idx = SVOp->getMaskElt(i+LaneStart);
6985         if (Idx < 0) {
6986           SVOps.push_back(DAG.getUNDEF(EltVT));
6987           continue;
6988         }
6989
6990         // The input vector this mask element indexes into.
6991         int Input = Idx / NumElems;
6992
6993         // Turn the index into an offset from the start of the input vector.
6994         Idx -= Input * NumElems;
6995
6996         // Extract the vector element by hand.
6997         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6998                                     SVOp->getOperand(Input),
6999                                     DAG.getIntPtrConstant(Idx)));
7000       }
7001
7002       // Construct the output using a BUILD_VECTOR.
7003       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
7004                               SVOps.size());
7005     } else if (InputUsed[0] < 0) {
7006       // No input vectors were used! The result is undefined.
7007       Output[l] = DAG.getUNDEF(NVT);
7008     } else {
7009       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7010                                         (InputUsed[0] % 2) * NumLaneElems,
7011                                         DAG, dl);
7012       // If only one input was used, use an undefined vector for the other.
7013       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7014         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7015                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7016       // At least one input vector was used. Create a new shuffle vector.
7017       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7018     }
7019
7020     Mask.clear();
7021   }
7022
7023   // Concatenate the result back
7024   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7025 }
7026
7027 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7028 /// 4 elements, and match them with several different shuffle types.
7029 static SDValue
7030 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7031   SDValue V1 = SVOp->getOperand(0);
7032   SDValue V2 = SVOp->getOperand(1);
7033   SDLoc dl(SVOp);
7034   MVT VT = SVOp->getSimpleValueType(0);
7035
7036   assert(VT.is128BitVector() && "Unsupported vector size");
7037
7038   std::pair<int, int> Locs[4];
7039   int Mask1[] = { -1, -1, -1, -1 };
7040   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7041
7042   unsigned NumHi = 0;
7043   unsigned NumLo = 0;
7044   for (unsigned i = 0; i != 4; ++i) {
7045     int Idx = PermMask[i];
7046     if (Idx < 0) {
7047       Locs[i] = std::make_pair(-1, -1);
7048     } else {
7049       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7050       if (Idx < 4) {
7051         Locs[i] = std::make_pair(0, NumLo);
7052         Mask1[NumLo] = Idx;
7053         NumLo++;
7054       } else {
7055         Locs[i] = std::make_pair(1, NumHi);
7056         if (2+NumHi < 4)
7057           Mask1[2+NumHi] = Idx;
7058         NumHi++;
7059       }
7060     }
7061   }
7062
7063   if (NumLo <= 2 && NumHi <= 2) {
7064     // If no more than two elements come from either vector. This can be
7065     // implemented with two shuffles. First shuffle gather the elements.
7066     // The second shuffle, which takes the first shuffle as both of its
7067     // vector operands, put the elements into the right order.
7068     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7069
7070     int Mask2[] = { -1, -1, -1, -1 };
7071
7072     for (unsigned i = 0; i != 4; ++i)
7073       if (Locs[i].first != -1) {
7074         unsigned Idx = (i < 2) ? 0 : 4;
7075         Idx += Locs[i].first * 2 + Locs[i].second;
7076         Mask2[i] = Idx;
7077       }
7078
7079     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7080   }
7081
7082   if (NumLo == 3 || NumHi == 3) {
7083     // Otherwise, we must have three elements from one vector, call it X, and
7084     // one element from the other, call it Y.  First, use a shufps to build an
7085     // intermediate vector with the one element from Y and the element from X
7086     // that will be in the same half in the final destination (the indexes don't
7087     // matter). Then, use a shufps to build the final vector, taking the half
7088     // containing the element from Y from the intermediate, and the other half
7089     // from X.
7090     if (NumHi == 3) {
7091       // Normalize it so the 3 elements come from V1.
7092       CommuteVectorShuffleMask(PermMask, 4);
7093       std::swap(V1, V2);
7094     }
7095
7096     // Find the element from V2.
7097     unsigned HiIndex;
7098     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7099       int Val = PermMask[HiIndex];
7100       if (Val < 0)
7101         continue;
7102       if (Val >= 4)
7103         break;
7104     }
7105
7106     Mask1[0] = PermMask[HiIndex];
7107     Mask1[1] = -1;
7108     Mask1[2] = PermMask[HiIndex^1];
7109     Mask1[3] = -1;
7110     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7111
7112     if (HiIndex >= 2) {
7113       Mask1[0] = PermMask[0];
7114       Mask1[1] = PermMask[1];
7115       Mask1[2] = HiIndex & 1 ? 6 : 4;
7116       Mask1[3] = HiIndex & 1 ? 4 : 6;
7117       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7118     }
7119
7120     Mask1[0] = HiIndex & 1 ? 2 : 0;
7121     Mask1[1] = HiIndex & 1 ? 0 : 2;
7122     Mask1[2] = PermMask[2];
7123     Mask1[3] = PermMask[3];
7124     if (Mask1[2] >= 0)
7125       Mask1[2] += 4;
7126     if (Mask1[3] >= 0)
7127       Mask1[3] += 4;
7128     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7129   }
7130
7131   // Break it into (shuffle shuffle_hi, shuffle_lo).
7132   int LoMask[] = { -1, -1, -1, -1 };
7133   int HiMask[] = { -1, -1, -1, -1 };
7134
7135   int *MaskPtr = LoMask;
7136   unsigned MaskIdx = 0;
7137   unsigned LoIdx = 0;
7138   unsigned HiIdx = 2;
7139   for (unsigned i = 0; i != 4; ++i) {
7140     if (i == 2) {
7141       MaskPtr = HiMask;
7142       MaskIdx = 1;
7143       LoIdx = 0;
7144       HiIdx = 2;
7145     }
7146     int Idx = PermMask[i];
7147     if (Idx < 0) {
7148       Locs[i] = std::make_pair(-1, -1);
7149     } else if (Idx < 4) {
7150       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7151       MaskPtr[LoIdx] = Idx;
7152       LoIdx++;
7153     } else {
7154       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7155       MaskPtr[HiIdx] = Idx;
7156       HiIdx++;
7157     }
7158   }
7159
7160   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7161   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7162   int MaskOps[] = { -1, -1, -1, -1 };
7163   for (unsigned i = 0; i != 4; ++i)
7164     if (Locs[i].first != -1)
7165       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7166   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7167 }
7168
7169 static bool MayFoldVectorLoad(SDValue V) {
7170   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7171     V = V.getOperand(0);
7172
7173   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7174     V = V.getOperand(0);
7175   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7176       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7177     // BUILD_VECTOR (load), undef
7178     V = V.getOperand(0);
7179
7180   return MayFoldLoad(V);
7181 }
7182
7183 static
7184 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7185   MVT VT = Op.getSimpleValueType();
7186
7187   // Canonizalize to v2f64.
7188   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7189   return DAG.getNode(ISD::BITCAST, dl, VT,
7190                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7191                                           V1, DAG));
7192 }
7193
7194 static
7195 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7196                         bool HasSSE2) {
7197   SDValue V1 = Op.getOperand(0);
7198   SDValue V2 = Op.getOperand(1);
7199   MVT VT = Op.getSimpleValueType();
7200
7201   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7202
7203   if (HasSSE2 && VT == MVT::v2f64)
7204     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7205
7206   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7207   return DAG.getNode(ISD::BITCAST, dl, VT,
7208                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7209                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7210                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7211 }
7212
7213 static
7214 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7215   SDValue V1 = Op.getOperand(0);
7216   SDValue V2 = Op.getOperand(1);
7217   MVT VT = Op.getSimpleValueType();
7218
7219   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7220          "unsupported shuffle type");
7221
7222   if (V2.getOpcode() == ISD::UNDEF)
7223     V2 = V1;
7224
7225   // v4i32 or v4f32
7226   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7227 }
7228
7229 static
7230 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7231   SDValue V1 = Op.getOperand(0);
7232   SDValue V2 = Op.getOperand(1);
7233   MVT VT = Op.getSimpleValueType();
7234   unsigned NumElems = VT.getVectorNumElements();
7235
7236   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7237   // operand of these instructions is only memory, so check if there's a
7238   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7239   // same masks.
7240   bool CanFoldLoad = false;
7241
7242   // Trivial case, when V2 comes from a load.
7243   if (MayFoldVectorLoad(V2))
7244     CanFoldLoad = true;
7245
7246   // When V1 is a load, it can be folded later into a store in isel, example:
7247   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7248   //    turns into:
7249   //  (MOVLPSmr addr:$src1, VR128:$src2)
7250   // So, recognize this potential and also use MOVLPS or MOVLPD
7251   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7252     CanFoldLoad = true;
7253
7254   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7255   if (CanFoldLoad) {
7256     if (HasSSE2 && NumElems == 2)
7257       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7258
7259     if (NumElems == 4)
7260       // If we don't care about the second element, proceed to use movss.
7261       if (SVOp->getMaskElt(1) != -1)
7262         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7263   }
7264
7265   // movl and movlp will both match v2i64, but v2i64 is never matched by
7266   // movl earlier because we make it strict to avoid messing with the movlp load
7267   // folding logic (see the code above getMOVLP call). Match it here then,
7268   // this is horrible, but will stay like this until we move all shuffle
7269   // matching to x86 specific nodes. Note that for the 1st condition all
7270   // types are matched with movsd.
7271   if (HasSSE2) {
7272     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7273     // as to remove this logic from here, as much as possible
7274     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7275       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7276     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7277   }
7278
7279   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7280
7281   // Invert the operand order and use SHUFPS to match it.
7282   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7283                               getShuffleSHUFImmediate(SVOp), DAG);
7284 }
7285
7286 // It is only safe to call this function if isINSERTPSMask is true for
7287 // this shufflevector mask.
7288 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7289                            SelectionDAG &DAG) {
7290   // Generate an insertps instruction when inserting an f32 from memory onto a
7291   // v4f32 or when copying a member from one v4f32 to another.
7292   // We also use it for transferring i32 from one register to another,
7293   // since it simply copies the same bits.
7294   // If we're transfering an i32 from memory to a specific element in a
7295   // register, we output a generic DAG that will match the PINSRD
7296   // instruction.
7297   // TODO: Optimize for AVX cases too (VINSERTPS)
7298   MVT VT = SVOp->getSimpleValueType(0);
7299   MVT EVT = VT.getVectorElementType();
7300   SDValue V1 = SVOp->getOperand(0);
7301   SDValue V2 = SVOp->getOperand(1);
7302   auto Mask = SVOp->getMask();
7303   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7304          "unsupported vector type for insertps/pinsrd");
7305
7306   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7307                              [](const int &i) { return i < 4; });
7308
7309   SDValue From;
7310   SDValue To;
7311   unsigned DestIndex;
7312   if (FromV1 == 1) {
7313     From = V1;
7314     To = V2;
7315     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7316                              [](const int &i) { return i < 4; }) -
7317                 Mask.begin();
7318   } else {
7319     From = V2;
7320     To = V1;
7321     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7322                              [](const int &i) { return i >= 4; }) -
7323                 Mask.begin();
7324   }
7325
7326   if (MayFoldLoad(From)) {
7327     // Trivial case, when From comes from a load and is only used by the
7328     // shuffle. Make it use insertps from the vector that we need from that
7329     // load.
7330     SDValue Addr = From.getOperand(1);
7331     SDValue NewAddr =
7332         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7333                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7334                                     Addr.getSimpleValueType()));
7335
7336     LoadSDNode *Load = cast<LoadSDNode>(From);
7337     SDValue NewLoad =
7338         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7339                     DAG.getMachineFunction().getMachineMemOperand(
7340                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7341
7342     if (EVT == MVT::f32) {
7343       // Create this as a scalar to vector to match the instruction pattern.
7344       SDValue LoadScalarToVector =
7345           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7346       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7347       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7348                          InsertpsMask);
7349     } else { // EVT == MVT::i32
7350       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7351       // instruction, to match the PINSRD instruction, which loads an i32 to a
7352       // certain vector element.
7353       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7354                          DAG.getConstant(DestIndex, MVT::i32));
7355     }
7356   }
7357
7358   // Vector-element-to-vector
7359   unsigned SrcIndex = Mask[DestIndex] % 4;
7360   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7361   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7362 }
7363
7364 // Reduce a vector shuffle to zext.
7365 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7366                                     SelectionDAG &DAG) {
7367   // PMOVZX is only available from SSE41.
7368   if (!Subtarget->hasSSE41())
7369     return SDValue();
7370
7371   MVT VT = Op.getSimpleValueType();
7372
7373   // Only AVX2 support 256-bit vector integer extending.
7374   if (!Subtarget->hasInt256() && VT.is256BitVector())
7375     return SDValue();
7376
7377   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7378   SDLoc DL(Op);
7379   SDValue V1 = Op.getOperand(0);
7380   SDValue V2 = Op.getOperand(1);
7381   unsigned NumElems = VT.getVectorNumElements();
7382
7383   // Extending is an unary operation and the element type of the source vector
7384   // won't be equal to or larger than i64.
7385   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7386       VT.getVectorElementType() == MVT::i64)
7387     return SDValue();
7388
7389   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7390   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7391   while ((1U << Shift) < NumElems) {
7392     if (SVOp->getMaskElt(1U << Shift) == 1)
7393       break;
7394     Shift += 1;
7395     // The maximal ratio is 8, i.e. from i8 to i64.
7396     if (Shift > 3)
7397       return SDValue();
7398   }
7399
7400   // Check the shuffle mask.
7401   unsigned Mask = (1U << Shift) - 1;
7402   for (unsigned i = 0; i != NumElems; ++i) {
7403     int EltIdx = SVOp->getMaskElt(i);
7404     if ((i & Mask) != 0 && EltIdx != -1)
7405       return SDValue();
7406     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7407       return SDValue();
7408   }
7409
7410   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7411   MVT NeVT = MVT::getIntegerVT(NBits);
7412   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7413
7414   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7415     return SDValue();
7416
7417   // Simplify the operand as it's prepared to be fed into shuffle.
7418   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7419   if (V1.getOpcode() == ISD::BITCAST &&
7420       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7421       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7422       V1.getOperand(0).getOperand(0)
7423         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7424     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7425     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7426     ConstantSDNode *CIdx =
7427       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7428     // If it's foldable, i.e. normal load with single use, we will let code
7429     // selection to fold it. Otherwise, we will short the conversion sequence.
7430     if (CIdx && CIdx->getZExtValue() == 0 &&
7431         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7432       MVT FullVT = V.getSimpleValueType();
7433       MVT V1VT = V1.getSimpleValueType();
7434       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7435         // The "ext_vec_elt" node is wider than the result node.
7436         // In this case we should extract subvector from V.
7437         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7438         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7439         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7440                                         FullVT.getVectorNumElements()/Ratio);
7441         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7442                         DAG.getIntPtrConstant(0));
7443       }
7444       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7445     }
7446   }
7447
7448   return DAG.getNode(ISD::BITCAST, DL, VT,
7449                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7450 }
7451
7452 static SDValue
7453 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7454                        SelectionDAG &DAG) {
7455   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7456   MVT VT = Op.getSimpleValueType();
7457   SDLoc dl(Op);
7458   SDValue V1 = Op.getOperand(0);
7459   SDValue V2 = Op.getOperand(1);
7460
7461   if (isZeroShuffle(SVOp))
7462     return getZeroVector(VT, Subtarget, DAG, dl);
7463
7464   // Handle splat operations
7465   if (SVOp->isSplat()) {
7466     // Use vbroadcast whenever the splat comes from a foldable load
7467     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7468     if (Broadcast.getNode())
7469       return Broadcast;
7470   }
7471
7472   // Check integer expanding shuffles.
7473   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7474   if (NewOp.getNode())
7475     return NewOp;
7476
7477   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7478   // do it!
7479   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7480       VT == MVT::v16i16 || VT == MVT::v32i8) {
7481     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7482     if (NewOp.getNode())
7483       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7484   } else if ((VT == MVT::v4i32 ||
7485              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7486     // FIXME: Figure out a cleaner way to do this.
7487     // Try to make use of movq to zero out the top part.
7488     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7489       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7490       if (NewOp.getNode()) {
7491         MVT NewVT = NewOp.getSimpleValueType();
7492         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7493                                NewVT, true, false))
7494           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7495                               DAG, Subtarget, dl);
7496       }
7497     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7498       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7499       if (NewOp.getNode()) {
7500         MVT NewVT = NewOp.getSimpleValueType();
7501         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7502           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7503                               DAG, Subtarget, dl);
7504       }
7505     }
7506   }
7507   return SDValue();
7508 }
7509
7510 SDValue
7511 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7512   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7513   SDValue V1 = Op.getOperand(0);
7514   SDValue V2 = Op.getOperand(1);
7515   MVT VT = Op.getSimpleValueType();
7516   SDLoc dl(Op);
7517   unsigned NumElems = VT.getVectorNumElements();
7518   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7519   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7520   bool V1IsSplat = false;
7521   bool V2IsSplat = false;
7522   bool HasSSE2 = Subtarget->hasSSE2();
7523   bool HasFp256    = Subtarget->hasFp256();
7524   bool HasInt256   = Subtarget->hasInt256();
7525   MachineFunction &MF = DAG.getMachineFunction();
7526   bool OptForSize = MF.getFunction()->getAttributes().
7527     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7528
7529   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7530
7531   if (V1IsUndef && V2IsUndef)
7532     return DAG.getUNDEF(VT);
7533
7534   // When we create a shuffle node we put the UNDEF node to second operand,
7535   // but in some cases the first operand may be transformed to UNDEF.
7536   // In this case we should just commute the node.
7537   if (V1IsUndef)
7538     return CommuteVectorShuffle(SVOp, DAG);
7539
7540   // Vector shuffle lowering takes 3 steps:
7541   //
7542   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7543   //    narrowing and commutation of operands should be handled.
7544   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7545   //    shuffle nodes.
7546   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7547   //    so the shuffle can be broken into other shuffles and the legalizer can
7548   //    try the lowering again.
7549   //
7550   // The general idea is that no vector_shuffle operation should be left to
7551   // be matched during isel, all of them must be converted to a target specific
7552   // node here.
7553
7554   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7555   // narrowing and commutation of operands should be handled. The actual code
7556   // doesn't include all of those, work in progress...
7557   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7558   if (NewOp.getNode())
7559     return NewOp;
7560
7561   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7562
7563   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7564   // unpckh_undef). Only use pshufd if speed is more important than size.
7565   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7566     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7567   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7568     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7569
7570   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7571       V2IsUndef && MayFoldVectorLoad(V1))
7572     return getMOVDDup(Op, dl, V1, DAG);
7573
7574   if (isMOVHLPS_v_undef_Mask(M, VT))
7575     return getMOVHighToLow(Op, dl, DAG);
7576
7577   // Use to match splats
7578   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7579       (VT == MVT::v2f64 || VT == MVT::v2i64))
7580     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7581
7582   if (isPSHUFDMask(M, VT)) {
7583     // The actual implementation will match the mask in the if above and then
7584     // during isel it can match several different instructions, not only pshufd
7585     // as its name says, sad but true, emulate the behavior for now...
7586     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7587       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7588
7589     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7590
7591     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7592       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7593
7594     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7595       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7596                                   DAG);
7597
7598     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7599                                 TargetMask, DAG);
7600   }
7601
7602   if (isPALIGNRMask(M, VT, Subtarget))
7603     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7604                                 getShufflePALIGNRImmediate(SVOp),
7605                                 DAG);
7606
7607   // Check if this can be converted into a logical shift.
7608   bool isLeft = false;
7609   unsigned ShAmt = 0;
7610   SDValue ShVal;
7611   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7612   if (isShift && ShVal.hasOneUse()) {
7613     // If the shifted value has multiple uses, it may be cheaper to use
7614     // v_set0 + movlhps or movhlps, etc.
7615     MVT EltVT = VT.getVectorElementType();
7616     ShAmt *= EltVT.getSizeInBits();
7617     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7618   }
7619
7620   if (isMOVLMask(M, VT)) {
7621     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7622       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7623     if (!isMOVLPMask(M, VT)) {
7624       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7625         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7626
7627       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7628         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7629     }
7630   }
7631
7632   // FIXME: fold these into legal mask.
7633   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7634     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7635
7636   if (isMOVHLPSMask(M, VT))
7637     return getMOVHighToLow(Op, dl, DAG);
7638
7639   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7640     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7641
7642   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7643     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7644
7645   if (isMOVLPMask(M, VT))
7646     return getMOVLP(Op, dl, DAG, HasSSE2);
7647
7648   if (ShouldXformToMOVHLPS(M, VT) ||
7649       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7650     return CommuteVectorShuffle(SVOp, DAG);
7651
7652   if (isShift) {
7653     // No better options. Use a vshldq / vsrldq.
7654     MVT EltVT = VT.getVectorElementType();
7655     ShAmt *= EltVT.getSizeInBits();
7656     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7657   }
7658
7659   bool Commuted = false;
7660   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7661   // 1,1,1,1 -> v8i16 though.
7662   V1IsSplat = isSplatVector(V1.getNode());
7663   V2IsSplat = isSplatVector(V2.getNode());
7664
7665   // Canonicalize the splat or undef, if present, to be on the RHS.
7666   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7667     CommuteVectorShuffleMask(M, NumElems);
7668     std::swap(V1, V2);
7669     std::swap(V1IsSplat, V2IsSplat);
7670     Commuted = true;
7671   }
7672
7673   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7674     // Shuffling low element of v1 into undef, just return v1.
7675     if (V2IsUndef)
7676       return V1;
7677     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7678     // the instruction selector will not match, so get a canonical MOVL with
7679     // swapped operands to undo the commute.
7680     return getMOVL(DAG, dl, VT, V2, V1);
7681   }
7682
7683   if (isUNPCKLMask(M, VT, HasInt256))
7684     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7685
7686   if (isUNPCKHMask(M, VT, HasInt256))
7687     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7688
7689   if (V2IsSplat) {
7690     // Normalize mask so all entries that point to V2 points to its first
7691     // element then try to match unpck{h|l} again. If match, return a
7692     // new vector_shuffle with the corrected mask.p
7693     SmallVector<int, 8> NewMask(M.begin(), M.end());
7694     NormalizeMask(NewMask, NumElems);
7695     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7696       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7697     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7698       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7699   }
7700
7701   if (Commuted) {
7702     // Commute is back and try unpck* again.
7703     // FIXME: this seems wrong.
7704     CommuteVectorShuffleMask(M, NumElems);
7705     std::swap(V1, V2);
7706     std::swap(V1IsSplat, V2IsSplat);
7707
7708     if (isUNPCKLMask(M, VT, HasInt256))
7709       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7710
7711     if (isUNPCKHMask(M, VT, HasInt256))
7712       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7713   }
7714
7715   // Normalize the node to match x86 shuffle ops if needed
7716   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7717     return CommuteVectorShuffle(SVOp, DAG);
7718
7719   // The checks below are all present in isShuffleMaskLegal, but they are
7720   // inlined here right now to enable us to directly emit target specific
7721   // nodes, and remove one by one until they don't return Op anymore.
7722
7723   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7724       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7725     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7726       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7727   }
7728
7729   if (isPSHUFHWMask(M, VT, HasInt256))
7730     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7731                                 getShufflePSHUFHWImmediate(SVOp),
7732                                 DAG);
7733
7734   if (isPSHUFLWMask(M, VT, HasInt256))
7735     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7736                                 getShufflePSHUFLWImmediate(SVOp),
7737                                 DAG);
7738
7739   if (isSHUFPMask(M, VT))
7740     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7741                                 getShuffleSHUFImmediate(SVOp), DAG);
7742
7743   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7744     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7745   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7746     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7747
7748   //===--------------------------------------------------------------------===//
7749   // Generate target specific nodes for 128 or 256-bit shuffles only
7750   // supported in the AVX instruction set.
7751   //
7752
7753   // Handle VMOVDDUPY permutations
7754   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7755     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7756
7757   // Handle VPERMILPS/D* permutations
7758   if (isVPERMILPMask(M, VT)) {
7759     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7760       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7761                                   getShuffleSHUFImmediate(SVOp), DAG);
7762     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7763                                 getShuffleSHUFImmediate(SVOp), DAG);
7764   }
7765
7766   // Handle VPERM2F128/VPERM2I128 permutations
7767   if (isVPERM2X128Mask(M, VT, HasFp256))
7768     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7769                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7770
7771   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7772   if (BlendOp.getNode())
7773     return BlendOp;
7774
7775   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7776     return getINSERTPS(SVOp, dl, DAG);
7777
7778   unsigned Imm8;
7779   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7780     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7781
7782   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7783       VT.is512BitVector()) {
7784     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7785     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7786     SmallVector<SDValue, 16> permclMask;
7787     for (unsigned i = 0; i != NumElems; ++i) {
7788       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7789     }
7790
7791     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7792                                 &permclMask[0], NumElems);
7793     if (V2IsUndef)
7794       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7795       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7796                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7797     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7798                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7799   }
7800
7801   //===--------------------------------------------------------------------===//
7802   // Since no target specific shuffle was selected for this generic one,
7803   // lower it into other known shuffles. FIXME: this isn't true yet, but
7804   // this is the plan.
7805   //
7806
7807   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7808   if (VT == MVT::v8i16) {
7809     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7810     if (NewOp.getNode())
7811       return NewOp;
7812   }
7813
7814   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7815     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7816     if (NewOp.getNode())
7817       return NewOp;
7818   }
7819
7820   if (VT == MVT::v16i8) {
7821     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7822     if (NewOp.getNode())
7823       return NewOp;
7824   }
7825
7826   if (VT == MVT::v32i8) {
7827     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7828     if (NewOp.getNode())
7829       return NewOp;
7830   }
7831
7832   // Handle all 128-bit wide vectors with 4 elements, and match them with
7833   // several different shuffle types.
7834   if (NumElems == 4 && VT.is128BitVector())
7835     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7836
7837   // Handle general 256-bit shuffles
7838   if (VT.is256BitVector())
7839     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7840
7841   return SDValue();
7842 }
7843
7844 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7845   MVT VT = Op.getSimpleValueType();
7846   SDLoc dl(Op);
7847
7848   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7849     return SDValue();
7850
7851   if (VT.getSizeInBits() == 8) {
7852     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7853                                   Op.getOperand(0), Op.getOperand(1));
7854     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7855                                   DAG.getValueType(VT));
7856     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7857   }
7858
7859   if (VT.getSizeInBits() == 16) {
7860     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7861     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7862     if (Idx == 0)
7863       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7864                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7865                                      DAG.getNode(ISD::BITCAST, dl,
7866                                                  MVT::v4i32,
7867                                                  Op.getOperand(0)),
7868                                      Op.getOperand(1)));
7869     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7870                                   Op.getOperand(0), Op.getOperand(1));
7871     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7872                                   DAG.getValueType(VT));
7873     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7874   }
7875
7876   if (VT == MVT::f32) {
7877     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7878     // the result back to FR32 register. It's only worth matching if the
7879     // result has a single use which is a store or a bitcast to i32.  And in
7880     // the case of a store, it's not worth it if the index is a constant 0,
7881     // because a MOVSSmr can be used instead, which is smaller and faster.
7882     if (!Op.hasOneUse())
7883       return SDValue();
7884     SDNode *User = *Op.getNode()->use_begin();
7885     if ((User->getOpcode() != ISD::STORE ||
7886          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7887           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7888         (User->getOpcode() != ISD::BITCAST ||
7889          User->getValueType(0) != MVT::i32))
7890       return SDValue();
7891     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7892                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7893                                               Op.getOperand(0)),
7894                                               Op.getOperand(1));
7895     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7896   }
7897
7898   if (VT == MVT::i32 || VT == MVT::i64) {
7899     // ExtractPS/pextrq works with constant index.
7900     if (isa<ConstantSDNode>(Op.getOperand(1)))
7901       return Op;
7902   }
7903   return SDValue();
7904 }
7905
7906 /// Extract one bit from mask vector, like v16i1 or v8i1.
7907 /// AVX-512 feature.
7908 SDValue
7909 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7910   SDValue Vec = Op.getOperand(0);
7911   SDLoc dl(Vec);
7912   MVT VecVT = Vec.getSimpleValueType();
7913   SDValue Idx = Op.getOperand(1);
7914   MVT EltVT = Op.getSimpleValueType();
7915
7916   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7917
7918   // variable index can't be handled in mask registers,
7919   // extend vector to VR512
7920   if (!isa<ConstantSDNode>(Idx)) {
7921     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7922     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7923     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7924                               ExtVT.getVectorElementType(), Ext, Idx);
7925     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7926   }
7927
7928   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7929   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7930   unsigned MaxSift = rc->getSize()*8 - 1;
7931   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7932                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7933   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7934                     DAG.getConstant(MaxSift, MVT::i8));
7935   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7936                        DAG.getIntPtrConstant(0));
7937 }
7938
7939 SDValue
7940 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7941                                            SelectionDAG &DAG) const {
7942   SDLoc dl(Op);
7943   SDValue Vec = Op.getOperand(0);
7944   MVT VecVT = Vec.getSimpleValueType();
7945   SDValue Idx = Op.getOperand(1);
7946
7947   if (Op.getSimpleValueType() == MVT::i1)
7948     return ExtractBitFromMaskVector(Op, DAG);
7949
7950   if (!isa<ConstantSDNode>(Idx)) {
7951     if (VecVT.is512BitVector() ||
7952         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7953          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7954
7955       MVT MaskEltVT =
7956         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7957       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7958                                     MaskEltVT.getSizeInBits());
7959
7960       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7961       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7962                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7963                                 Idx, DAG.getConstant(0, getPointerTy()));
7964       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7965       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7966                         Perm, DAG.getConstant(0, getPointerTy()));
7967     }
7968     return SDValue();
7969   }
7970
7971   // If this is a 256-bit vector result, first extract the 128-bit vector and
7972   // then extract the element from the 128-bit vector.
7973   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7974
7975     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7976     // Get the 128-bit vector.
7977     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7978     MVT EltVT = VecVT.getVectorElementType();
7979
7980     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7981
7982     //if (IdxVal >= NumElems/2)
7983     //  IdxVal -= NumElems/2;
7984     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7985     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7986                        DAG.getConstant(IdxVal, MVT::i32));
7987   }
7988
7989   assert(VecVT.is128BitVector() && "Unexpected vector length");
7990
7991   if (Subtarget->hasSSE41()) {
7992     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7993     if (Res.getNode())
7994       return Res;
7995   }
7996
7997   MVT VT = Op.getSimpleValueType();
7998   // TODO: handle v16i8.
7999   if (VT.getSizeInBits() == 16) {
8000     SDValue Vec = Op.getOperand(0);
8001     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8002     if (Idx == 0)
8003       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8004                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8005                                      DAG.getNode(ISD::BITCAST, dl,
8006                                                  MVT::v4i32, Vec),
8007                                      Op.getOperand(1)));
8008     // Transform it so it match pextrw which produces a 32-bit result.
8009     MVT EltVT = MVT::i32;
8010     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8011                                   Op.getOperand(0), Op.getOperand(1));
8012     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8013                                   DAG.getValueType(VT));
8014     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8015   }
8016
8017   if (VT.getSizeInBits() == 32) {
8018     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8019     if (Idx == 0)
8020       return Op;
8021
8022     // SHUFPS the element to the lowest double word, then movss.
8023     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8024     MVT VVT = Op.getOperand(0).getSimpleValueType();
8025     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8026                                        DAG.getUNDEF(VVT), Mask);
8027     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8028                        DAG.getIntPtrConstant(0));
8029   }
8030
8031   if (VT.getSizeInBits() == 64) {
8032     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8033     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8034     //        to match extract_elt for f64.
8035     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8036     if (Idx == 0)
8037       return Op;
8038
8039     // UNPCKHPD the element to the lowest double word, then movsd.
8040     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8041     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8042     int Mask[2] = { 1, -1 };
8043     MVT VVT = Op.getOperand(0).getSimpleValueType();
8044     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8045                                        DAG.getUNDEF(VVT), Mask);
8046     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8047                        DAG.getIntPtrConstant(0));
8048   }
8049
8050   return SDValue();
8051 }
8052
8053 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8054   MVT VT = Op.getSimpleValueType();
8055   MVT EltVT = VT.getVectorElementType();
8056   SDLoc dl(Op);
8057
8058   SDValue N0 = Op.getOperand(0);
8059   SDValue N1 = Op.getOperand(1);
8060   SDValue N2 = Op.getOperand(2);
8061
8062   if (!VT.is128BitVector())
8063     return SDValue();
8064
8065   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8066       isa<ConstantSDNode>(N2)) {
8067     unsigned Opc;
8068     if (VT == MVT::v8i16)
8069       Opc = X86ISD::PINSRW;
8070     else if (VT == MVT::v16i8)
8071       Opc = X86ISD::PINSRB;
8072     else
8073       Opc = X86ISD::PINSRB;
8074
8075     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8076     // argument.
8077     if (N1.getValueType() != MVT::i32)
8078       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8079     if (N2.getValueType() != MVT::i32)
8080       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8081     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8082   }
8083
8084   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8085     // Bits [7:6] of the constant are the source select.  This will always be
8086     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8087     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8088     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8089     // Bits [5:4] of the constant are the destination select.  This is the
8090     //  value of the incoming immediate.
8091     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8092     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8093     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8094     // Create this as a scalar to vector..
8095     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8096     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8097   }
8098
8099   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8100     // PINSR* works with constant index.
8101     return Op;
8102   }
8103   return SDValue();
8104 }
8105
8106 /// Insert one bit to mask vector, like v16i1 or v8i1.
8107 /// AVX-512 feature.
8108 SDValue 
8109 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8110   SDLoc dl(Op);
8111   SDValue Vec = Op.getOperand(0);
8112   SDValue Elt = Op.getOperand(1);
8113   SDValue Idx = Op.getOperand(2);
8114   MVT VecVT = Vec.getSimpleValueType();
8115
8116   if (!isa<ConstantSDNode>(Idx)) {
8117     // Non constant index. Extend source and destination,
8118     // insert element and then truncate the result.
8119     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8120     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8121     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8122       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8123       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8124     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8125   }
8126
8127   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8128   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8129   if (Vec.getOpcode() == ISD::UNDEF)
8130     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8131                        DAG.getConstant(IdxVal, MVT::i8));
8132   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8133   unsigned MaxSift = rc->getSize()*8 - 1;
8134   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8135                     DAG.getConstant(MaxSift, MVT::i8));
8136   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8137                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8138   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8139 }
8140 SDValue
8141 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8142   MVT VT = Op.getSimpleValueType();
8143   MVT EltVT = VT.getVectorElementType();
8144   
8145   if (EltVT == MVT::i1)
8146     return InsertBitToMaskVector(Op, DAG);
8147
8148   SDLoc dl(Op);
8149   SDValue N0 = Op.getOperand(0);
8150   SDValue N1 = Op.getOperand(1);
8151   SDValue N2 = Op.getOperand(2);
8152
8153   // If this is a 256-bit vector result, first extract the 128-bit vector,
8154   // insert the element into the extracted half and then place it back.
8155   if (VT.is256BitVector() || VT.is512BitVector()) {
8156     if (!isa<ConstantSDNode>(N2))
8157       return SDValue();
8158
8159     // Get the desired 128-bit vector half.
8160     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8161     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8162
8163     // Insert the element into the desired half.
8164     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8165     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8166
8167     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8168                     DAG.getConstant(IdxIn128, MVT::i32));
8169
8170     // Insert the changed part back to the 256-bit vector
8171     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8172   }
8173
8174   if (Subtarget->hasSSE41())
8175     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8176
8177   if (EltVT == MVT::i8)
8178     return SDValue();
8179
8180   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8181     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8182     // as its second argument.
8183     if (N1.getValueType() != MVT::i32)
8184       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8185     if (N2.getValueType() != MVT::i32)
8186       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8187     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8188   }
8189   return SDValue();
8190 }
8191
8192 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8193   SDLoc dl(Op);
8194   MVT OpVT = Op.getSimpleValueType();
8195
8196   // If this is a 256-bit vector result, first insert into a 128-bit
8197   // vector and then insert into the 256-bit vector.
8198   if (!OpVT.is128BitVector()) {
8199     // Insert into a 128-bit vector.
8200     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8201     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8202                                  OpVT.getVectorNumElements() / SizeFactor);
8203
8204     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8205
8206     // Insert the 128-bit vector.
8207     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8208   }
8209
8210   if (OpVT == MVT::v1i64 &&
8211       Op.getOperand(0).getValueType() == MVT::i64)
8212     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8213
8214   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8215   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8216   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8217                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8218 }
8219
8220 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8221 // a simple subregister reference or explicit instructions to grab
8222 // upper bits of a vector.
8223 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8224                                       SelectionDAG &DAG) {
8225   SDLoc dl(Op);
8226   SDValue In =  Op.getOperand(0);
8227   SDValue Idx = Op.getOperand(1);
8228   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8229   MVT ResVT   = Op.getSimpleValueType();
8230   MVT InVT    = In.getSimpleValueType();
8231
8232   if (Subtarget->hasFp256()) {
8233     if (ResVT.is128BitVector() &&
8234         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8235         isa<ConstantSDNode>(Idx)) {
8236       return Extract128BitVector(In, IdxVal, DAG, dl);
8237     }
8238     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8239         isa<ConstantSDNode>(Idx)) {
8240       return Extract256BitVector(In, IdxVal, DAG, dl);
8241     }
8242   }
8243   return SDValue();
8244 }
8245
8246 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8247 // simple superregister reference or explicit instructions to insert
8248 // the upper bits of a vector.
8249 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8250                                      SelectionDAG &DAG) {
8251   if (Subtarget->hasFp256()) {
8252     SDLoc dl(Op.getNode());
8253     SDValue Vec = Op.getNode()->getOperand(0);
8254     SDValue SubVec = Op.getNode()->getOperand(1);
8255     SDValue Idx = Op.getNode()->getOperand(2);
8256
8257     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8258          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8259         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8260         isa<ConstantSDNode>(Idx)) {
8261       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8262       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8263     }
8264
8265     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8266         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8267         isa<ConstantSDNode>(Idx)) {
8268       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8269       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8270     }
8271   }
8272   return SDValue();
8273 }
8274
8275 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8276 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8277 // one of the above mentioned nodes. It has to be wrapped because otherwise
8278 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8279 // be used to form addressing mode. These wrapped nodes will be selected
8280 // into MOV32ri.
8281 SDValue
8282 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8283   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8284
8285   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8286   // global base reg.
8287   unsigned char OpFlag = 0;
8288   unsigned WrapperKind = X86ISD::Wrapper;
8289   CodeModel::Model M = getTargetMachine().getCodeModel();
8290
8291   if (Subtarget->isPICStyleRIPRel() &&
8292       (M == CodeModel::Small || M == CodeModel::Kernel))
8293     WrapperKind = X86ISD::WrapperRIP;
8294   else if (Subtarget->isPICStyleGOT())
8295     OpFlag = X86II::MO_GOTOFF;
8296   else if (Subtarget->isPICStyleStubPIC())
8297     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8298
8299   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8300                                              CP->getAlignment(),
8301                                              CP->getOffset(), OpFlag);
8302   SDLoc DL(CP);
8303   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8304   // With PIC, the address is actually $g + Offset.
8305   if (OpFlag) {
8306     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8307                          DAG.getNode(X86ISD::GlobalBaseReg,
8308                                      SDLoc(), getPointerTy()),
8309                          Result);
8310   }
8311
8312   return Result;
8313 }
8314
8315 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8316   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8317
8318   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8319   // global base reg.
8320   unsigned char OpFlag = 0;
8321   unsigned WrapperKind = X86ISD::Wrapper;
8322   CodeModel::Model M = getTargetMachine().getCodeModel();
8323
8324   if (Subtarget->isPICStyleRIPRel() &&
8325       (M == CodeModel::Small || M == CodeModel::Kernel))
8326     WrapperKind = X86ISD::WrapperRIP;
8327   else if (Subtarget->isPICStyleGOT())
8328     OpFlag = X86II::MO_GOTOFF;
8329   else if (Subtarget->isPICStyleStubPIC())
8330     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8331
8332   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8333                                           OpFlag);
8334   SDLoc DL(JT);
8335   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8336
8337   // With PIC, the address is actually $g + Offset.
8338   if (OpFlag)
8339     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8340                          DAG.getNode(X86ISD::GlobalBaseReg,
8341                                      SDLoc(), getPointerTy()),
8342                          Result);
8343
8344   return Result;
8345 }
8346
8347 SDValue
8348 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8349   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8350
8351   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8352   // global base reg.
8353   unsigned char OpFlag = 0;
8354   unsigned WrapperKind = X86ISD::Wrapper;
8355   CodeModel::Model M = getTargetMachine().getCodeModel();
8356
8357   if (Subtarget->isPICStyleRIPRel() &&
8358       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8359     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8360       OpFlag = X86II::MO_GOTPCREL;
8361     WrapperKind = X86ISD::WrapperRIP;
8362   } else if (Subtarget->isPICStyleGOT()) {
8363     OpFlag = X86II::MO_GOT;
8364   } else if (Subtarget->isPICStyleStubPIC()) {
8365     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8366   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8367     OpFlag = X86II::MO_DARWIN_NONLAZY;
8368   }
8369
8370   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8371
8372   SDLoc DL(Op);
8373   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8374
8375   // With PIC, the address is actually $g + Offset.
8376   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8377       !Subtarget->is64Bit()) {
8378     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8379                          DAG.getNode(X86ISD::GlobalBaseReg,
8380                                      SDLoc(), getPointerTy()),
8381                          Result);
8382   }
8383
8384   // For symbols that require a load from a stub to get the address, emit the
8385   // load.
8386   if (isGlobalStubReference(OpFlag))
8387     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8388                          MachinePointerInfo::getGOT(), false, false, false, 0);
8389
8390   return Result;
8391 }
8392
8393 SDValue
8394 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8395   // Create the TargetBlockAddressAddress node.
8396   unsigned char OpFlags =
8397     Subtarget->ClassifyBlockAddressReference();
8398   CodeModel::Model M = getTargetMachine().getCodeModel();
8399   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8400   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8401   SDLoc dl(Op);
8402   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8403                                              OpFlags);
8404
8405   if (Subtarget->isPICStyleRIPRel() &&
8406       (M == CodeModel::Small || M == CodeModel::Kernel))
8407     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8408   else
8409     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8410
8411   // With PIC, the address is actually $g + Offset.
8412   if (isGlobalRelativeToPICBase(OpFlags)) {
8413     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8414                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8415                          Result);
8416   }
8417
8418   return Result;
8419 }
8420
8421 SDValue
8422 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8423                                       int64_t Offset, SelectionDAG &DAG) const {
8424   // Create the TargetGlobalAddress node, folding in the constant
8425   // offset if it is legal.
8426   unsigned char OpFlags =
8427     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8428   CodeModel::Model M = getTargetMachine().getCodeModel();
8429   SDValue Result;
8430   if (OpFlags == X86II::MO_NO_FLAG &&
8431       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8432     // A direct static reference to a global.
8433     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8434     Offset = 0;
8435   } else {
8436     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8437   }
8438
8439   if (Subtarget->isPICStyleRIPRel() &&
8440       (M == CodeModel::Small || M == CodeModel::Kernel))
8441     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8442   else
8443     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8444
8445   // With PIC, the address is actually $g + Offset.
8446   if (isGlobalRelativeToPICBase(OpFlags)) {
8447     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8448                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8449                          Result);
8450   }
8451
8452   // For globals that require a load from a stub to get the address, emit the
8453   // load.
8454   if (isGlobalStubReference(OpFlags))
8455     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8456                          MachinePointerInfo::getGOT(), false, false, false, 0);
8457
8458   // If there was a non-zero offset that we didn't fold, create an explicit
8459   // addition for it.
8460   if (Offset != 0)
8461     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8462                          DAG.getConstant(Offset, getPointerTy()));
8463
8464   return Result;
8465 }
8466
8467 SDValue
8468 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8469   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8470   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8471   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8472 }
8473
8474 static SDValue
8475 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8476            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8477            unsigned char OperandFlags, bool LocalDynamic = false) {
8478   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8479   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8480   SDLoc dl(GA);
8481   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8482                                            GA->getValueType(0),
8483                                            GA->getOffset(),
8484                                            OperandFlags);
8485
8486   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8487                                            : X86ISD::TLSADDR;
8488
8489   if (InFlag) {
8490     SDValue Ops[] = { Chain,  TGA, *InFlag };
8491     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8492   } else {
8493     SDValue Ops[]  = { Chain, TGA };
8494     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8495   }
8496
8497   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8498   MFI->setAdjustsStack(true);
8499
8500   SDValue Flag = Chain.getValue(1);
8501   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8502 }
8503
8504 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8505 static SDValue
8506 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8507                                 const EVT PtrVT) {
8508   SDValue InFlag;
8509   SDLoc dl(GA);  // ? function entry point might be better
8510   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8511                                    DAG.getNode(X86ISD::GlobalBaseReg,
8512                                                SDLoc(), PtrVT), InFlag);
8513   InFlag = Chain.getValue(1);
8514
8515   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8516 }
8517
8518 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8519 static SDValue
8520 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8521                                 const EVT PtrVT) {
8522   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8523                     X86::RAX, X86II::MO_TLSGD);
8524 }
8525
8526 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8527                                            SelectionDAG &DAG,
8528                                            const EVT PtrVT,
8529                                            bool is64Bit) {
8530   SDLoc dl(GA);
8531
8532   // Get the start address of the TLS block for this module.
8533   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8534       .getInfo<X86MachineFunctionInfo>();
8535   MFI->incNumLocalDynamicTLSAccesses();
8536
8537   SDValue Base;
8538   if (is64Bit) {
8539     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8540                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8541   } else {
8542     SDValue InFlag;
8543     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8544         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8545     InFlag = Chain.getValue(1);
8546     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8547                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8548   }
8549
8550   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8551   // of Base.
8552
8553   // Build x@dtpoff.
8554   unsigned char OperandFlags = X86II::MO_DTPOFF;
8555   unsigned WrapperKind = X86ISD::Wrapper;
8556   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8557                                            GA->getValueType(0),
8558                                            GA->getOffset(), OperandFlags);
8559   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8560
8561   // Add x@dtpoff with the base.
8562   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8563 }
8564
8565 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8566 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8567                                    const EVT PtrVT, TLSModel::Model model,
8568                                    bool is64Bit, bool isPIC) {
8569   SDLoc dl(GA);
8570
8571   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8572   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8573                                                          is64Bit ? 257 : 256));
8574
8575   SDValue ThreadPointer =
8576       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8577                   MachinePointerInfo(Ptr), false, false, false, 0);
8578
8579   unsigned char OperandFlags = 0;
8580   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8581   // initialexec.
8582   unsigned WrapperKind = X86ISD::Wrapper;
8583   if (model == TLSModel::LocalExec) {
8584     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8585   } else if (model == TLSModel::InitialExec) {
8586     if (is64Bit) {
8587       OperandFlags = X86II::MO_GOTTPOFF;
8588       WrapperKind = X86ISD::WrapperRIP;
8589     } else {
8590       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8591     }
8592   } else {
8593     llvm_unreachable("Unexpected model");
8594   }
8595
8596   // emit "addl x@ntpoff,%eax" (local exec)
8597   // or "addl x@indntpoff,%eax" (initial exec)
8598   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8599   SDValue TGA =
8600       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8601                                  GA->getOffset(), OperandFlags);
8602   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8603
8604   if (model == TLSModel::InitialExec) {
8605     if (isPIC && !is64Bit) {
8606       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8607                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8608                            Offset);
8609     }
8610
8611     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8612                          MachinePointerInfo::getGOT(), false, false, false, 0);
8613   }
8614
8615   // The address of the thread local variable is the add of the thread
8616   // pointer with the offset of the variable.
8617   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8618 }
8619
8620 SDValue
8621 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8622
8623   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8624   const GlobalValue *GV = GA->getGlobal();
8625
8626   if (Subtarget->isTargetELF()) {
8627     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8628
8629     switch (model) {
8630       case TLSModel::GeneralDynamic:
8631         if (Subtarget->is64Bit())
8632           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8633         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8634       case TLSModel::LocalDynamic:
8635         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8636                                            Subtarget->is64Bit());
8637       case TLSModel::InitialExec:
8638       case TLSModel::LocalExec:
8639         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8640                                    Subtarget->is64Bit(),
8641                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8642     }
8643     llvm_unreachable("Unknown TLS model.");
8644   }
8645
8646   if (Subtarget->isTargetDarwin()) {
8647     // Darwin only has one model of TLS.  Lower to that.
8648     unsigned char OpFlag = 0;
8649     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8650                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8651
8652     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8653     // global base reg.
8654     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8655                   !Subtarget->is64Bit();
8656     if (PIC32)
8657       OpFlag = X86II::MO_TLVP_PIC_BASE;
8658     else
8659       OpFlag = X86II::MO_TLVP;
8660     SDLoc DL(Op);
8661     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8662                                                 GA->getValueType(0),
8663                                                 GA->getOffset(), OpFlag);
8664     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8665
8666     // With PIC32, the address is actually $g + Offset.
8667     if (PIC32)
8668       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8669                            DAG.getNode(X86ISD::GlobalBaseReg,
8670                                        SDLoc(), getPointerTy()),
8671                            Offset);
8672
8673     // Lowering the machine isd will make sure everything is in the right
8674     // location.
8675     SDValue Chain = DAG.getEntryNode();
8676     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8677     SDValue Args[] = { Chain, Offset };
8678     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8679
8680     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8681     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8682     MFI->setAdjustsStack(true);
8683
8684     // And our return value (tls address) is in the standard call return value
8685     // location.
8686     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8687     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8688                               Chain.getValue(1));
8689   }
8690
8691   if (Subtarget->isTargetKnownWindowsMSVC() ||
8692       Subtarget->isTargetWindowsGNU()) {
8693     // Just use the implicit TLS architecture
8694     // Need to generate someting similar to:
8695     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8696     //                                  ; from TEB
8697     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8698     //   mov     rcx, qword [rdx+rcx*8]
8699     //   mov     eax, .tls$:tlsvar
8700     //   [rax+rcx] contains the address
8701     // Windows 64bit: gs:0x58
8702     // Windows 32bit: fs:__tls_array
8703
8704     // If GV is an alias then use the aliasee for determining
8705     // thread-localness.
8706     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8707       GV = GA->getAliasedGlobal();
8708     SDLoc dl(GA);
8709     SDValue Chain = DAG.getEntryNode();
8710
8711     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8712     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8713     // use its literal value of 0x2C.
8714     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8715                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8716                                                              256)
8717                                         : Type::getInt32PtrTy(*DAG.getContext(),
8718                                                               257));
8719
8720     SDValue TlsArray =
8721         Subtarget->is64Bit()
8722             ? DAG.getIntPtrConstant(0x58)
8723             : (Subtarget->isTargetWindowsGNU()
8724                    ? DAG.getIntPtrConstant(0x2C)
8725                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8726
8727     SDValue ThreadPointer =
8728         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8729                     MachinePointerInfo(Ptr), false, false, false, 0);
8730
8731     // Load the _tls_index variable
8732     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8733     if (Subtarget->is64Bit())
8734       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8735                            IDX, MachinePointerInfo(), MVT::i32,
8736                            false, false, 0);
8737     else
8738       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8739                         false, false, false, 0);
8740
8741     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8742                                     getPointerTy());
8743     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8744
8745     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8746     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8747                       false, false, false, 0);
8748
8749     // Get the offset of start of .tls section
8750     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8751                                              GA->getValueType(0),
8752                                              GA->getOffset(), X86II::MO_SECREL);
8753     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8754
8755     // The address of the thread local variable is the add of the thread
8756     // pointer with the offset of the variable.
8757     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8758   }
8759
8760   llvm_unreachable("TLS not implemented for this target.");
8761 }
8762
8763 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8764 /// and take a 2 x i32 value to shift plus a shift amount.
8765 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8766   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8767   MVT VT = Op.getSimpleValueType();
8768   unsigned VTBits = VT.getSizeInBits();
8769   SDLoc dl(Op);
8770   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8771   SDValue ShOpLo = Op.getOperand(0);
8772   SDValue ShOpHi = Op.getOperand(1);
8773   SDValue ShAmt  = Op.getOperand(2);
8774   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8775   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8776   // during isel.
8777   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8778                                   DAG.getConstant(VTBits - 1, MVT::i8));
8779   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8780                                      DAG.getConstant(VTBits - 1, MVT::i8))
8781                        : DAG.getConstant(0, VT);
8782
8783   SDValue Tmp2, Tmp3;
8784   if (Op.getOpcode() == ISD::SHL_PARTS) {
8785     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8786     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8787   } else {
8788     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8789     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8790   }
8791
8792   // If the shift amount is larger or equal than the width of a part we can't
8793   // rely on the results of shld/shrd. Insert a test and select the appropriate
8794   // values for large shift amounts.
8795   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8796                                 DAG.getConstant(VTBits, MVT::i8));
8797   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8798                              AndNode, DAG.getConstant(0, MVT::i8));
8799
8800   SDValue Hi, Lo;
8801   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8802   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8803   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8804
8805   if (Op.getOpcode() == ISD::SHL_PARTS) {
8806     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8807     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8808   } else {
8809     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8810     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8811   }
8812
8813   SDValue Ops[2] = { Lo, Hi };
8814   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8815 }
8816
8817 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8818                                            SelectionDAG &DAG) const {
8819   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8820
8821   if (SrcVT.isVector())
8822     return SDValue();
8823
8824   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8825          "Unknown SINT_TO_FP to lower!");
8826
8827   // These are really Legal; return the operand so the caller accepts it as
8828   // Legal.
8829   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8830     return Op;
8831   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8832       Subtarget->is64Bit()) {
8833     return Op;
8834   }
8835
8836   SDLoc dl(Op);
8837   unsigned Size = SrcVT.getSizeInBits()/8;
8838   MachineFunction &MF = DAG.getMachineFunction();
8839   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8840   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8841   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8842                                StackSlot,
8843                                MachinePointerInfo::getFixedStack(SSFI),
8844                                false, false, 0);
8845   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8846 }
8847
8848 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8849                                      SDValue StackSlot,
8850                                      SelectionDAG &DAG) const {
8851   // Build the FILD
8852   SDLoc DL(Op);
8853   SDVTList Tys;
8854   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8855   if (useSSE)
8856     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8857   else
8858     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8859
8860   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8861
8862   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8863   MachineMemOperand *MMO;
8864   if (FI) {
8865     int SSFI = FI->getIndex();
8866     MMO =
8867       DAG.getMachineFunction()
8868       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8869                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8870   } else {
8871     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8872     StackSlot = StackSlot.getOperand(1);
8873   }
8874   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8875   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8876                                            X86ISD::FILD, DL,
8877                                            Tys, Ops, array_lengthof(Ops),
8878                                            SrcVT, MMO);
8879
8880   if (useSSE) {
8881     Chain = Result.getValue(1);
8882     SDValue InFlag = Result.getValue(2);
8883
8884     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8885     // shouldn't be necessary except that RFP cannot be live across
8886     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8887     MachineFunction &MF = DAG.getMachineFunction();
8888     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8889     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8890     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8891     Tys = DAG.getVTList(MVT::Other);
8892     SDValue Ops[] = {
8893       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8894     };
8895     MachineMemOperand *MMO =
8896       DAG.getMachineFunction()
8897       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8898                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8899
8900     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8901                                     Ops, array_lengthof(Ops),
8902                                     Op.getValueType(), MMO);
8903     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8904                          MachinePointerInfo::getFixedStack(SSFI),
8905                          false, false, false, 0);
8906   }
8907
8908   return Result;
8909 }
8910
8911 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8912 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8913                                                SelectionDAG &DAG) const {
8914   // This algorithm is not obvious. Here it is what we're trying to output:
8915   /*
8916      movq       %rax,  %xmm0
8917      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8918      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8919      #ifdef __SSE3__
8920        haddpd   %xmm0, %xmm0
8921      #else
8922        pshufd   $0x4e, %xmm0, %xmm1
8923        addpd    %xmm1, %xmm0
8924      #endif
8925   */
8926
8927   SDLoc dl(Op);
8928   LLVMContext *Context = DAG.getContext();
8929
8930   // Build some magic constants.
8931   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8932   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8933   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8934
8935   SmallVector<Constant*,2> CV1;
8936   CV1.push_back(
8937     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8938                                       APInt(64, 0x4330000000000000ULL))));
8939   CV1.push_back(
8940     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8941                                       APInt(64, 0x4530000000000000ULL))));
8942   Constant *C1 = ConstantVector::get(CV1);
8943   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8944
8945   // Load the 64-bit value into an XMM register.
8946   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8947                             Op.getOperand(0));
8948   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8949                               MachinePointerInfo::getConstantPool(),
8950                               false, false, false, 16);
8951   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8952                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8953                               CLod0);
8954
8955   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8956                               MachinePointerInfo::getConstantPool(),
8957                               false, false, false, 16);
8958   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8959   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8960   SDValue Result;
8961
8962   if (Subtarget->hasSSE3()) {
8963     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8964     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8965   } else {
8966     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8967     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8968                                            S2F, 0x4E, DAG);
8969     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8970                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8971                          Sub);
8972   }
8973
8974   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8975                      DAG.getIntPtrConstant(0));
8976 }
8977
8978 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8979 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8980                                                SelectionDAG &DAG) const {
8981   SDLoc dl(Op);
8982   // FP constant to bias correct the final result.
8983   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8984                                    MVT::f64);
8985
8986   // Load the 32-bit value into an XMM register.
8987   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8988                              Op.getOperand(0));
8989
8990   // Zero out the upper parts of the register.
8991   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8992
8993   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8994                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8995                      DAG.getIntPtrConstant(0));
8996
8997   // Or the load with the bias.
8998   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8999                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9000                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9001                                                    MVT::v2f64, Load)),
9002                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9003                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9004                                                    MVT::v2f64, Bias)));
9005   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9006                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9007                    DAG.getIntPtrConstant(0));
9008
9009   // Subtract the bias.
9010   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9011
9012   // Handle final rounding.
9013   EVT DestVT = Op.getValueType();
9014
9015   if (DestVT.bitsLT(MVT::f64))
9016     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9017                        DAG.getIntPtrConstant(0));
9018   if (DestVT.bitsGT(MVT::f64))
9019     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9020
9021   // Handle final rounding.
9022   return Sub;
9023 }
9024
9025 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9026                                                SelectionDAG &DAG) const {
9027   SDValue N0 = Op.getOperand(0);
9028   MVT SVT = N0.getSimpleValueType();
9029   SDLoc dl(Op);
9030
9031   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9032           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9033          "Custom UINT_TO_FP is not supported!");
9034
9035   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9036   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9037                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9038 }
9039
9040 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9041                                            SelectionDAG &DAG) const {
9042   SDValue N0 = Op.getOperand(0);
9043   SDLoc dl(Op);
9044
9045   if (Op.getValueType().isVector())
9046     return lowerUINT_TO_FP_vec(Op, DAG);
9047
9048   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9049   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9050   // the optimization here.
9051   if (DAG.SignBitIsZero(N0))
9052     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9053
9054   MVT SrcVT = N0.getSimpleValueType();
9055   MVT DstVT = Op.getSimpleValueType();
9056   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9057     return LowerUINT_TO_FP_i64(Op, DAG);
9058   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9059     return LowerUINT_TO_FP_i32(Op, DAG);
9060   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9061     return SDValue();
9062
9063   // Make a 64-bit buffer, and use it to build an FILD.
9064   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9065   if (SrcVT == MVT::i32) {
9066     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9067     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9068                                      getPointerTy(), StackSlot, WordOff);
9069     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9070                                   StackSlot, MachinePointerInfo(),
9071                                   false, false, 0);
9072     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9073                                   OffsetSlot, MachinePointerInfo(),
9074                                   false, false, 0);
9075     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9076     return Fild;
9077   }
9078
9079   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9080   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9081                                StackSlot, MachinePointerInfo(),
9082                                false, false, 0);
9083   // For i64 source, we need to add the appropriate power of 2 if the input
9084   // was negative.  This is the same as the optimization in
9085   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9086   // we must be careful to do the computation in x87 extended precision, not
9087   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9088   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9089   MachineMemOperand *MMO =
9090     DAG.getMachineFunction()
9091     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9092                           MachineMemOperand::MOLoad, 8, 8);
9093
9094   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9095   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9096   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9097                                          array_lengthof(Ops), MVT::i64, MMO);
9098
9099   APInt FF(32, 0x5F800000ULL);
9100
9101   // Check whether the sign bit is set.
9102   SDValue SignSet = DAG.getSetCC(dl,
9103                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9104                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9105                                  ISD::SETLT);
9106
9107   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9108   SDValue FudgePtr = DAG.getConstantPool(
9109                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9110                                          getPointerTy());
9111
9112   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9113   SDValue Zero = DAG.getIntPtrConstant(0);
9114   SDValue Four = DAG.getIntPtrConstant(4);
9115   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9116                                Zero, Four);
9117   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9118
9119   // Load the value out, extending it from f32 to f80.
9120   // FIXME: Avoid the extend by constructing the right constant pool?
9121   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9122                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9123                                  MVT::f32, false, false, 4);
9124   // Extend everything to 80 bits to force it to be done on x87.
9125   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9126   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9127 }
9128
9129 std::pair<SDValue,SDValue>
9130 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9131                                     bool IsSigned, bool IsReplace) const {
9132   SDLoc DL(Op);
9133
9134   EVT DstTy = Op.getValueType();
9135
9136   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9137     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9138     DstTy = MVT::i64;
9139   }
9140
9141   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9142          DstTy.getSimpleVT() >= MVT::i16 &&
9143          "Unknown FP_TO_INT to lower!");
9144
9145   // These are really Legal.
9146   if (DstTy == MVT::i32 &&
9147       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9148     return std::make_pair(SDValue(), SDValue());
9149   if (Subtarget->is64Bit() &&
9150       DstTy == MVT::i64 &&
9151       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9152     return std::make_pair(SDValue(), SDValue());
9153
9154   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9155   // stack slot, or into the FTOL runtime function.
9156   MachineFunction &MF = DAG.getMachineFunction();
9157   unsigned MemSize = DstTy.getSizeInBits()/8;
9158   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9159   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9160
9161   unsigned Opc;
9162   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9163     Opc = X86ISD::WIN_FTOL;
9164   else
9165     switch (DstTy.getSimpleVT().SimpleTy) {
9166     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9167     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9168     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9169     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9170     }
9171
9172   SDValue Chain = DAG.getEntryNode();
9173   SDValue Value = Op.getOperand(0);
9174   EVT TheVT = Op.getOperand(0).getValueType();
9175   // FIXME This causes a redundant load/store if the SSE-class value is already
9176   // in memory, such as if it is on the callstack.
9177   if (isScalarFPTypeInSSEReg(TheVT)) {
9178     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9179     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9180                          MachinePointerInfo::getFixedStack(SSFI),
9181                          false, false, 0);
9182     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9183     SDValue Ops[] = {
9184       Chain, StackSlot, DAG.getValueType(TheVT)
9185     };
9186
9187     MachineMemOperand *MMO =
9188       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9189                               MachineMemOperand::MOLoad, MemSize, MemSize);
9190     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9191                                     array_lengthof(Ops), DstTy, MMO);
9192     Chain = Value.getValue(1);
9193     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9194     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9195   }
9196
9197   MachineMemOperand *MMO =
9198     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9199                             MachineMemOperand::MOStore, MemSize, MemSize);
9200
9201   if (Opc != X86ISD::WIN_FTOL) {
9202     // Build the FP_TO_INT*_IN_MEM
9203     SDValue Ops[] = { Chain, Value, StackSlot };
9204     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9205                                            Ops, array_lengthof(Ops), DstTy,
9206                                            MMO);
9207     return std::make_pair(FIST, StackSlot);
9208   } else {
9209     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9210       DAG.getVTList(MVT::Other, MVT::Glue),
9211       Chain, Value);
9212     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9213       MVT::i32, ftol.getValue(1));
9214     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9215       MVT::i32, eax.getValue(2));
9216     SDValue Ops[] = { eax, edx };
9217     SDValue pair = IsReplace
9218       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9219       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9220     return std::make_pair(pair, SDValue());
9221   }
9222 }
9223
9224 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9225                               const X86Subtarget *Subtarget) {
9226   MVT VT = Op->getSimpleValueType(0);
9227   SDValue In = Op->getOperand(0);
9228   MVT InVT = In.getSimpleValueType();
9229   SDLoc dl(Op);
9230
9231   // Optimize vectors in AVX mode:
9232   //
9233   //   v8i16 -> v8i32
9234   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9235   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9236   //   Concat upper and lower parts.
9237   //
9238   //   v4i32 -> v4i64
9239   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9240   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9241   //   Concat upper and lower parts.
9242   //
9243
9244   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9245       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9246       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9247     return SDValue();
9248
9249   if (Subtarget->hasInt256())
9250     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9251
9252   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9253   SDValue Undef = DAG.getUNDEF(InVT);
9254   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9255   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9256   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9257
9258   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9259                              VT.getVectorNumElements()/2);
9260
9261   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9262   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9263
9264   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9265 }
9266
9267 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9268                                         SelectionDAG &DAG) {
9269   MVT VT = Op->getSimpleValueType(0);
9270   SDValue In = Op->getOperand(0);
9271   MVT InVT = In.getSimpleValueType();
9272   SDLoc DL(Op);
9273   unsigned int NumElts = VT.getVectorNumElements();
9274   if (NumElts != 8 && NumElts != 16)
9275     return SDValue();
9276
9277   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9278     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9279
9280   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9282   // Now we have only mask extension
9283   assert(InVT.getVectorElementType() == MVT::i1);
9284   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9285   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9286   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9287   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9288   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9289                            MachinePointerInfo::getConstantPool(),
9290                            false, false, false, Alignment);
9291
9292   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9293   if (VT.is512BitVector())
9294     return Brcst;
9295   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9296 }
9297
9298 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9299                                SelectionDAG &DAG) {
9300   if (Subtarget->hasFp256()) {
9301     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9302     if (Res.getNode())
9303       return Res;
9304   }
9305
9306   return SDValue();
9307 }
9308
9309 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9310                                 SelectionDAG &DAG) {
9311   SDLoc DL(Op);
9312   MVT VT = Op.getSimpleValueType();
9313   SDValue In = Op.getOperand(0);
9314   MVT SVT = In.getSimpleValueType();
9315
9316   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9317     return LowerZERO_EXTEND_AVX512(Op, DAG);
9318
9319   if (Subtarget->hasFp256()) {
9320     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9321     if (Res.getNode())
9322       return Res;
9323   }
9324
9325   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9326          VT.getVectorNumElements() != SVT.getVectorNumElements());
9327   return SDValue();
9328 }
9329
9330 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9331   SDLoc DL(Op);
9332   MVT VT = Op.getSimpleValueType();
9333   SDValue In = Op.getOperand(0);
9334   MVT InVT = In.getSimpleValueType();
9335
9336   if (VT == MVT::i1) {
9337     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9338            "Invalid scalar TRUNCATE operation");
9339     if (InVT == MVT::i32)
9340       return SDValue();
9341     if (InVT.getSizeInBits() == 64)
9342       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9343     else if (InVT.getSizeInBits() < 32)
9344       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9345     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9346   }
9347   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9348          "Invalid TRUNCATE operation");
9349
9350   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9351     if (VT.getVectorElementType().getSizeInBits() >=8)
9352       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9353
9354     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9355     unsigned NumElts = InVT.getVectorNumElements();
9356     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9357     if (InVT.getSizeInBits() < 512) {
9358       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9359       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9360       InVT = ExtVT;
9361     }
9362     
9363     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9364     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9365     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9366     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9367     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9368                            MachinePointerInfo::getConstantPool(),
9369                            false, false, false, Alignment);
9370     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9371     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9372     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9373   }
9374
9375   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9376     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9377     if (Subtarget->hasInt256()) {
9378       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9379       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9380       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9381                                 ShufMask);
9382       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9383                          DAG.getIntPtrConstant(0));
9384     }
9385
9386     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9387                                DAG.getIntPtrConstant(0));
9388     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9389                                DAG.getIntPtrConstant(2));
9390     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9391     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9392     static const int ShufMask[] = {0, 2, 4, 6};
9393     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9394   }
9395
9396   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9397     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9398     if (Subtarget->hasInt256()) {
9399       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9400
9401       SmallVector<SDValue,32> pshufbMask;
9402       for (unsigned i = 0; i < 2; ++i) {
9403         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9404         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9405         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9406         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9407         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9408         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9409         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9410         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9411         for (unsigned j = 0; j < 8; ++j)
9412           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9413       }
9414       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9415                                &pshufbMask[0], 32);
9416       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9417       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9418
9419       static const int ShufMask[] = {0,  2,  -1,  -1};
9420       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9421                                 &ShufMask[0]);
9422       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9423                        DAG.getIntPtrConstant(0));
9424       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9425     }
9426
9427     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9428                                DAG.getIntPtrConstant(0));
9429
9430     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9431                                DAG.getIntPtrConstant(4));
9432
9433     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9434     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9435
9436     // The PSHUFB mask:
9437     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9438                                    -1, -1, -1, -1, -1, -1, -1, -1};
9439
9440     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9441     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9442     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9443
9444     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9445     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9446
9447     // The MOVLHPS Mask:
9448     static const int ShufMask2[] = {0, 1, 4, 5};
9449     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9450     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9451   }
9452
9453   // Handle truncation of V256 to V128 using shuffles.
9454   if (!VT.is128BitVector() || !InVT.is256BitVector())
9455     return SDValue();
9456
9457   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9458
9459   unsigned NumElems = VT.getVectorNumElements();
9460   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9461
9462   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9463   // Prepare truncation shuffle mask
9464   for (unsigned i = 0; i != NumElems; ++i)
9465     MaskVec[i] = i * 2;
9466   SDValue V = DAG.getVectorShuffle(NVT, DL,
9467                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9468                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9469   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9470                      DAG.getIntPtrConstant(0));
9471 }
9472
9473 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9474                                            SelectionDAG &DAG) const {
9475   assert(!Op.getSimpleValueType().isVector());
9476
9477   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9478     /*IsSigned=*/ true, /*IsReplace=*/ false);
9479   SDValue FIST = Vals.first, StackSlot = Vals.second;
9480   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9481   if (!FIST.getNode()) return Op;
9482
9483   if (StackSlot.getNode())
9484     // Load the result.
9485     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9486                        FIST, StackSlot, MachinePointerInfo(),
9487                        false, false, false, 0);
9488
9489   // The node is the result.
9490   return FIST;
9491 }
9492
9493 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9494                                            SelectionDAG &DAG) const {
9495   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9496     /*IsSigned=*/ false, /*IsReplace=*/ false);
9497   SDValue FIST = Vals.first, StackSlot = Vals.second;
9498   assert(FIST.getNode() && "Unexpected failure");
9499
9500   if (StackSlot.getNode())
9501     // Load the result.
9502     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9503                        FIST, StackSlot, MachinePointerInfo(),
9504                        false, false, false, 0);
9505
9506   // The node is the result.
9507   return FIST;
9508 }
9509
9510 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9511   SDLoc DL(Op);
9512   MVT VT = Op.getSimpleValueType();
9513   SDValue In = Op.getOperand(0);
9514   MVT SVT = In.getSimpleValueType();
9515
9516   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9517
9518   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9519                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9520                                  In, DAG.getUNDEF(SVT)));
9521 }
9522
9523 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9524   LLVMContext *Context = DAG.getContext();
9525   SDLoc dl(Op);
9526   MVT VT = Op.getSimpleValueType();
9527   MVT EltVT = VT;
9528   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9529   if (VT.isVector()) {
9530     EltVT = VT.getVectorElementType();
9531     NumElts = VT.getVectorNumElements();
9532   }
9533   Constant *C;
9534   if (EltVT == MVT::f64)
9535     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9536                                           APInt(64, ~(1ULL << 63))));
9537   else
9538     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9539                                           APInt(32, ~(1U << 31))));
9540   C = ConstantVector::getSplat(NumElts, C);
9541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9542   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9543   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9544   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9545                              MachinePointerInfo::getConstantPool(),
9546                              false, false, false, Alignment);
9547   if (VT.isVector()) {
9548     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9549     return DAG.getNode(ISD::BITCAST, dl, VT,
9550                        DAG.getNode(ISD::AND, dl, ANDVT,
9551                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9552                                                Op.getOperand(0)),
9553                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9554   }
9555   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9556 }
9557
9558 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9559   LLVMContext *Context = DAG.getContext();
9560   SDLoc dl(Op);
9561   MVT VT = Op.getSimpleValueType();
9562   MVT EltVT = VT;
9563   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9564   if (VT.isVector()) {
9565     EltVT = VT.getVectorElementType();
9566     NumElts = VT.getVectorNumElements();
9567   }
9568   Constant *C;
9569   if (EltVT == MVT::f64)
9570     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9571                                           APInt(64, 1ULL << 63)));
9572   else
9573     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9574                                           APInt(32, 1U << 31)));
9575   C = ConstantVector::getSplat(NumElts, C);
9576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9577   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9578   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9579   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9580                              MachinePointerInfo::getConstantPool(),
9581                              false, false, false, Alignment);
9582   if (VT.isVector()) {
9583     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9584     return DAG.getNode(ISD::BITCAST, dl, VT,
9585                        DAG.getNode(ISD::XOR, dl, XORVT,
9586                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9587                                                Op.getOperand(0)),
9588                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9589   }
9590
9591   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9592 }
9593
9594 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9595   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9596   LLVMContext *Context = DAG.getContext();
9597   SDValue Op0 = Op.getOperand(0);
9598   SDValue Op1 = Op.getOperand(1);
9599   SDLoc dl(Op);
9600   MVT VT = Op.getSimpleValueType();
9601   MVT SrcVT = Op1.getSimpleValueType();
9602
9603   // If second operand is smaller, extend it first.
9604   if (SrcVT.bitsLT(VT)) {
9605     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9606     SrcVT = VT;
9607   }
9608   // And if it is bigger, shrink it first.
9609   if (SrcVT.bitsGT(VT)) {
9610     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9611     SrcVT = VT;
9612   }
9613
9614   // At this point the operands and the result should have the same
9615   // type, and that won't be f80 since that is not custom lowered.
9616
9617   // First get the sign bit of second operand.
9618   SmallVector<Constant*,4> CV;
9619   if (SrcVT == MVT::f64) {
9620     const fltSemantics &Sem = APFloat::IEEEdouble;
9621     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9622     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9623   } else {
9624     const fltSemantics &Sem = APFloat::IEEEsingle;
9625     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9626     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9627     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9628     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9629   }
9630   Constant *C = ConstantVector::get(CV);
9631   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9632   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9633                               MachinePointerInfo::getConstantPool(),
9634                               false, false, false, 16);
9635   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9636
9637   // Shift sign bit right or left if the two operands have different types.
9638   if (SrcVT.bitsGT(VT)) {
9639     // Op0 is MVT::f32, Op1 is MVT::f64.
9640     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9641     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9642                           DAG.getConstant(32, MVT::i32));
9643     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9644     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9645                           DAG.getIntPtrConstant(0));
9646   }
9647
9648   // Clear first operand sign bit.
9649   CV.clear();
9650   if (VT == MVT::f64) {
9651     const fltSemantics &Sem = APFloat::IEEEdouble;
9652     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9653                                                    APInt(64, ~(1ULL << 63)))));
9654     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9655   } else {
9656     const fltSemantics &Sem = APFloat::IEEEsingle;
9657     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9658                                                    APInt(32, ~(1U << 31)))));
9659     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9660     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9661     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9662   }
9663   C = ConstantVector::get(CV);
9664   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9665   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9666                               MachinePointerInfo::getConstantPool(),
9667                               false, false, false, 16);
9668   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9669
9670   // Or the value with the sign bit.
9671   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9672 }
9673
9674 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9675   SDValue N0 = Op.getOperand(0);
9676   SDLoc dl(Op);
9677   MVT VT = Op.getSimpleValueType();
9678
9679   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9680   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9681                                   DAG.getConstant(1, VT));
9682   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9683 }
9684
9685 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9686 //
9687 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9688                                       SelectionDAG &DAG) {
9689   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9690
9691   if (!Subtarget->hasSSE41())
9692     return SDValue();
9693
9694   if (!Op->hasOneUse())
9695     return SDValue();
9696
9697   SDNode *N = Op.getNode();
9698   SDLoc DL(N);
9699
9700   SmallVector<SDValue, 8> Opnds;
9701   DenseMap<SDValue, unsigned> VecInMap;
9702   SmallVector<SDValue, 8> VecIns;
9703   EVT VT = MVT::Other;
9704
9705   // Recognize a special case where a vector is casted into wide integer to
9706   // test all 0s.
9707   Opnds.push_back(N->getOperand(0));
9708   Opnds.push_back(N->getOperand(1));
9709
9710   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9711     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9712     // BFS traverse all OR'd operands.
9713     if (I->getOpcode() == ISD::OR) {
9714       Opnds.push_back(I->getOperand(0));
9715       Opnds.push_back(I->getOperand(1));
9716       // Re-evaluate the number of nodes to be traversed.
9717       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9718       continue;
9719     }
9720
9721     // Quit if a non-EXTRACT_VECTOR_ELT
9722     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9723       return SDValue();
9724
9725     // Quit if without a constant index.
9726     SDValue Idx = I->getOperand(1);
9727     if (!isa<ConstantSDNode>(Idx))
9728       return SDValue();
9729
9730     SDValue ExtractedFromVec = I->getOperand(0);
9731     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9732     if (M == VecInMap.end()) {
9733       VT = ExtractedFromVec.getValueType();
9734       // Quit if not 128/256-bit vector.
9735       if (!VT.is128BitVector() && !VT.is256BitVector())
9736         return SDValue();
9737       // Quit if not the same type.
9738       if (VecInMap.begin() != VecInMap.end() &&
9739           VT != VecInMap.begin()->first.getValueType())
9740         return SDValue();
9741       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9742       VecIns.push_back(ExtractedFromVec);
9743     }
9744     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9745   }
9746
9747   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9748          "Not extracted from 128-/256-bit vector.");
9749
9750   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9751
9752   for (DenseMap<SDValue, unsigned>::const_iterator
9753         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9754     // Quit if not all elements are used.
9755     if (I->second != FullMask)
9756       return SDValue();
9757   }
9758
9759   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9760
9761   // Cast all vectors into TestVT for PTEST.
9762   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9763     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9764
9765   // If more than one full vectors are evaluated, OR them first before PTEST.
9766   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9767     // Each iteration will OR 2 nodes and append the result until there is only
9768     // 1 node left, i.e. the final OR'd value of all vectors.
9769     SDValue LHS = VecIns[Slot];
9770     SDValue RHS = VecIns[Slot + 1];
9771     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9772   }
9773
9774   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9775                      VecIns.back(), VecIns.back());
9776 }
9777
9778 /// \brief return true if \c Op has a use that doesn't just read flags.
9779 static bool hasNonFlagsUse(SDValue Op) {
9780   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9781        ++UI) {
9782     SDNode *User = *UI;
9783     unsigned UOpNo = UI.getOperandNo();
9784     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9785       // Look pass truncate.
9786       UOpNo = User->use_begin().getOperandNo();
9787       User = *User->use_begin();
9788     }
9789
9790     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9791         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9792       return true;
9793   }
9794   return false;
9795 }
9796
9797 /// Emit nodes that will be selected as "test Op0,Op0", or something
9798 /// equivalent.
9799 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9800                                     SelectionDAG &DAG) const {
9801   if (Op.getValueType() == MVT::i1)
9802     // KORTEST instruction should be selected
9803     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9804                        DAG.getConstant(0, Op.getValueType()));
9805
9806   // CF and OF aren't always set the way we want. Determine which
9807   // of these we need.
9808   bool NeedCF = false;
9809   bool NeedOF = false;
9810   switch (X86CC) {
9811   default: break;
9812   case X86::COND_A: case X86::COND_AE:
9813   case X86::COND_B: case X86::COND_BE:
9814     NeedCF = true;
9815     break;
9816   case X86::COND_G: case X86::COND_GE:
9817   case X86::COND_L: case X86::COND_LE:
9818   case X86::COND_O: case X86::COND_NO:
9819     NeedOF = true;
9820     break;
9821   }
9822   // See if we can use the EFLAGS value from the operand instead of
9823   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9824   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9825   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9826     // Emit a CMP with 0, which is the TEST pattern.
9827     //if (Op.getValueType() == MVT::i1)
9828     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9829     //                     DAG.getConstant(0, MVT::i1));
9830     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9831                        DAG.getConstant(0, Op.getValueType()));
9832   }
9833   unsigned Opcode = 0;
9834   unsigned NumOperands = 0;
9835
9836   // Truncate operations may prevent the merge of the SETCC instruction
9837   // and the arithmetic instruction before it. Attempt to truncate the operands
9838   // of the arithmetic instruction and use a reduced bit-width instruction.
9839   bool NeedTruncation = false;
9840   SDValue ArithOp = Op;
9841   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9842     SDValue Arith = Op->getOperand(0);
9843     // Both the trunc and the arithmetic op need to have one user each.
9844     if (Arith->hasOneUse())
9845       switch (Arith.getOpcode()) {
9846         default: break;
9847         case ISD::ADD:
9848         case ISD::SUB:
9849         case ISD::AND:
9850         case ISD::OR:
9851         case ISD::XOR: {
9852           NeedTruncation = true;
9853           ArithOp = Arith;
9854         }
9855       }
9856   }
9857
9858   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9859   // which may be the result of a CAST.  We use the variable 'Op', which is the
9860   // non-casted variable when we check for possible users.
9861   switch (ArithOp.getOpcode()) {
9862   case ISD::ADD:
9863     // Due to an isel shortcoming, be conservative if this add is likely to be
9864     // selected as part of a load-modify-store instruction. When the root node
9865     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9866     // uses of other nodes in the match, such as the ADD in this case. This
9867     // leads to the ADD being left around and reselected, with the result being
9868     // two adds in the output.  Alas, even if none our users are stores, that
9869     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9870     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9871     // climbing the DAG back to the root, and it doesn't seem to be worth the
9872     // effort.
9873     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9874          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9875       if (UI->getOpcode() != ISD::CopyToReg &&
9876           UI->getOpcode() != ISD::SETCC &&
9877           UI->getOpcode() != ISD::STORE)
9878         goto default_case;
9879
9880     if (ConstantSDNode *C =
9881         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9882       // An add of one will be selected as an INC.
9883       if (C->getAPIntValue() == 1) {
9884         Opcode = X86ISD::INC;
9885         NumOperands = 1;
9886         break;
9887       }
9888
9889       // An add of negative one (subtract of one) will be selected as a DEC.
9890       if (C->getAPIntValue().isAllOnesValue()) {
9891         Opcode = X86ISD::DEC;
9892         NumOperands = 1;
9893         break;
9894       }
9895     }
9896
9897     // Otherwise use a regular EFLAGS-setting add.
9898     Opcode = X86ISD::ADD;
9899     NumOperands = 2;
9900     break;
9901   case ISD::SHL:
9902   case ISD::SRL:
9903     // If we have a constant logical shift that's only used in a comparison
9904     // against zero turn it into an equivalent AND. This allows turning it into
9905     // a TEST instruction later.
9906     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9907         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9908       EVT VT = Op.getValueType();
9909       unsigned BitWidth = VT.getSizeInBits();
9910       unsigned ShAmt = Op->getConstantOperandVal(1);
9911       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9912         break;
9913       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9914                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9915                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9916       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9917         break;
9918       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9919                                 DAG.getConstant(Mask, VT));
9920       DAG.ReplaceAllUsesWith(Op, New);
9921       Op = New;
9922     }
9923     break;
9924
9925   case ISD::AND:
9926     // If the primary and result isn't used, don't bother using X86ISD::AND,
9927     // because a TEST instruction will be better.
9928     if (!hasNonFlagsUse(Op))
9929       break;
9930     // FALL THROUGH
9931   case ISD::SUB:
9932   case ISD::OR:
9933   case ISD::XOR:
9934     // Due to the ISEL shortcoming noted above, be conservative if this op is
9935     // likely to be selected as part of a load-modify-store instruction.
9936     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9937            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9938       if (UI->getOpcode() == ISD::STORE)
9939         goto default_case;
9940
9941     // Otherwise use a regular EFLAGS-setting instruction.
9942     switch (ArithOp.getOpcode()) {
9943     default: llvm_unreachable("unexpected operator!");
9944     case ISD::SUB: Opcode = X86ISD::SUB; break;
9945     case ISD::XOR: Opcode = X86ISD::XOR; break;
9946     case ISD::AND: Opcode = X86ISD::AND; break;
9947     case ISD::OR: {
9948       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9949         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9950         if (EFLAGS.getNode())
9951           return EFLAGS;
9952       }
9953       Opcode = X86ISD::OR;
9954       break;
9955     }
9956     }
9957
9958     NumOperands = 2;
9959     break;
9960   case X86ISD::ADD:
9961   case X86ISD::SUB:
9962   case X86ISD::INC:
9963   case X86ISD::DEC:
9964   case X86ISD::OR:
9965   case X86ISD::XOR:
9966   case X86ISD::AND:
9967     return SDValue(Op.getNode(), 1);
9968   default:
9969   default_case:
9970     break;
9971   }
9972
9973   // If we found that truncation is beneficial, perform the truncation and
9974   // update 'Op'.
9975   if (NeedTruncation) {
9976     EVT VT = Op.getValueType();
9977     SDValue WideVal = Op->getOperand(0);
9978     EVT WideVT = WideVal.getValueType();
9979     unsigned ConvertedOp = 0;
9980     // Use a target machine opcode to prevent further DAGCombine
9981     // optimizations that may separate the arithmetic operations
9982     // from the setcc node.
9983     switch (WideVal.getOpcode()) {
9984       default: break;
9985       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9986       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9987       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9988       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9989       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9990     }
9991
9992     if (ConvertedOp) {
9993       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9994       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9995         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9996         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9997         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9998       }
9999     }
10000   }
10001
10002   if (Opcode == 0)
10003     // Emit a CMP with 0, which is the TEST pattern.
10004     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10005                        DAG.getConstant(0, Op.getValueType()));
10006
10007   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10008   SmallVector<SDValue, 4> Ops;
10009   for (unsigned i = 0; i != NumOperands; ++i)
10010     Ops.push_back(Op.getOperand(i));
10011
10012   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
10013   DAG.ReplaceAllUsesWith(Op, New);
10014   return SDValue(New.getNode(), 1);
10015 }
10016
10017 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10018 /// equivalent.
10019 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10020                                    SDLoc dl, SelectionDAG &DAG) const {
10021   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10022     if (C->getAPIntValue() == 0)
10023       return EmitTest(Op0, X86CC, dl, DAG);
10024
10025      if (Op0.getValueType() == MVT::i1)
10026        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10027   }
10028  
10029   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10030        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10031     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10032     // This avoids subregister aliasing issues. Keep the smaller reference 
10033     // if we're optimizing for size, however, as that'll allow better folding 
10034     // of memory operations.
10035     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10036         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10037              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10038         !Subtarget->isAtom()) {
10039       unsigned ExtendOp =
10040           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10041       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10042       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10043     }
10044     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10045     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10046     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10047                               Op0, Op1);
10048     return SDValue(Sub.getNode(), 1);
10049   }
10050   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10051 }
10052
10053 /// Convert a comparison if required by the subtarget.
10054 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10055                                                  SelectionDAG &DAG) const {
10056   // If the subtarget does not support the FUCOMI instruction, floating-point
10057   // comparisons have to be converted.
10058   if (Subtarget->hasCMov() ||
10059       Cmp.getOpcode() != X86ISD::CMP ||
10060       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10061       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10062     return Cmp;
10063
10064   // The instruction selector will select an FUCOM instruction instead of
10065   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10066   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10067   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10068   SDLoc dl(Cmp);
10069   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10070   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10071   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10072                             DAG.getConstant(8, MVT::i8));
10073   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10074   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10075 }
10076
10077 static bool isAllOnes(SDValue V) {
10078   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10079   return C && C->isAllOnesValue();
10080 }
10081
10082 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10083 /// if it's possible.
10084 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10085                                      SDLoc dl, SelectionDAG &DAG) const {
10086   SDValue Op0 = And.getOperand(0);
10087   SDValue Op1 = And.getOperand(1);
10088   if (Op0.getOpcode() == ISD::TRUNCATE)
10089     Op0 = Op0.getOperand(0);
10090   if (Op1.getOpcode() == ISD::TRUNCATE)
10091     Op1 = Op1.getOperand(0);
10092
10093   SDValue LHS, RHS;
10094   if (Op1.getOpcode() == ISD::SHL)
10095     std::swap(Op0, Op1);
10096   if (Op0.getOpcode() == ISD::SHL) {
10097     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10098       if (And00C->getZExtValue() == 1) {
10099         // If we looked past a truncate, check that it's only truncating away
10100         // known zeros.
10101         unsigned BitWidth = Op0.getValueSizeInBits();
10102         unsigned AndBitWidth = And.getValueSizeInBits();
10103         if (BitWidth > AndBitWidth) {
10104           APInt Zeros, Ones;
10105           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10106           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10107             return SDValue();
10108         }
10109         LHS = Op1;
10110         RHS = Op0.getOperand(1);
10111       }
10112   } else if (Op1.getOpcode() == ISD::Constant) {
10113     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10114     uint64_t AndRHSVal = AndRHS->getZExtValue();
10115     SDValue AndLHS = Op0;
10116
10117     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10118       LHS = AndLHS.getOperand(0);
10119       RHS = AndLHS.getOperand(1);
10120     }
10121
10122     // Use BT if the immediate can't be encoded in a TEST instruction.
10123     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10124       LHS = AndLHS;
10125       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10126     }
10127   }
10128
10129   if (LHS.getNode()) {
10130     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10131     // instruction.  Since the shift amount is in-range-or-undefined, we know
10132     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10133     // the encoding for the i16 version is larger than the i32 version.
10134     // Also promote i16 to i32 for performance / code size reason.
10135     if (LHS.getValueType() == MVT::i8 ||
10136         LHS.getValueType() == MVT::i16)
10137       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10138
10139     // If the operand types disagree, extend the shift amount to match.  Since
10140     // BT ignores high bits (like shifts) we can use anyextend.
10141     if (LHS.getValueType() != RHS.getValueType())
10142       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10143
10144     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10145     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10146     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10147                        DAG.getConstant(Cond, MVT::i8), BT);
10148   }
10149
10150   return SDValue();
10151 }
10152
10153 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10154 /// mask CMPs.
10155 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10156                               SDValue &Op1) {
10157   unsigned SSECC;
10158   bool Swap = false;
10159
10160   // SSE Condition code mapping:
10161   //  0 - EQ
10162   //  1 - LT
10163   //  2 - LE
10164   //  3 - UNORD
10165   //  4 - NEQ
10166   //  5 - NLT
10167   //  6 - NLE
10168   //  7 - ORD
10169   switch (SetCCOpcode) {
10170   default: llvm_unreachable("Unexpected SETCC condition");
10171   case ISD::SETOEQ:
10172   case ISD::SETEQ:  SSECC = 0; break;
10173   case ISD::SETOGT:
10174   case ISD::SETGT:  Swap = true; // Fallthrough
10175   case ISD::SETLT:
10176   case ISD::SETOLT: SSECC = 1; break;
10177   case ISD::SETOGE:
10178   case ISD::SETGE:  Swap = true; // Fallthrough
10179   case ISD::SETLE:
10180   case ISD::SETOLE: SSECC = 2; break;
10181   case ISD::SETUO:  SSECC = 3; break;
10182   case ISD::SETUNE:
10183   case ISD::SETNE:  SSECC = 4; break;
10184   case ISD::SETULE: Swap = true; // Fallthrough
10185   case ISD::SETUGE: SSECC = 5; break;
10186   case ISD::SETULT: Swap = true; // Fallthrough
10187   case ISD::SETUGT: SSECC = 6; break;
10188   case ISD::SETO:   SSECC = 7; break;
10189   case ISD::SETUEQ:
10190   case ISD::SETONE: SSECC = 8; break;
10191   }
10192   if (Swap)
10193     std::swap(Op0, Op1);
10194
10195   return SSECC;
10196 }
10197
10198 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10199 // ones, and then concatenate the result back.
10200 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10201   MVT VT = Op.getSimpleValueType();
10202
10203   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10204          "Unsupported value type for operation");
10205
10206   unsigned NumElems = VT.getVectorNumElements();
10207   SDLoc dl(Op);
10208   SDValue CC = Op.getOperand(2);
10209
10210   // Extract the LHS vectors
10211   SDValue LHS = Op.getOperand(0);
10212   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10213   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10214
10215   // Extract the RHS vectors
10216   SDValue RHS = Op.getOperand(1);
10217   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10218   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10219
10220   // Issue the operation on the smaller types and concatenate the result back
10221   MVT EltVT = VT.getVectorElementType();
10222   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10223   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10224                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10225                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10226 }
10227
10228 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10229                                      const X86Subtarget *Subtarget) {
10230   SDValue Op0 = Op.getOperand(0);
10231   SDValue Op1 = Op.getOperand(1);
10232   SDValue CC = Op.getOperand(2);
10233   MVT VT = Op.getSimpleValueType();
10234   SDLoc dl(Op);
10235
10236   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10237          Op.getValueType().getScalarType() == MVT::i1 &&
10238          "Cannot set masked compare for this operation");
10239
10240   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10241   unsigned  Opc = 0;
10242   bool Unsigned = false;
10243   bool Swap = false;
10244   unsigned SSECC;
10245   switch (SetCCOpcode) {
10246   default: llvm_unreachable("Unexpected SETCC condition");
10247   case ISD::SETNE:  SSECC = 4; break;
10248   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10249   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10250   case ISD::SETLT:  Swap = true; //fall-through
10251   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10252   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10253   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10254   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10255   case ISD::SETULE: Unsigned = true; //fall-through
10256   case ISD::SETLE:  SSECC = 2; break;
10257   }
10258
10259   if (Swap)
10260     std::swap(Op0, Op1);
10261   if (Opc)
10262     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10263   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10264   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10265                      DAG.getConstant(SSECC, MVT::i8));
10266 }
10267
10268 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10269 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10270 /// return an empty value.
10271 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10272 {
10273   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10274   if (!BV)
10275     return SDValue();
10276
10277   MVT VT = Op1.getSimpleValueType();
10278   MVT EVT = VT.getVectorElementType();
10279   unsigned n = VT.getVectorNumElements();
10280   SmallVector<SDValue, 8> ULTOp1;
10281
10282   for (unsigned i = 0; i < n; ++i) {
10283     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10284     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10285       return SDValue();
10286
10287     // Avoid underflow.
10288     APInt Val = Elt->getAPIntValue();
10289     if (Val == 0)
10290       return SDValue();
10291
10292     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10293   }
10294
10295   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10296 }
10297
10298 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10299                            SelectionDAG &DAG) {
10300   SDValue Op0 = Op.getOperand(0);
10301   SDValue Op1 = Op.getOperand(1);
10302   SDValue CC = Op.getOperand(2);
10303   MVT VT = Op.getSimpleValueType();
10304   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10305   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10306   SDLoc dl(Op);
10307
10308   if (isFP) {
10309 #ifndef NDEBUG
10310     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10311     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10312 #endif
10313
10314     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10315     unsigned Opc = X86ISD::CMPP;
10316     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10317       assert(VT.getVectorNumElements() <= 16);
10318       Opc = X86ISD::CMPM;
10319     }
10320     // In the two special cases we can't handle, emit two comparisons.
10321     if (SSECC == 8) {
10322       unsigned CC0, CC1;
10323       unsigned CombineOpc;
10324       if (SetCCOpcode == ISD::SETUEQ) {
10325         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10326       } else {
10327         assert(SetCCOpcode == ISD::SETONE);
10328         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10329       }
10330
10331       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10332                                  DAG.getConstant(CC0, MVT::i8));
10333       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10334                                  DAG.getConstant(CC1, MVT::i8));
10335       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10336     }
10337     // Handle all other FP comparisons here.
10338     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10339                        DAG.getConstant(SSECC, MVT::i8));
10340   }
10341
10342   // Break 256-bit integer vector compare into smaller ones.
10343   if (VT.is256BitVector() && !Subtarget->hasInt256())
10344     return Lower256IntVSETCC(Op, DAG);
10345
10346   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10347   EVT OpVT = Op1.getValueType();
10348   if (Subtarget->hasAVX512()) {
10349     if (Op1.getValueType().is512BitVector() ||
10350         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10351       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10352
10353     // In AVX-512 architecture setcc returns mask with i1 elements,
10354     // But there is no compare instruction for i8 and i16 elements.
10355     // We are not talking about 512-bit operands in this case, these
10356     // types are illegal.
10357     if (MaskResult &&
10358         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10359          OpVT.getVectorElementType().getSizeInBits() >= 8))
10360       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10361                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10362   }
10363
10364   // We are handling one of the integer comparisons here.  Since SSE only has
10365   // GT and EQ comparisons for integer, swapping operands and multiple
10366   // operations may be required for some comparisons.
10367   unsigned Opc;
10368   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10369   bool Subus = false;
10370
10371   switch (SetCCOpcode) {
10372   default: llvm_unreachable("Unexpected SETCC condition");
10373   case ISD::SETNE:  Invert = true;
10374   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10375   case ISD::SETLT:  Swap = true;
10376   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10377   case ISD::SETGE:  Swap = true;
10378   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10379                     Invert = true; break;
10380   case ISD::SETULT: Swap = true;
10381   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10382                     FlipSigns = true; break;
10383   case ISD::SETUGE: Swap = true;
10384   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10385                     FlipSigns = true; Invert = true; break;
10386   }
10387
10388   // Special case: Use min/max operations for SETULE/SETUGE
10389   MVT VET = VT.getVectorElementType();
10390   bool hasMinMax =
10391        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10392     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10393
10394   if (hasMinMax) {
10395     switch (SetCCOpcode) {
10396     default: break;
10397     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10398     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10399     }
10400
10401     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10402   }
10403
10404   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10405   if (!MinMax && hasSubus) {
10406     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10407     // Op0 u<= Op1:
10408     //   t = psubus Op0, Op1
10409     //   pcmpeq t, <0..0>
10410     switch (SetCCOpcode) {
10411     default: break;
10412     case ISD::SETULT: {
10413       // If the comparison is against a constant we can turn this into a
10414       // setule.  With psubus, setule does not require a swap.  This is
10415       // beneficial because the constant in the register is no longer
10416       // destructed as the destination so it can be hoisted out of a loop.
10417       // Only do this pre-AVX since vpcmp* is no longer destructive.
10418       if (Subtarget->hasAVX())
10419         break;
10420       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10421       if (ULEOp1.getNode()) {
10422         Op1 = ULEOp1;
10423         Subus = true; Invert = false; Swap = false;
10424       }
10425       break;
10426     }
10427     // Psubus is better than flip-sign because it requires no inversion.
10428     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10429     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10430     }
10431
10432     if (Subus) {
10433       Opc = X86ISD::SUBUS;
10434       FlipSigns = false;
10435     }
10436   }
10437
10438   if (Swap)
10439     std::swap(Op0, Op1);
10440
10441   // Check that the operation in question is available (most are plain SSE2,
10442   // but PCMPGTQ and PCMPEQQ have different requirements).
10443   if (VT == MVT::v2i64) {
10444     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10445       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10446
10447       // First cast everything to the right type.
10448       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10449       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10450
10451       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10452       // bits of the inputs before performing those operations. The lower
10453       // compare is always unsigned.
10454       SDValue SB;
10455       if (FlipSigns) {
10456         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10457       } else {
10458         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10459         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10460         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10461                          Sign, Zero, Sign, Zero);
10462       }
10463       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10464       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10465
10466       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10467       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10468       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10469
10470       // Create masks for only the low parts/high parts of the 64 bit integers.
10471       static const int MaskHi[] = { 1, 1, 3, 3 };
10472       static const int MaskLo[] = { 0, 0, 2, 2 };
10473       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10474       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10475       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10476
10477       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10478       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10479
10480       if (Invert)
10481         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10482
10483       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10484     }
10485
10486     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10487       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10488       // pcmpeqd + pshufd + pand.
10489       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10490
10491       // First cast everything to the right type.
10492       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10493       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10494
10495       // Do the compare.
10496       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10497
10498       // Make sure the lower and upper halves are both all-ones.
10499       static const int Mask[] = { 1, 0, 3, 2 };
10500       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10501       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10502
10503       if (Invert)
10504         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10505
10506       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10507     }
10508   }
10509
10510   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10511   // bits of the inputs before performing those operations.
10512   if (FlipSigns) {
10513     EVT EltVT = VT.getVectorElementType();
10514     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10515     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10516     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10517   }
10518
10519   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10520
10521   // If the logical-not of the result is required, perform that now.
10522   if (Invert)
10523     Result = DAG.getNOT(dl, Result, VT);
10524
10525   if (MinMax)
10526     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10527
10528   if (Subus)
10529     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10530                          getZeroVector(VT, Subtarget, DAG, dl));
10531
10532   return Result;
10533 }
10534
10535 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10536
10537   MVT VT = Op.getSimpleValueType();
10538
10539   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10540
10541   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10542          && "SetCC type must be 8-bit or 1-bit integer");
10543   SDValue Op0 = Op.getOperand(0);
10544   SDValue Op1 = Op.getOperand(1);
10545   SDLoc dl(Op);
10546   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10547
10548   // Optimize to BT if possible.
10549   // Lower (X & (1 << N)) == 0 to BT(X, N).
10550   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10551   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10552   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10553       Op1.getOpcode() == ISD::Constant &&
10554       cast<ConstantSDNode>(Op1)->isNullValue() &&
10555       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10556     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10557     if (NewSetCC.getNode())
10558       return NewSetCC;
10559   }
10560
10561   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10562   // these.
10563   if (Op1.getOpcode() == ISD::Constant &&
10564       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10565        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10566       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10567
10568     // If the input is a setcc, then reuse the input setcc or use a new one with
10569     // the inverted condition.
10570     if (Op0.getOpcode() == X86ISD::SETCC) {
10571       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10572       bool Invert = (CC == ISD::SETNE) ^
10573         cast<ConstantSDNode>(Op1)->isNullValue();
10574       if (!Invert)
10575         return Op0;
10576
10577       CCode = X86::GetOppositeBranchCondition(CCode);
10578       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10579                                   DAG.getConstant(CCode, MVT::i8),
10580                                   Op0.getOperand(1));
10581       if (VT == MVT::i1)
10582         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10583       return SetCC;
10584     }
10585   }
10586   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10587       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10588       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10589
10590     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10591     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10592   }
10593
10594   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10595   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10596   if (X86CC == X86::COND_INVALID)
10597     return SDValue();
10598
10599   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10600   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10601   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10602                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10603   if (VT == MVT::i1)
10604     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10605   return SetCC;
10606 }
10607
10608 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10609 static bool isX86LogicalCmp(SDValue Op) {
10610   unsigned Opc = Op.getNode()->getOpcode();
10611   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10612       Opc == X86ISD::SAHF)
10613     return true;
10614   if (Op.getResNo() == 1 &&
10615       (Opc == X86ISD::ADD ||
10616        Opc == X86ISD::SUB ||
10617        Opc == X86ISD::ADC ||
10618        Opc == X86ISD::SBB ||
10619        Opc == X86ISD::SMUL ||
10620        Opc == X86ISD::UMUL ||
10621        Opc == X86ISD::INC ||
10622        Opc == X86ISD::DEC ||
10623        Opc == X86ISD::OR ||
10624        Opc == X86ISD::XOR ||
10625        Opc == X86ISD::AND))
10626     return true;
10627
10628   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10629     return true;
10630
10631   return false;
10632 }
10633
10634 static bool isZero(SDValue V) {
10635   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10636   return C && C->isNullValue();
10637 }
10638
10639 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10640   if (V.getOpcode() != ISD::TRUNCATE)
10641     return false;
10642
10643   SDValue VOp0 = V.getOperand(0);
10644   unsigned InBits = VOp0.getValueSizeInBits();
10645   unsigned Bits = V.getValueSizeInBits();
10646   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10647 }
10648
10649 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10650   bool addTest = true;
10651   SDValue Cond  = Op.getOperand(0);
10652   SDValue Op1 = Op.getOperand(1);
10653   SDValue Op2 = Op.getOperand(2);
10654   SDLoc DL(Op);
10655   EVT VT = Op1.getValueType();
10656   SDValue CC;
10657
10658   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10659   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10660   // sequence later on.
10661   if (Cond.getOpcode() == ISD::SETCC &&
10662       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10663        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10664       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10665     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10666     int SSECC = translateX86FSETCC(
10667         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10668
10669     if (SSECC != 8) {
10670       if (Subtarget->hasAVX512()) {
10671         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10672                                   DAG.getConstant(SSECC, MVT::i8));
10673         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10674       }
10675       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10676                                 DAG.getConstant(SSECC, MVT::i8));
10677       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10678       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10679       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10680     }
10681   }
10682
10683   if (Cond.getOpcode() == ISD::SETCC) {
10684     SDValue NewCond = LowerSETCC(Cond, DAG);
10685     if (NewCond.getNode())
10686       Cond = NewCond;
10687   }
10688
10689   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10690   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10691   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10692   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10693   if (Cond.getOpcode() == X86ISD::SETCC &&
10694       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10695       isZero(Cond.getOperand(1).getOperand(1))) {
10696     SDValue Cmp = Cond.getOperand(1);
10697
10698     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10699
10700     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10701         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10702       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10703
10704       SDValue CmpOp0 = Cmp.getOperand(0);
10705       // Apply further optimizations for special cases
10706       // (select (x != 0), -1, 0) -> neg & sbb
10707       // (select (x == 0), 0, -1) -> neg & sbb
10708       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10709         if (YC->isNullValue() &&
10710             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10711           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10712           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10713                                     DAG.getConstant(0, CmpOp0.getValueType()),
10714                                     CmpOp0);
10715           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10716                                     DAG.getConstant(X86::COND_B, MVT::i8),
10717                                     SDValue(Neg.getNode(), 1));
10718           return Res;
10719         }
10720
10721       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10722                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10723       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10724
10725       SDValue Res =   // Res = 0 or -1.
10726         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10727                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10728
10729       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10730         Res = DAG.getNOT(DL, Res, Res.getValueType());
10731
10732       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10733       if (!N2C || !N2C->isNullValue())
10734         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10735       return Res;
10736     }
10737   }
10738
10739   // Look past (and (setcc_carry (cmp ...)), 1).
10740   if (Cond.getOpcode() == ISD::AND &&
10741       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10742     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10743     if (C && C->getAPIntValue() == 1)
10744       Cond = Cond.getOperand(0);
10745   }
10746
10747   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10748   // setting operand in place of the X86ISD::SETCC.
10749   unsigned CondOpcode = Cond.getOpcode();
10750   if (CondOpcode == X86ISD::SETCC ||
10751       CondOpcode == X86ISD::SETCC_CARRY) {
10752     CC = Cond.getOperand(0);
10753
10754     SDValue Cmp = Cond.getOperand(1);
10755     unsigned Opc = Cmp.getOpcode();
10756     MVT VT = Op.getSimpleValueType();
10757
10758     bool IllegalFPCMov = false;
10759     if (VT.isFloatingPoint() && !VT.isVector() &&
10760         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10761       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10762
10763     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10764         Opc == X86ISD::BT) { // FIXME
10765       Cond = Cmp;
10766       addTest = false;
10767     }
10768   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10769              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10770              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10771               Cond.getOperand(0).getValueType() != MVT::i8)) {
10772     SDValue LHS = Cond.getOperand(0);
10773     SDValue RHS = Cond.getOperand(1);
10774     unsigned X86Opcode;
10775     unsigned X86Cond;
10776     SDVTList VTs;
10777     switch (CondOpcode) {
10778     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10779     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10780     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10781     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10782     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10783     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10784     default: llvm_unreachable("unexpected overflowing operator");
10785     }
10786     if (CondOpcode == ISD::UMULO)
10787       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10788                           MVT::i32);
10789     else
10790       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10791
10792     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10793
10794     if (CondOpcode == ISD::UMULO)
10795       Cond = X86Op.getValue(2);
10796     else
10797       Cond = X86Op.getValue(1);
10798
10799     CC = DAG.getConstant(X86Cond, MVT::i8);
10800     addTest = false;
10801   }
10802
10803   if (addTest) {
10804     // Look pass the truncate if the high bits are known zero.
10805     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10806         Cond = Cond.getOperand(0);
10807
10808     // We know the result of AND is compared against zero. Try to match
10809     // it to BT.
10810     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10811       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10812       if (NewSetCC.getNode()) {
10813         CC = NewSetCC.getOperand(0);
10814         Cond = NewSetCC.getOperand(1);
10815         addTest = false;
10816       }
10817     }
10818   }
10819
10820   if (addTest) {
10821     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10822     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10823   }
10824
10825   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10826   // a <  b ?  0 : -1 -> RES = setcc_carry
10827   // a >= b ? -1 :  0 -> RES = setcc_carry
10828   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10829   if (Cond.getOpcode() == X86ISD::SUB) {
10830     Cond = ConvertCmpIfNecessary(Cond, DAG);
10831     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10832
10833     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10834         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10835       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10836                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10837       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10838         return DAG.getNOT(DL, Res, Res.getValueType());
10839       return Res;
10840     }
10841   }
10842
10843   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10844   // widen the cmov and push the truncate through. This avoids introducing a new
10845   // branch during isel and doesn't add any extensions.
10846   if (Op.getValueType() == MVT::i8 &&
10847       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10848     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10849     if (T1.getValueType() == T2.getValueType() &&
10850         // Blacklist CopyFromReg to avoid partial register stalls.
10851         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10852       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10853       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10854       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10855     }
10856   }
10857
10858   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10859   // condition is true.
10860   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10861   SDValue Ops[] = { Op2, Op1, CC, Cond };
10862   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10863 }
10864
10865 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10866   MVT VT = Op->getSimpleValueType(0);
10867   SDValue In = Op->getOperand(0);
10868   MVT InVT = In.getSimpleValueType();
10869   SDLoc dl(Op);
10870
10871   unsigned int NumElts = VT.getVectorNumElements();
10872   if (NumElts != 8 && NumElts != 16)
10873     return SDValue();
10874
10875   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10876     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10877
10878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10879   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10880
10881   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10882   Constant *C = ConstantInt::get(*DAG.getContext(),
10883     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10884
10885   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10886   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10887   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10888                           MachinePointerInfo::getConstantPool(),
10889                           false, false, false, Alignment);
10890   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10891   if (VT.is512BitVector())
10892     return Brcst;
10893   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10894 }
10895
10896 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10897                                 SelectionDAG &DAG) {
10898   MVT VT = Op->getSimpleValueType(0);
10899   SDValue In = Op->getOperand(0);
10900   MVT InVT = In.getSimpleValueType();
10901   SDLoc dl(Op);
10902
10903   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10904     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10905
10906   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10907       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10908       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10909     return SDValue();
10910
10911   if (Subtarget->hasInt256())
10912     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10913
10914   // Optimize vectors in AVX mode
10915   // Sign extend  v8i16 to v8i32 and
10916   //              v4i32 to v4i64
10917   //
10918   // Divide input vector into two parts
10919   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10920   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10921   // concat the vectors to original VT
10922
10923   unsigned NumElems = InVT.getVectorNumElements();
10924   SDValue Undef = DAG.getUNDEF(InVT);
10925
10926   SmallVector<int,8> ShufMask1(NumElems, -1);
10927   for (unsigned i = 0; i != NumElems/2; ++i)
10928     ShufMask1[i] = i;
10929
10930   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10931
10932   SmallVector<int,8> ShufMask2(NumElems, -1);
10933   for (unsigned i = 0; i != NumElems/2; ++i)
10934     ShufMask2[i] = i + NumElems/2;
10935
10936   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10937
10938   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10939                                 VT.getVectorNumElements()/2);
10940
10941   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10942   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10943
10944   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10945 }
10946
10947 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10948 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10949 // from the AND / OR.
10950 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10951   Opc = Op.getOpcode();
10952   if (Opc != ISD::OR && Opc != ISD::AND)
10953     return false;
10954   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10955           Op.getOperand(0).hasOneUse() &&
10956           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10957           Op.getOperand(1).hasOneUse());
10958 }
10959
10960 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10961 // 1 and that the SETCC node has a single use.
10962 static bool isXor1OfSetCC(SDValue Op) {
10963   if (Op.getOpcode() != ISD::XOR)
10964     return false;
10965   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10966   if (N1C && N1C->getAPIntValue() == 1) {
10967     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10968       Op.getOperand(0).hasOneUse();
10969   }
10970   return false;
10971 }
10972
10973 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10974   bool addTest = true;
10975   SDValue Chain = Op.getOperand(0);
10976   SDValue Cond  = Op.getOperand(1);
10977   SDValue Dest  = Op.getOperand(2);
10978   SDLoc dl(Op);
10979   SDValue CC;
10980   bool Inverted = false;
10981
10982   if (Cond.getOpcode() == ISD::SETCC) {
10983     // Check for setcc([su]{add,sub,mul}o == 0).
10984     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10985         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10986         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10987         Cond.getOperand(0).getResNo() == 1 &&
10988         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10989          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10990          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10991          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10992          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10993          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10994       Inverted = true;
10995       Cond = Cond.getOperand(0);
10996     } else {
10997       SDValue NewCond = LowerSETCC(Cond, DAG);
10998       if (NewCond.getNode())
10999         Cond = NewCond;
11000     }
11001   }
11002 #if 0
11003   // FIXME: LowerXALUO doesn't handle these!!
11004   else if (Cond.getOpcode() == X86ISD::ADD  ||
11005            Cond.getOpcode() == X86ISD::SUB  ||
11006            Cond.getOpcode() == X86ISD::SMUL ||
11007            Cond.getOpcode() == X86ISD::UMUL)
11008     Cond = LowerXALUO(Cond, DAG);
11009 #endif
11010
11011   // Look pass (and (setcc_carry (cmp ...)), 1).
11012   if (Cond.getOpcode() == ISD::AND &&
11013       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11014     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11015     if (C && C->getAPIntValue() == 1)
11016       Cond = Cond.getOperand(0);
11017   }
11018
11019   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11020   // setting operand in place of the X86ISD::SETCC.
11021   unsigned CondOpcode = Cond.getOpcode();
11022   if (CondOpcode == X86ISD::SETCC ||
11023       CondOpcode == X86ISD::SETCC_CARRY) {
11024     CC = Cond.getOperand(0);
11025
11026     SDValue Cmp = Cond.getOperand(1);
11027     unsigned Opc = Cmp.getOpcode();
11028     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11029     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11030       Cond = Cmp;
11031       addTest = false;
11032     } else {
11033       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11034       default: break;
11035       case X86::COND_O:
11036       case X86::COND_B:
11037         // These can only come from an arithmetic instruction with overflow,
11038         // e.g. SADDO, UADDO.
11039         Cond = Cond.getNode()->getOperand(1);
11040         addTest = false;
11041         break;
11042       }
11043     }
11044   }
11045   CondOpcode = Cond.getOpcode();
11046   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11047       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11048       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11049        Cond.getOperand(0).getValueType() != MVT::i8)) {
11050     SDValue LHS = Cond.getOperand(0);
11051     SDValue RHS = Cond.getOperand(1);
11052     unsigned X86Opcode;
11053     unsigned X86Cond;
11054     SDVTList VTs;
11055     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11056     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11057     // X86ISD::INC).
11058     switch (CondOpcode) {
11059     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11060     case ISD::SADDO:
11061       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11062         if (C->isOne()) {
11063           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11064           break;
11065         }
11066       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11067     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11068     case ISD::SSUBO:
11069       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11070         if (C->isOne()) {
11071           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11072           break;
11073         }
11074       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11075     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11076     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11077     default: llvm_unreachable("unexpected overflowing operator");
11078     }
11079     if (Inverted)
11080       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11081     if (CondOpcode == ISD::UMULO)
11082       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11083                           MVT::i32);
11084     else
11085       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11086
11087     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11088
11089     if (CondOpcode == ISD::UMULO)
11090       Cond = X86Op.getValue(2);
11091     else
11092       Cond = X86Op.getValue(1);
11093
11094     CC = DAG.getConstant(X86Cond, MVT::i8);
11095     addTest = false;
11096   } else {
11097     unsigned CondOpc;
11098     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11099       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11100       if (CondOpc == ISD::OR) {
11101         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11102         // two branches instead of an explicit OR instruction with a
11103         // separate test.
11104         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11105             isX86LogicalCmp(Cmp)) {
11106           CC = Cond.getOperand(0).getOperand(0);
11107           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11108                               Chain, Dest, CC, Cmp);
11109           CC = Cond.getOperand(1).getOperand(0);
11110           Cond = Cmp;
11111           addTest = false;
11112         }
11113       } else { // ISD::AND
11114         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11115         // two branches instead of an explicit AND instruction with a
11116         // separate test. However, we only do this if this block doesn't
11117         // have a fall-through edge, because this requires an explicit
11118         // jmp when the condition is false.
11119         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11120             isX86LogicalCmp(Cmp) &&
11121             Op.getNode()->hasOneUse()) {
11122           X86::CondCode CCode =
11123             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11124           CCode = X86::GetOppositeBranchCondition(CCode);
11125           CC = DAG.getConstant(CCode, MVT::i8);
11126           SDNode *User = *Op.getNode()->use_begin();
11127           // Look for an unconditional branch following this conditional branch.
11128           // We need this because we need to reverse the successors in order
11129           // to implement FCMP_OEQ.
11130           if (User->getOpcode() == ISD::BR) {
11131             SDValue FalseBB = User->getOperand(1);
11132             SDNode *NewBR =
11133               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11134             assert(NewBR == User);
11135             (void)NewBR;
11136             Dest = FalseBB;
11137
11138             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11139                                 Chain, Dest, CC, Cmp);
11140             X86::CondCode CCode =
11141               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11142             CCode = X86::GetOppositeBranchCondition(CCode);
11143             CC = DAG.getConstant(CCode, MVT::i8);
11144             Cond = Cmp;
11145             addTest = false;
11146           }
11147         }
11148       }
11149     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11150       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11151       // It should be transformed during dag combiner except when the condition
11152       // is set by a arithmetics with overflow node.
11153       X86::CondCode CCode =
11154         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11155       CCode = X86::GetOppositeBranchCondition(CCode);
11156       CC = DAG.getConstant(CCode, MVT::i8);
11157       Cond = Cond.getOperand(0).getOperand(1);
11158       addTest = false;
11159     } else if (Cond.getOpcode() == ISD::SETCC &&
11160                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11161       // For FCMP_OEQ, we can emit
11162       // two branches instead of an explicit AND instruction with a
11163       // separate test. However, we only do this if this block doesn't
11164       // have a fall-through edge, because this requires an explicit
11165       // jmp when the condition is false.
11166       if (Op.getNode()->hasOneUse()) {
11167         SDNode *User = *Op.getNode()->use_begin();
11168         // Look for an unconditional branch following this conditional branch.
11169         // We need this because we need to reverse the successors in order
11170         // to implement FCMP_OEQ.
11171         if (User->getOpcode() == ISD::BR) {
11172           SDValue FalseBB = User->getOperand(1);
11173           SDNode *NewBR =
11174             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11175           assert(NewBR == User);
11176           (void)NewBR;
11177           Dest = FalseBB;
11178
11179           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11180                                     Cond.getOperand(0), Cond.getOperand(1));
11181           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11182           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11183           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11184                               Chain, Dest, CC, Cmp);
11185           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11186           Cond = Cmp;
11187           addTest = false;
11188         }
11189       }
11190     } else if (Cond.getOpcode() == ISD::SETCC &&
11191                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11192       // For FCMP_UNE, we can emit
11193       // two branches instead of an explicit AND instruction with a
11194       // separate test. However, we only do this if this block doesn't
11195       // have a fall-through edge, because this requires an explicit
11196       // jmp when the condition is false.
11197       if (Op.getNode()->hasOneUse()) {
11198         SDNode *User = *Op.getNode()->use_begin();
11199         // Look for an unconditional branch following this conditional branch.
11200         // We need this because we need to reverse the successors in order
11201         // to implement FCMP_UNE.
11202         if (User->getOpcode() == ISD::BR) {
11203           SDValue FalseBB = User->getOperand(1);
11204           SDNode *NewBR =
11205             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11206           assert(NewBR == User);
11207           (void)NewBR;
11208
11209           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11210                                     Cond.getOperand(0), Cond.getOperand(1));
11211           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11212           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11213           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11214                               Chain, Dest, CC, Cmp);
11215           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11216           Cond = Cmp;
11217           addTest = false;
11218           Dest = FalseBB;
11219         }
11220       }
11221     }
11222   }
11223
11224   if (addTest) {
11225     // Look pass the truncate if the high bits are known zero.
11226     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11227         Cond = Cond.getOperand(0);
11228
11229     // We know the result of AND is compared against zero. Try to match
11230     // it to BT.
11231     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11232       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11233       if (NewSetCC.getNode()) {
11234         CC = NewSetCC.getOperand(0);
11235         Cond = NewSetCC.getOperand(1);
11236         addTest = false;
11237       }
11238     }
11239   }
11240
11241   if (addTest) {
11242     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11243     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11244   }
11245   Cond = ConvertCmpIfNecessary(Cond, DAG);
11246   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11247                      Chain, Dest, CC, Cond);
11248 }
11249
11250 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11251 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11252 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11253 // that the guard pages used by the OS virtual memory manager are allocated in
11254 // correct sequence.
11255 SDValue
11256 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11257                                            SelectionDAG &DAG) const {
11258   MachineFunction &MF = DAG.getMachineFunction();
11259   bool SplitStack = MF.shouldSplitStack();
11260   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11261                SplitStack;
11262   SDLoc dl(Op);
11263
11264   if (!Lower) {
11265     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11266     SDNode* Node = Op.getNode();
11267
11268     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11269     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11270         " not tell us which reg is the stack pointer!");
11271     EVT VT = Node->getValueType(0);
11272     SDValue Tmp1 = SDValue(Node, 0);
11273     SDValue Tmp2 = SDValue(Node, 1);
11274     SDValue Tmp3 = Node->getOperand(2);
11275     SDValue Chain = Tmp1.getOperand(0);
11276
11277     // Chain the dynamic stack allocation so that it doesn't modify the stack
11278     // pointer when other instructions are using the stack.
11279     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11280         SDLoc(Node));
11281
11282     SDValue Size = Tmp2.getOperand(1);
11283     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11284     Chain = SP.getValue(1);
11285     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11286     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11287     unsigned StackAlign = TFI.getStackAlignment();
11288     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11289     if (Align > StackAlign)
11290       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11291           DAG.getConstant(-(uint64_t)Align, VT));
11292     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11293
11294     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11295         DAG.getIntPtrConstant(0, true), SDValue(),
11296         SDLoc(Node));
11297
11298     SDValue Ops[2] = { Tmp1, Tmp2 };
11299     return DAG.getMergeValues(Ops, 2, dl);
11300   }
11301
11302   // Get the inputs.
11303   SDValue Chain = Op.getOperand(0);
11304   SDValue Size  = Op.getOperand(1);
11305   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11306   EVT VT = Op.getNode()->getValueType(0);
11307
11308   bool Is64Bit = Subtarget->is64Bit();
11309   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11310
11311   if (SplitStack) {
11312     MachineRegisterInfo &MRI = MF.getRegInfo();
11313
11314     if (Is64Bit) {
11315       // The 64 bit implementation of segmented stacks needs to clobber both r10
11316       // r11. This makes it impossible to use it along with nested parameters.
11317       const Function *F = MF.getFunction();
11318
11319       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11320            I != E; ++I)
11321         if (I->hasNestAttr())
11322           report_fatal_error("Cannot use segmented stacks with functions that "
11323                              "have nested arguments.");
11324     }
11325
11326     const TargetRegisterClass *AddrRegClass =
11327       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11328     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11329     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11330     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11331                                 DAG.getRegister(Vreg, SPTy));
11332     SDValue Ops1[2] = { Value, Chain };
11333     return DAG.getMergeValues(Ops1, 2, dl);
11334   } else {
11335     SDValue Flag;
11336     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11337
11338     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11339     Flag = Chain.getValue(1);
11340     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11341
11342     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11343
11344     const X86RegisterInfo *RegInfo =
11345       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11346     unsigned SPReg = RegInfo->getStackRegister();
11347     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11348     Chain = SP.getValue(1);
11349
11350     if (Align) {
11351       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11352                        DAG.getConstant(-(uint64_t)Align, VT));
11353       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11354     }
11355
11356     SDValue Ops1[2] = { SP, Chain };
11357     return DAG.getMergeValues(Ops1, 2, dl);
11358   }
11359 }
11360
11361 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11362   MachineFunction &MF = DAG.getMachineFunction();
11363   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11364
11365   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11366   SDLoc DL(Op);
11367
11368   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11369     // vastart just stores the address of the VarArgsFrameIndex slot into the
11370     // memory location argument.
11371     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11372                                    getPointerTy());
11373     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11374                         MachinePointerInfo(SV), false, false, 0);
11375   }
11376
11377   // __va_list_tag:
11378   //   gp_offset         (0 - 6 * 8)
11379   //   fp_offset         (48 - 48 + 8 * 16)
11380   //   overflow_arg_area (point to parameters coming in memory).
11381   //   reg_save_area
11382   SmallVector<SDValue, 8> MemOps;
11383   SDValue FIN = Op.getOperand(1);
11384   // Store gp_offset
11385   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11386                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11387                                                MVT::i32),
11388                                FIN, MachinePointerInfo(SV), false, false, 0);
11389   MemOps.push_back(Store);
11390
11391   // Store fp_offset
11392   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11393                     FIN, DAG.getIntPtrConstant(4));
11394   Store = DAG.getStore(Op.getOperand(0), DL,
11395                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11396                                        MVT::i32),
11397                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11398   MemOps.push_back(Store);
11399
11400   // Store ptr to overflow_arg_area
11401   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11402                     FIN, DAG.getIntPtrConstant(4));
11403   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11404                                     getPointerTy());
11405   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11406                        MachinePointerInfo(SV, 8),
11407                        false, false, 0);
11408   MemOps.push_back(Store);
11409
11410   // Store ptr to reg_save_area.
11411   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11412                     FIN, DAG.getIntPtrConstant(8));
11413   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11414                                     getPointerTy());
11415   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11416                        MachinePointerInfo(SV, 16), false, false, 0);
11417   MemOps.push_back(Store);
11418   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11419                      &MemOps[0], MemOps.size());
11420 }
11421
11422 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11423   assert(Subtarget->is64Bit() &&
11424          "LowerVAARG only handles 64-bit va_arg!");
11425   assert((Subtarget->isTargetLinux() ||
11426           Subtarget->isTargetDarwin()) &&
11427           "Unhandled target in LowerVAARG");
11428   assert(Op.getNode()->getNumOperands() == 4);
11429   SDValue Chain = Op.getOperand(0);
11430   SDValue SrcPtr = Op.getOperand(1);
11431   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11432   unsigned Align = Op.getConstantOperandVal(3);
11433   SDLoc dl(Op);
11434
11435   EVT ArgVT = Op.getNode()->getValueType(0);
11436   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11437   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11438   uint8_t ArgMode;
11439
11440   // Decide which area this value should be read from.
11441   // TODO: Implement the AMD64 ABI in its entirety. This simple
11442   // selection mechanism works only for the basic types.
11443   if (ArgVT == MVT::f80) {
11444     llvm_unreachable("va_arg for f80 not yet implemented");
11445   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11446     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11447   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11448     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11449   } else {
11450     llvm_unreachable("Unhandled argument type in LowerVAARG");
11451   }
11452
11453   if (ArgMode == 2) {
11454     // Sanity Check: Make sure using fp_offset makes sense.
11455     assert(!getTargetMachine().Options.UseSoftFloat &&
11456            !(DAG.getMachineFunction()
11457                 .getFunction()->getAttributes()
11458                 .hasAttribute(AttributeSet::FunctionIndex,
11459                               Attribute::NoImplicitFloat)) &&
11460            Subtarget->hasSSE1());
11461   }
11462
11463   // Insert VAARG_64 node into the DAG
11464   // VAARG_64 returns two values: Variable Argument Address, Chain
11465   SmallVector<SDValue, 11> InstOps;
11466   InstOps.push_back(Chain);
11467   InstOps.push_back(SrcPtr);
11468   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11469   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11470   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11471   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11472   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11473                                           VTs, &InstOps[0], InstOps.size(),
11474                                           MVT::i64,
11475                                           MachinePointerInfo(SV),
11476                                           /*Align=*/0,
11477                                           /*Volatile=*/false,
11478                                           /*ReadMem=*/true,
11479                                           /*WriteMem=*/true);
11480   Chain = VAARG.getValue(1);
11481
11482   // Load the next argument and return it
11483   return DAG.getLoad(ArgVT, dl,
11484                      Chain,
11485                      VAARG,
11486                      MachinePointerInfo(),
11487                      false, false, false, 0);
11488 }
11489
11490 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11491                            SelectionDAG &DAG) {
11492   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11493   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11494   SDValue Chain = Op.getOperand(0);
11495   SDValue DstPtr = Op.getOperand(1);
11496   SDValue SrcPtr = Op.getOperand(2);
11497   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11498   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11499   SDLoc DL(Op);
11500
11501   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11502                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11503                        false,
11504                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11505 }
11506
11507 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11508 // amount is a constant. Takes immediate version of shift as input.
11509 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11510                                           SDValue SrcOp, uint64_t ShiftAmt,
11511                                           SelectionDAG &DAG) {
11512   MVT ElementType = VT.getVectorElementType();
11513
11514   // Check for ShiftAmt >= element width
11515   if (ShiftAmt >= ElementType.getSizeInBits()) {
11516     if (Opc == X86ISD::VSRAI)
11517       ShiftAmt = ElementType.getSizeInBits() - 1;
11518     else
11519       return DAG.getConstant(0, VT);
11520   }
11521
11522   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11523          && "Unknown target vector shift-by-constant node");
11524
11525   // Fold this packed vector shift into a build vector if SrcOp is a
11526   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11527   if (VT == SrcOp.getSimpleValueType() &&
11528       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11529     SmallVector<SDValue, 8> Elts;
11530     unsigned NumElts = SrcOp->getNumOperands();
11531     ConstantSDNode *ND;
11532
11533     switch(Opc) {
11534     default: llvm_unreachable(0);
11535     case X86ISD::VSHLI:
11536       for (unsigned i=0; i!=NumElts; ++i) {
11537         SDValue CurrentOp = SrcOp->getOperand(i);
11538         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11539           Elts.push_back(CurrentOp);
11540           continue;
11541         }
11542         ND = cast<ConstantSDNode>(CurrentOp);
11543         const APInt &C = ND->getAPIntValue();
11544         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11545       }
11546       break;
11547     case X86ISD::VSRLI:
11548       for (unsigned i=0; i!=NumElts; ++i) {
11549         SDValue CurrentOp = SrcOp->getOperand(i);
11550         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11551           Elts.push_back(CurrentOp);
11552           continue;
11553         }
11554         ND = cast<ConstantSDNode>(CurrentOp);
11555         const APInt &C = ND->getAPIntValue();
11556         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11557       }
11558       break;
11559     case X86ISD::VSRAI:
11560       for (unsigned i=0; i!=NumElts; ++i) {
11561         SDValue CurrentOp = SrcOp->getOperand(i);
11562         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11563           Elts.push_back(CurrentOp);
11564           continue;
11565         }
11566         ND = cast<ConstantSDNode>(CurrentOp);
11567         const APInt &C = ND->getAPIntValue();
11568         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11569       }
11570       break;
11571     }
11572
11573     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11574   }
11575
11576   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11577 }
11578
11579 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11580 // may or may not be a constant. Takes immediate version of shift as input.
11581 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11582                                    SDValue SrcOp, SDValue ShAmt,
11583                                    SelectionDAG &DAG) {
11584   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11585
11586   // Catch shift-by-constant.
11587   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11588     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11589                                       CShAmt->getZExtValue(), DAG);
11590
11591   // Change opcode to non-immediate version
11592   switch (Opc) {
11593     default: llvm_unreachable("Unknown target vector shift node");
11594     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11595     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11596     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11597   }
11598
11599   // Need to build a vector containing shift amount
11600   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11601   SDValue ShOps[4];
11602   ShOps[0] = ShAmt;
11603   ShOps[1] = DAG.getConstant(0, MVT::i32);
11604   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11605   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11606
11607   // The return type has to be a 128-bit type with the same element
11608   // type as the input type.
11609   MVT EltVT = VT.getVectorElementType();
11610   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11611
11612   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11613   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11614 }
11615
11616 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11617   SDLoc dl(Op);
11618   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11619   switch (IntNo) {
11620   default: return SDValue();    // Don't custom lower most intrinsics.
11621   // Comparison intrinsics.
11622   case Intrinsic::x86_sse_comieq_ss:
11623   case Intrinsic::x86_sse_comilt_ss:
11624   case Intrinsic::x86_sse_comile_ss:
11625   case Intrinsic::x86_sse_comigt_ss:
11626   case Intrinsic::x86_sse_comige_ss:
11627   case Intrinsic::x86_sse_comineq_ss:
11628   case Intrinsic::x86_sse_ucomieq_ss:
11629   case Intrinsic::x86_sse_ucomilt_ss:
11630   case Intrinsic::x86_sse_ucomile_ss:
11631   case Intrinsic::x86_sse_ucomigt_ss:
11632   case Intrinsic::x86_sse_ucomige_ss:
11633   case Intrinsic::x86_sse_ucomineq_ss:
11634   case Intrinsic::x86_sse2_comieq_sd:
11635   case Intrinsic::x86_sse2_comilt_sd:
11636   case Intrinsic::x86_sse2_comile_sd:
11637   case Intrinsic::x86_sse2_comigt_sd:
11638   case Intrinsic::x86_sse2_comige_sd:
11639   case Intrinsic::x86_sse2_comineq_sd:
11640   case Intrinsic::x86_sse2_ucomieq_sd:
11641   case Intrinsic::x86_sse2_ucomilt_sd:
11642   case Intrinsic::x86_sse2_ucomile_sd:
11643   case Intrinsic::x86_sse2_ucomigt_sd:
11644   case Intrinsic::x86_sse2_ucomige_sd:
11645   case Intrinsic::x86_sse2_ucomineq_sd: {
11646     unsigned Opc;
11647     ISD::CondCode CC;
11648     switch (IntNo) {
11649     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11650     case Intrinsic::x86_sse_comieq_ss:
11651     case Intrinsic::x86_sse2_comieq_sd:
11652       Opc = X86ISD::COMI;
11653       CC = ISD::SETEQ;
11654       break;
11655     case Intrinsic::x86_sse_comilt_ss:
11656     case Intrinsic::x86_sse2_comilt_sd:
11657       Opc = X86ISD::COMI;
11658       CC = ISD::SETLT;
11659       break;
11660     case Intrinsic::x86_sse_comile_ss:
11661     case Intrinsic::x86_sse2_comile_sd:
11662       Opc = X86ISD::COMI;
11663       CC = ISD::SETLE;
11664       break;
11665     case Intrinsic::x86_sse_comigt_ss:
11666     case Intrinsic::x86_sse2_comigt_sd:
11667       Opc = X86ISD::COMI;
11668       CC = ISD::SETGT;
11669       break;
11670     case Intrinsic::x86_sse_comige_ss:
11671     case Intrinsic::x86_sse2_comige_sd:
11672       Opc = X86ISD::COMI;
11673       CC = ISD::SETGE;
11674       break;
11675     case Intrinsic::x86_sse_comineq_ss:
11676     case Intrinsic::x86_sse2_comineq_sd:
11677       Opc = X86ISD::COMI;
11678       CC = ISD::SETNE;
11679       break;
11680     case Intrinsic::x86_sse_ucomieq_ss:
11681     case Intrinsic::x86_sse2_ucomieq_sd:
11682       Opc = X86ISD::UCOMI;
11683       CC = ISD::SETEQ;
11684       break;
11685     case Intrinsic::x86_sse_ucomilt_ss:
11686     case Intrinsic::x86_sse2_ucomilt_sd:
11687       Opc = X86ISD::UCOMI;
11688       CC = ISD::SETLT;
11689       break;
11690     case Intrinsic::x86_sse_ucomile_ss:
11691     case Intrinsic::x86_sse2_ucomile_sd:
11692       Opc = X86ISD::UCOMI;
11693       CC = ISD::SETLE;
11694       break;
11695     case Intrinsic::x86_sse_ucomigt_ss:
11696     case Intrinsic::x86_sse2_ucomigt_sd:
11697       Opc = X86ISD::UCOMI;
11698       CC = ISD::SETGT;
11699       break;
11700     case Intrinsic::x86_sse_ucomige_ss:
11701     case Intrinsic::x86_sse2_ucomige_sd:
11702       Opc = X86ISD::UCOMI;
11703       CC = ISD::SETGE;
11704       break;
11705     case Intrinsic::x86_sse_ucomineq_ss:
11706     case Intrinsic::x86_sse2_ucomineq_sd:
11707       Opc = X86ISD::UCOMI;
11708       CC = ISD::SETNE;
11709       break;
11710     }
11711
11712     SDValue LHS = Op.getOperand(1);
11713     SDValue RHS = Op.getOperand(2);
11714     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11715     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11716     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11717     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11718                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11719     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11720   }
11721
11722   // Arithmetic intrinsics.
11723   case Intrinsic::x86_sse2_pmulu_dq:
11724   case Intrinsic::x86_avx2_pmulu_dq:
11725     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11726                        Op.getOperand(1), Op.getOperand(2));
11727
11728   // SSE2/AVX2 sub with unsigned saturation intrinsics
11729   case Intrinsic::x86_sse2_psubus_b:
11730   case Intrinsic::x86_sse2_psubus_w:
11731   case Intrinsic::x86_avx2_psubus_b:
11732   case Intrinsic::x86_avx2_psubus_w:
11733     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11734                        Op.getOperand(1), Op.getOperand(2));
11735
11736   // SSE3/AVX horizontal add/sub intrinsics
11737   case Intrinsic::x86_sse3_hadd_ps:
11738   case Intrinsic::x86_sse3_hadd_pd:
11739   case Intrinsic::x86_avx_hadd_ps_256:
11740   case Intrinsic::x86_avx_hadd_pd_256:
11741   case Intrinsic::x86_sse3_hsub_ps:
11742   case Intrinsic::x86_sse3_hsub_pd:
11743   case Intrinsic::x86_avx_hsub_ps_256:
11744   case Intrinsic::x86_avx_hsub_pd_256:
11745   case Intrinsic::x86_ssse3_phadd_w_128:
11746   case Intrinsic::x86_ssse3_phadd_d_128:
11747   case Intrinsic::x86_avx2_phadd_w:
11748   case Intrinsic::x86_avx2_phadd_d:
11749   case Intrinsic::x86_ssse3_phsub_w_128:
11750   case Intrinsic::x86_ssse3_phsub_d_128:
11751   case Intrinsic::x86_avx2_phsub_w:
11752   case Intrinsic::x86_avx2_phsub_d: {
11753     unsigned Opcode;
11754     switch (IntNo) {
11755     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11756     case Intrinsic::x86_sse3_hadd_ps:
11757     case Intrinsic::x86_sse3_hadd_pd:
11758     case Intrinsic::x86_avx_hadd_ps_256:
11759     case Intrinsic::x86_avx_hadd_pd_256:
11760       Opcode = X86ISD::FHADD;
11761       break;
11762     case Intrinsic::x86_sse3_hsub_ps:
11763     case Intrinsic::x86_sse3_hsub_pd:
11764     case Intrinsic::x86_avx_hsub_ps_256:
11765     case Intrinsic::x86_avx_hsub_pd_256:
11766       Opcode = X86ISD::FHSUB;
11767       break;
11768     case Intrinsic::x86_ssse3_phadd_w_128:
11769     case Intrinsic::x86_ssse3_phadd_d_128:
11770     case Intrinsic::x86_avx2_phadd_w:
11771     case Intrinsic::x86_avx2_phadd_d:
11772       Opcode = X86ISD::HADD;
11773       break;
11774     case Intrinsic::x86_ssse3_phsub_w_128:
11775     case Intrinsic::x86_ssse3_phsub_d_128:
11776     case Intrinsic::x86_avx2_phsub_w:
11777     case Intrinsic::x86_avx2_phsub_d:
11778       Opcode = X86ISD::HSUB;
11779       break;
11780     }
11781     return DAG.getNode(Opcode, dl, Op.getValueType(),
11782                        Op.getOperand(1), Op.getOperand(2));
11783   }
11784
11785   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11786   case Intrinsic::x86_sse2_pmaxu_b:
11787   case Intrinsic::x86_sse41_pmaxuw:
11788   case Intrinsic::x86_sse41_pmaxud:
11789   case Intrinsic::x86_avx2_pmaxu_b:
11790   case Intrinsic::x86_avx2_pmaxu_w:
11791   case Intrinsic::x86_avx2_pmaxu_d:
11792   case Intrinsic::x86_sse2_pminu_b:
11793   case Intrinsic::x86_sse41_pminuw:
11794   case Intrinsic::x86_sse41_pminud:
11795   case Intrinsic::x86_avx2_pminu_b:
11796   case Intrinsic::x86_avx2_pminu_w:
11797   case Intrinsic::x86_avx2_pminu_d:
11798   case Intrinsic::x86_sse41_pmaxsb:
11799   case Intrinsic::x86_sse2_pmaxs_w:
11800   case Intrinsic::x86_sse41_pmaxsd:
11801   case Intrinsic::x86_avx2_pmaxs_b:
11802   case Intrinsic::x86_avx2_pmaxs_w:
11803   case Intrinsic::x86_avx2_pmaxs_d:
11804   case Intrinsic::x86_sse41_pminsb:
11805   case Intrinsic::x86_sse2_pmins_w:
11806   case Intrinsic::x86_sse41_pminsd:
11807   case Intrinsic::x86_avx2_pmins_b:
11808   case Intrinsic::x86_avx2_pmins_w:
11809   case Intrinsic::x86_avx2_pmins_d: {
11810     unsigned Opcode;
11811     switch (IntNo) {
11812     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11813     case Intrinsic::x86_sse2_pmaxu_b:
11814     case Intrinsic::x86_sse41_pmaxuw:
11815     case Intrinsic::x86_sse41_pmaxud:
11816     case Intrinsic::x86_avx2_pmaxu_b:
11817     case Intrinsic::x86_avx2_pmaxu_w:
11818     case Intrinsic::x86_avx2_pmaxu_d:
11819       Opcode = X86ISD::UMAX;
11820       break;
11821     case Intrinsic::x86_sse2_pminu_b:
11822     case Intrinsic::x86_sse41_pminuw:
11823     case Intrinsic::x86_sse41_pminud:
11824     case Intrinsic::x86_avx2_pminu_b:
11825     case Intrinsic::x86_avx2_pminu_w:
11826     case Intrinsic::x86_avx2_pminu_d:
11827       Opcode = X86ISD::UMIN;
11828       break;
11829     case Intrinsic::x86_sse41_pmaxsb:
11830     case Intrinsic::x86_sse2_pmaxs_w:
11831     case Intrinsic::x86_sse41_pmaxsd:
11832     case Intrinsic::x86_avx2_pmaxs_b:
11833     case Intrinsic::x86_avx2_pmaxs_w:
11834     case Intrinsic::x86_avx2_pmaxs_d:
11835       Opcode = X86ISD::SMAX;
11836       break;
11837     case Intrinsic::x86_sse41_pminsb:
11838     case Intrinsic::x86_sse2_pmins_w:
11839     case Intrinsic::x86_sse41_pminsd:
11840     case Intrinsic::x86_avx2_pmins_b:
11841     case Intrinsic::x86_avx2_pmins_w:
11842     case Intrinsic::x86_avx2_pmins_d:
11843       Opcode = X86ISD::SMIN;
11844       break;
11845     }
11846     return DAG.getNode(Opcode, dl, Op.getValueType(),
11847                        Op.getOperand(1), Op.getOperand(2));
11848   }
11849
11850   // SSE/SSE2/AVX floating point max/min intrinsics.
11851   case Intrinsic::x86_sse_max_ps:
11852   case Intrinsic::x86_sse2_max_pd:
11853   case Intrinsic::x86_avx_max_ps_256:
11854   case Intrinsic::x86_avx_max_pd_256:
11855   case Intrinsic::x86_sse_min_ps:
11856   case Intrinsic::x86_sse2_min_pd:
11857   case Intrinsic::x86_avx_min_ps_256:
11858   case Intrinsic::x86_avx_min_pd_256: {
11859     unsigned Opcode;
11860     switch (IntNo) {
11861     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11862     case Intrinsic::x86_sse_max_ps:
11863     case Intrinsic::x86_sse2_max_pd:
11864     case Intrinsic::x86_avx_max_ps_256:
11865     case Intrinsic::x86_avx_max_pd_256:
11866       Opcode = X86ISD::FMAX;
11867       break;
11868     case Intrinsic::x86_sse_min_ps:
11869     case Intrinsic::x86_sse2_min_pd:
11870     case Intrinsic::x86_avx_min_ps_256:
11871     case Intrinsic::x86_avx_min_pd_256:
11872       Opcode = X86ISD::FMIN;
11873       break;
11874     }
11875     return DAG.getNode(Opcode, dl, Op.getValueType(),
11876                        Op.getOperand(1), Op.getOperand(2));
11877   }
11878
11879   // AVX2 variable shift intrinsics
11880   case Intrinsic::x86_avx2_psllv_d:
11881   case Intrinsic::x86_avx2_psllv_q:
11882   case Intrinsic::x86_avx2_psllv_d_256:
11883   case Intrinsic::x86_avx2_psllv_q_256:
11884   case Intrinsic::x86_avx2_psrlv_d:
11885   case Intrinsic::x86_avx2_psrlv_q:
11886   case Intrinsic::x86_avx2_psrlv_d_256:
11887   case Intrinsic::x86_avx2_psrlv_q_256:
11888   case Intrinsic::x86_avx2_psrav_d:
11889   case Intrinsic::x86_avx2_psrav_d_256: {
11890     unsigned Opcode;
11891     switch (IntNo) {
11892     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11893     case Intrinsic::x86_avx2_psllv_d:
11894     case Intrinsic::x86_avx2_psllv_q:
11895     case Intrinsic::x86_avx2_psllv_d_256:
11896     case Intrinsic::x86_avx2_psllv_q_256:
11897       Opcode = ISD::SHL;
11898       break;
11899     case Intrinsic::x86_avx2_psrlv_d:
11900     case Intrinsic::x86_avx2_psrlv_q:
11901     case Intrinsic::x86_avx2_psrlv_d_256:
11902     case Intrinsic::x86_avx2_psrlv_q_256:
11903       Opcode = ISD::SRL;
11904       break;
11905     case Intrinsic::x86_avx2_psrav_d:
11906     case Intrinsic::x86_avx2_psrav_d_256:
11907       Opcode = ISD::SRA;
11908       break;
11909     }
11910     return DAG.getNode(Opcode, dl, Op.getValueType(),
11911                        Op.getOperand(1), Op.getOperand(2));
11912   }
11913
11914   case Intrinsic::x86_ssse3_pshuf_b_128:
11915   case Intrinsic::x86_avx2_pshuf_b:
11916     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11917                        Op.getOperand(1), Op.getOperand(2));
11918
11919   case Intrinsic::x86_ssse3_psign_b_128:
11920   case Intrinsic::x86_ssse3_psign_w_128:
11921   case Intrinsic::x86_ssse3_psign_d_128:
11922   case Intrinsic::x86_avx2_psign_b:
11923   case Intrinsic::x86_avx2_psign_w:
11924   case Intrinsic::x86_avx2_psign_d:
11925     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11926                        Op.getOperand(1), Op.getOperand(2));
11927
11928   case Intrinsic::x86_sse41_insertps:
11929     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11930                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11931
11932   case Intrinsic::x86_avx_vperm2f128_ps_256:
11933   case Intrinsic::x86_avx_vperm2f128_pd_256:
11934   case Intrinsic::x86_avx_vperm2f128_si_256:
11935   case Intrinsic::x86_avx2_vperm2i128:
11936     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11937                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11938
11939   case Intrinsic::x86_avx2_permd:
11940   case Intrinsic::x86_avx2_permps:
11941     // Operands intentionally swapped. Mask is last operand to intrinsic,
11942     // but second operand for node/instruction.
11943     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11944                        Op.getOperand(2), Op.getOperand(1));
11945
11946   case Intrinsic::x86_sse_sqrt_ps:
11947   case Intrinsic::x86_sse2_sqrt_pd:
11948   case Intrinsic::x86_avx_sqrt_ps_256:
11949   case Intrinsic::x86_avx_sqrt_pd_256:
11950     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11951
11952   // ptest and testp intrinsics. The intrinsic these come from are designed to
11953   // return an integer value, not just an instruction so lower it to the ptest
11954   // or testp pattern and a setcc for the result.
11955   case Intrinsic::x86_sse41_ptestz:
11956   case Intrinsic::x86_sse41_ptestc:
11957   case Intrinsic::x86_sse41_ptestnzc:
11958   case Intrinsic::x86_avx_ptestz_256:
11959   case Intrinsic::x86_avx_ptestc_256:
11960   case Intrinsic::x86_avx_ptestnzc_256:
11961   case Intrinsic::x86_avx_vtestz_ps:
11962   case Intrinsic::x86_avx_vtestc_ps:
11963   case Intrinsic::x86_avx_vtestnzc_ps:
11964   case Intrinsic::x86_avx_vtestz_pd:
11965   case Intrinsic::x86_avx_vtestc_pd:
11966   case Intrinsic::x86_avx_vtestnzc_pd:
11967   case Intrinsic::x86_avx_vtestz_ps_256:
11968   case Intrinsic::x86_avx_vtestc_ps_256:
11969   case Intrinsic::x86_avx_vtestnzc_ps_256:
11970   case Intrinsic::x86_avx_vtestz_pd_256:
11971   case Intrinsic::x86_avx_vtestc_pd_256:
11972   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11973     bool IsTestPacked = false;
11974     unsigned X86CC;
11975     switch (IntNo) {
11976     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11977     case Intrinsic::x86_avx_vtestz_ps:
11978     case Intrinsic::x86_avx_vtestz_pd:
11979     case Intrinsic::x86_avx_vtestz_ps_256:
11980     case Intrinsic::x86_avx_vtestz_pd_256:
11981       IsTestPacked = true; // Fallthrough
11982     case Intrinsic::x86_sse41_ptestz:
11983     case Intrinsic::x86_avx_ptestz_256:
11984       // ZF = 1
11985       X86CC = X86::COND_E;
11986       break;
11987     case Intrinsic::x86_avx_vtestc_ps:
11988     case Intrinsic::x86_avx_vtestc_pd:
11989     case Intrinsic::x86_avx_vtestc_ps_256:
11990     case Intrinsic::x86_avx_vtestc_pd_256:
11991       IsTestPacked = true; // Fallthrough
11992     case Intrinsic::x86_sse41_ptestc:
11993     case Intrinsic::x86_avx_ptestc_256:
11994       // CF = 1
11995       X86CC = X86::COND_B;
11996       break;
11997     case Intrinsic::x86_avx_vtestnzc_ps:
11998     case Intrinsic::x86_avx_vtestnzc_pd:
11999     case Intrinsic::x86_avx_vtestnzc_ps_256:
12000     case Intrinsic::x86_avx_vtestnzc_pd_256:
12001       IsTestPacked = true; // Fallthrough
12002     case Intrinsic::x86_sse41_ptestnzc:
12003     case Intrinsic::x86_avx_ptestnzc_256:
12004       // ZF and CF = 0
12005       X86CC = X86::COND_A;
12006       break;
12007     }
12008
12009     SDValue LHS = Op.getOperand(1);
12010     SDValue RHS = Op.getOperand(2);
12011     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12012     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12013     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12014     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12015     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12016   }
12017   case Intrinsic::x86_avx512_kortestz_w:
12018   case Intrinsic::x86_avx512_kortestc_w: {
12019     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12020     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12021     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12022     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12023     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12024     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12025     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12026   }
12027
12028   // SSE/AVX shift intrinsics
12029   case Intrinsic::x86_sse2_psll_w:
12030   case Intrinsic::x86_sse2_psll_d:
12031   case Intrinsic::x86_sse2_psll_q:
12032   case Intrinsic::x86_avx2_psll_w:
12033   case Intrinsic::x86_avx2_psll_d:
12034   case Intrinsic::x86_avx2_psll_q:
12035   case Intrinsic::x86_sse2_psrl_w:
12036   case Intrinsic::x86_sse2_psrl_d:
12037   case Intrinsic::x86_sse2_psrl_q:
12038   case Intrinsic::x86_avx2_psrl_w:
12039   case Intrinsic::x86_avx2_psrl_d:
12040   case Intrinsic::x86_avx2_psrl_q:
12041   case Intrinsic::x86_sse2_psra_w:
12042   case Intrinsic::x86_sse2_psra_d:
12043   case Intrinsic::x86_avx2_psra_w:
12044   case Intrinsic::x86_avx2_psra_d: {
12045     unsigned Opcode;
12046     switch (IntNo) {
12047     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12048     case Intrinsic::x86_sse2_psll_w:
12049     case Intrinsic::x86_sse2_psll_d:
12050     case Intrinsic::x86_sse2_psll_q:
12051     case Intrinsic::x86_avx2_psll_w:
12052     case Intrinsic::x86_avx2_psll_d:
12053     case Intrinsic::x86_avx2_psll_q:
12054       Opcode = X86ISD::VSHL;
12055       break;
12056     case Intrinsic::x86_sse2_psrl_w:
12057     case Intrinsic::x86_sse2_psrl_d:
12058     case Intrinsic::x86_sse2_psrl_q:
12059     case Intrinsic::x86_avx2_psrl_w:
12060     case Intrinsic::x86_avx2_psrl_d:
12061     case Intrinsic::x86_avx2_psrl_q:
12062       Opcode = X86ISD::VSRL;
12063       break;
12064     case Intrinsic::x86_sse2_psra_w:
12065     case Intrinsic::x86_sse2_psra_d:
12066     case Intrinsic::x86_avx2_psra_w:
12067     case Intrinsic::x86_avx2_psra_d:
12068       Opcode = X86ISD::VSRA;
12069       break;
12070     }
12071     return DAG.getNode(Opcode, dl, Op.getValueType(),
12072                        Op.getOperand(1), Op.getOperand(2));
12073   }
12074
12075   // SSE/AVX immediate shift intrinsics
12076   case Intrinsic::x86_sse2_pslli_w:
12077   case Intrinsic::x86_sse2_pslli_d:
12078   case Intrinsic::x86_sse2_pslli_q:
12079   case Intrinsic::x86_avx2_pslli_w:
12080   case Intrinsic::x86_avx2_pslli_d:
12081   case Intrinsic::x86_avx2_pslli_q:
12082   case Intrinsic::x86_sse2_psrli_w:
12083   case Intrinsic::x86_sse2_psrli_d:
12084   case Intrinsic::x86_sse2_psrli_q:
12085   case Intrinsic::x86_avx2_psrli_w:
12086   case Intrinsic::x86_avx2_psrli_d:
12087   case Intrinsic::x86_avx2_psrli_q:
12088   case Intrinsic::x86_sse2_psrai_w:
12089   case Intrinsic::x86_sse2_psrai_d:
12090   case Intrinsic::x86_avx2_psrai_w:
12091   case Intrinsic::x86_avx2_psrai_d: {
12092     unsigned Opcode;
12093     switch (IntNo) {
12094     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12095     case Intrinsic::x86_sse2_pslli_w:
12096     case Intrinsic::x86_sse2_pslli_d:
12097     case Intrinsic::x86_sse2_pslli_q:
12098     case Intrinsic::x86_avx2_pslli_w:
12099     case Intrinsic::x86_avx2_pslli_d:
12100     case Intrinsic::x86_avx2_pslli_q:
12101       Opcode = X86ISD::VSHLI;
12102       break;
12103     case Intrinsic::x86_sse2_psrli_w:
12104     case Intrinsic::x86_sse2_psrli_d:
12105     case Intrinsic::x86_sse2_psrli_q:
12106     case Intrinsic::x86_avx2_psrli_w:
12107     case Intrinsic::x86_avx2_psrli_d:
12108     case Intrinsic::x86_avx2_psrli_q:
12109       Opcode = X86ISD::VSRLI;
12110       break;
12111     case Intrinsic::x86_sse2_psrai_w:
12112     case Intrinsic::x86_sse2_psrai_d:
12113     case Intrinsic::x86_avx2_psrai_w:
12114     case Intrinsic::x86_avx2_psrai_d:
12115       Opcode = X86ISD::VSRAI;
12116       break;
12117     }
12118     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12119                                Op.getOperand(1), Op.getOperand(2), DAG);
12120   }
12121
12122   case Intrinsic::x86_sse42_pcmpistria128:
12123   case Intrinsic::x86_sse42_pcmpestria128:
12124   case Intrinsic::x86_sse42_pcmpistric128:
12125   case Intrinsic::x86_sse42_pcmpestric128:
12126   case Intrinsic::x86_sse42_pcmpistrio128:
12127   case Intrinsic::x86_sse42_pcmpestrio128:
12128   case Intrinsic::x86_sse42_pcmpistris128:
12129   case Intrinsic::x86_sse42_pcmpestris128:
12130   case Intrinsic::x86_sse42_pcmpistriz128:
12131   case Intrinsic::x86_sse42_pcmpestriz128: {
12132     unsigned Opcode;
12133     unsigned X86CC;
12134     switch (IntNo) {
12135     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12136     case Intrinsic::x86_sse42_pcmpistria128:
12137       Opcode = X86ISD::PCMPISTRI;
12138       X86CC = X86::COND_A;
12139       break;
12140     case Intrinsic::x86_sse42_pcmpestria128:
12141       Opcode = X86ISD::PCMPESTRI;
12142       X86CC = X86::COND_A;
12143       break;
12144     case Intrinsic::x86_sse42_pcmpistric128:
12145       Opcode = X86ISD::PCMPISTRI;
12146       X86CC = X86::COND_B;
12147       break;
12148     case Intrinsic::x86_sse42_pcmpestric128:
12149       Opcode = X86ISD::PCMPESTRI;
12150       X86CC = X86::COND_B;
12151       break;
12152     case Intrinsic::x86_sse42_pcmpistrio128:
12153       Opcode = X86ISD::PCMPISTRI;
12154       X86CC = X86::COND_O;
12155       break;
12156     case Intrinsic::x86_sse42_pcmpestrio128:
12157       Opcode = X86ISD::PCMPESTRI;
12158       X86CC = X86::COND_O;
12159       break;
12160     case Intrinsic::x86_sse42_pcmpistris128:
12161       Opcode = X86ISD::PCMPISTRI;
12162       X86CC = X86::COND_S;
12163       break;
12164     case Intrinsic::x86_sse42_pcmpestris128:
12165       Opcode = X86ISD::PCMPESTRI;
12166       X86CC = X86::COND_S;
12167       break;
12168     case Intrinsic::x86_sse42_pcmpistriz128:
12169       Opcode = X86ISD::PCMPISTRI;
12170       X86CC = X86::COND_E;
12171       break;
12172     case Intrinsic::x86_sse42_pcmpestriz128:
12173       Opcode = X86ISD::PCMPESTRI;
12174       X86CC = X86::COND_E;
12175       break;
12176     }
12177     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12178     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12179     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12180     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12181                                 DAG.getConstant(X86CC, MVT::i8),
12182                                 SDValue(PCMP.getNode(), 1));
12183     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12184   }
12185
12186   case Intrinsic::x86_sse42_pcmpistri128:
12187   case Intrinsic::x86_sse42_pcmpestri128: {
12188     unsigned Opcode;
12189     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12190       Opcode = X86ISD::PCMPISTRI;
12191     else
12192       Opcode = X86ISD::PCMPESTRI;
12193
12194     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12195     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12196     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12197   }
12198   case Intrinsic::x86_fma_vfmadd_ps:
12199   case Intrinsic::x86_fma_vfmadd_pd:
12200   case Intrinsic::x86_fma_vfmsub_ps:
12201   case Intrinsic::x86_fma_vfmsub_pd:
12202   case Intrinsic::x86_fma_vfnmadd_ps:
12203   case Intrinsic::x86_fma_vfnmadd_pd:
12204   case Intrinsic::x86_fma_vfnmsub_ps:
12205   case Intrinsic::x86_fma_vfnmsub_pd:
12206   case Intrinsic::x86_fma_vfmaddsub_ps:
12207   case Intrinsic::x86_fma_vfmaddsub_pd:
12208   case Intrinsic::x86_fma_vfmsubadd_ps:
12209   case Intrinsic::x86_fma_vfmsubadd_pd:
12210   case Intrinsic::x86_fma_vfmadd_ps_256:
12211   case Intrinsic::x86_fma_vfmadd_pd_256:
12212   case Intrinsic::x86_fma_vfmsub_ps_256:
12213   case Intrinsic::x86_fma_vfmsub_pd_256:
12214   case Intrinsic::x86_fma_vfnmadd_ps_256:
12215   case Intrinsic::x86_fma_vfnmadd_pd_256:
12216   case Intrinsic::x86_fma_vfnmsub_ps_256:
12217   case Intrinsic::x86_fma_vfnmsub_pd_256:
12218   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12219   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12220   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12221   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12222   case Intrinsic::x86_fma_vfmadd_ps_512:
12223   case Intrinsic::x86_fma_vfmadd_pd_512:
12224   case Intrinsic::x86_fma_vfmsub_ps_512:
12225   case Intrinsic::x86_fma_vfmsub_pd_512:
12226   case Intrinsic::x86_fma_vfnmadd_ps_512:
12227   case Intrinsic::x86_fma_vfnmadd_pd_512:
12228   case Intrinsic::x86_fma_vfnmsub_ps_512:
12229   case Intrinsic::x86_fma_vfnmsub_pd_512:
12230   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12231   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12232   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12233   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12234     unsigned Opc;
12235     switch (IntNo) {
12236     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12237     case Intrinsic::x86_fma_vfmadd_ps:
12238     case Intrinsic::x86_fma_vfmadd_pd:
12239     case Intrinsic::x86_fma_vfmadd_ps_256:
12240     case Intrinsic::x86_fma_vfmadd_pd_256:
12241     case Intrinsic::x86_fma_vfmadd_ps_512:
12242     case Intrinsic::x86_fma_vfmadd_pd_512:
12243       Opc = X86ISD::FMADD;
12244       break;
12245     case Intrinsic::x86_fma_vfmsub_ps:
12246     case Intrinsic::x86_fma_vfmsub_pd:
12247     case Intrinsic::x86_fma_vfmsub_ps_256:
12248     case Intrinsic::x86_fma_vfmsub_pd_256:
12249     case Intrinsic::x86_fma_vfmsub_ps_512:
12250     case Intrinsic::x86_fma_vfmsub_pd_512:
12251       Opc = X86ISD::FMSUB;
12252       break;
12253     case Intrinsic::x86_fma_vfnmadd_ps:
12254     case Intrinsic::x86_fma_vfnmadd_pd:
12255     case Intrinsic::x86_fma_vfnmadd_ps_256:
12256     case Intrinsic::x86_fma_vfnmadd_pd_256:
12257     case Intrinsic::x86_fma_vfnmadd_ps_512:
12258     case Intrinsic::x86_fma_vfnmadd_pd_512:
12259       Opc = X86ISD::FNMADD;
12260       break;
12261     case Intrinsic::x86_fma_vfnmsub_ps:
12262     case Intrinsic::x86_fma_vfnmsub_pd:
12263     case Intrinsic::x86_fma_vfnmsub_ps_256:
12264     case Intrinsic::x86_fma_vfnmsub_pd_256:
12265     case Intrinsic::x86_fma_vfnmsub_ps_512:
12266     case Intrinsic::x86_fma_vfnmsub_pd_512:
12267       Opc = X86ISD::FNMSUB;
12268       break;
12269     case Intrinsic::x86_fma_vfmaddsub_ps:
12270     case Intrinsic::x86_fma_vfmaddsub_pd:
12271     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12272     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12273     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12274     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12275       Opc = X86ISD::FMADDSUB;
12276       break;
12277     case Intrinsic::x86_fma_vfmsubadd_ps:
12278     case Intrinsic::x86_fma_vfmsubadd_pd:
12279     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12280     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12281     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12282     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12283       Opc = X86ISD::FMSUBADD;
12284       break;
12285     }
12286
12287     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12288                        Op.getOperand(2), Op.getOperand(3));
12289   }
12290   }
12291 }
12292
12293 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12294                              SDValue Base, SDValue Index,
12295                              SDValue ScaleOp, SDValue Chain,
12296                              const X86Subtarget * Subtarget) {
12297   SDLoc dl(Op);
12298   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12299   assert(C && "Invalid scale type");
12300   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12301   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12302   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12303                              Index.getSimpleValueType().getVectorNumElements());
12304   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12305   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12306   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12307   SDValue Segment = DAG.getRegister(0, MVT::i32);
12308   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12309   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12310   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12311   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12312 }
12313
12314 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12315                               SDValue Src, SDValue Mask, SDValue Base,
12316                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12317                               const X86Subtarget * Subtarget) {
12318   SDLoc dl(Op);
12319   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12320   assert(C && "Invalid scale type");
12321   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12322   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12323                              Index.getSimpleValueType().getVectorNumElements());
12324   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12325   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12326   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12327   SDValue Segment = DAG.getRegister(0, MVT::i32);
12328   if (Src.getOpcode() == ISD::UNDEF)
12329     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12330   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12331   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12332   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12333   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12334 }
12335
12336 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12337                               SDValue Src, SDValue Base, SDValue Index,
12338                               SDValue ScaleOp, SDValue Chain) {
12339   SDLoc dl(Op);
12340   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12341   assert(C && "Invalid scale type");
12342   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12343   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12344   SDValue Segment = DAG.getRegister(0, MVT::i32);
12345   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12346                              Index.getSimpleValueType().getVectorNumElements());
12347   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12348   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12349   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12350   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12351   return SDValue(Res, 1);
12352 }
12353
12354 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12355                                SDValue Src, SDValue Mask, SDValue Base,
12356                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12357   SDLoc dl(Op);
12358   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12359   assert(C && "Invalid scale type");
12360   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12361   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12362   SDValue Segment = DAG.getRegister(0, MVT::i32);
12363   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12364                              Index.getSimpleValueType().getVectorNumElements());
12365   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12366   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12367   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12368   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12369   return SDValue(Res, 1);
12370 }
12371
12372 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12373 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12374 // also used to custom lower READCYCLECOUNTER nodes.
12375 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12376                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12377                               SmallVectorImpl<SDValue> &Results) {
12378   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12379   SDValue TheChain = N->getOperand(0);
12380   SDValue rd = DAG.getNode(Opcode, DL, Tys, &TheChain, 1);
12381   SDValue LO, HI;
12382
12383   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12384   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12385   // and the EAX register is loaded with the low-order 32 bits.
12386   if (Subtarget->is64Bit()) {
12387     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12388     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12389                             LO.getValue(2));
12390   } else {
12391     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12392     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12393                             LO.getValue(2));
12394   }
12395   SDValue Chain = HI.getValue(1);
12396
12397   if (Opcode == X86ISD::RDTSCP_DAG) {
12398     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12399
12400     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12401     // the ECX register. Add 'ecx' explicitly to the chain.
12402     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12403                                      HI.getValue(2));
12404     // Explicitly store the content of ECX at the location passed in input
12405     // to the 'rdtscp' intrinsic.
12406     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12407                          MachinePointerInfo(), false, false, 0);
12408   }
12409
12410   if (Subtarget->is64Bit()) {
12411     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12412     // the EAX register is loaded with the low-order 32 bits.
12413     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12414                               DAG.getConstant(32, MVT::i8));
12415     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12416     Results.push_back(Chain);
12417     return;
12418   }
12419
12420   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12421   SDValue Ops[] = { LO, HI };
12422   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops,
12423                              array_lengthof(Ops));
12424   Results.push_back(Pair);
12425   Results.push_back(Chain);
12426 }
12427
12428 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12429                                      SelectionDAG &DAG) {
12430   SmallVector<SDValue, 2> Results;
12431   SDLoc DL(Op);
12432   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12433                           Results);
12434   return DAG.getMergeValues(&Results[0], Results.size(), DL);
12435 }
12436
12437 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12438                                       SelectionDAG &DAG) {
12439   SDLoc dl(Op);
12440   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12441   switch (IntNo) {
12442   default: return SDValue();    // Don't custom lower most intrinsics.
12443
12444   // RDRAND/RDSEED intrinsics.
12445   case Intrinsic::x86_rdrand_16:
12446   case Intrinsic::x86_rdrand_32:
12447   case Intrinsic::x86_rdrand_64:
12448   case Intrinsic::x86_rdseed_16:
12449   case Intrinsic::x86_rdseed_32:
12450   case Intrinsic::x86_rdseed_64: {
12451     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12452                        IntNo == Intrinsic::x86_rdseed_32 ||
12453                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12454                                                             X86ISD::RDRAND;
12455     // Emit the node with the right value type.
12456     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12457     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12458
12459     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12460     // Otherwise return the value from Rand, which is always 0, casted to i32.
12461     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12462                       DAG.getConstant(1, Op->getValueType(1)),
12463                       DAG.getConstant(X86::COND_B, MVT::i32),
12464                       SDValue(Result.getNode(), 1) };
12465     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12466                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12467                                   Ops, array_lengthof(Ops));
12468
12469     // Return { result, isValid, chain }.
12470     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12471                        SDValue(Result.getNode(), 2));
12472   }
12473   //int_gather(index, base, scale);
12474   case Intrinsic::x86_avx512_gather_qpd_512:
12475   case Intrinsic::x86_avx512_gather_qps_512:
12476   case Intrinsic::x86_avx512_gather_dpd_512:
12477   case Intrinsic::x86_avx512_gather_qpi_512:
12478   case Intrinsic::x86_avx512_gather_qpq_512:
12479   case Intrinsic::x86_avx512_gather_dpq_512:
12480   case Intrinsic::x86_avx512_gather_dps_512:
12481   case Intrinsic::x86_avx512_gather_dpi_512: {
12482     unsigned Opc;
12483     switch (IntNo) {
12484     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12485     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12486     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12487     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12488     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12489     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12490     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12491     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12492     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12493     }
12494     SDValue Chain = Op.getOperand(0);
12495     SDValue Index = Op.getOperand(2);
12496     SDValue Base  = Op.getOperand(3);
12497     SDValue Scale = Op.getOperand(4);
12498     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12499   }
12500   //int_gather_mask(v1, mask, index, base, scale);
12501   case Intrinsic::x86_avx512_gather_qps_mask_512:
12502   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12503   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12504   case Intrinsic::x86_avx512_gather_dps_mask_512:
12505   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12506   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12507   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12508   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12509     unsigned Opc;
12510     switch (IntNo) {
12511     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12512     case Intrinsic::x86_avx512_gather_qps_mask_512:
12513       Opc = X86::VGATHERQPSZrm; break;
12514     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12515       Opc = X86::VGATHERQPDZrm; break;
12516     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12517       Opc = X86::VGATHERDPDZrm; break;
12518     case Intrinsic::x86_avx512_gather_dps_mask_512:
12519       Opc = X86::VGATHERDPSZrm; break;
12520     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12521       Opc = X86::VPGATHERQDZrm; break;
12522     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12523       Opc = X86::VPGATHERQQZrm; break;
12524     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12525       Opc = X86::VPGATHERDDZrm; break;
12526     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12527       Opc = X86::VPGATHERDQZrm; break;
12528     }
12529     SDValue Chain = Op.getOperand(0);
12530     SDValue Src   = Op.getOperand(2);
12531     SDValue Mask  = Op.getOperand(3);
12532     SDValue Index = Op.getOperand(4);
12533     SDValue Base  = Op.getOperand(5);
12534     SDValue Scale = Op.getOperand(6);
12535     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12536                           Subtarget);
12537   }
12538   //int_scatter(base, index, v1, scale);
12539   case Intrinsic::x86_avx512_scatter_qpd_512:
12540   case Intrinsic::x86_avx512_scatter_qps_512:
12541   case Intrinsic::x86_avx512_scatter_dpd_512:
12542   case Intrinsic::x86_avx512_scatter_qpi_512:
12543   case Intrinsic::x86_avx512_scatter_qpq_512:
12544   case Intrinsic::x86_avx512_scatter_dpq_512:
12545   case Intrinsic::x86_avx512_scatter_dps_512:
12546   case Intrinsic::x86_avx512_scatter_dpi_512: {
12547     unsigned Opc;
12548     switch (IntNo) {
12549     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12550     case Intrinsic::x86_avx512_scatter_qpd_512:
12551       Opc = X86::VSCATTERQPDZmr; break;
12552     case Intrinsic::x86_avx512_scatter_qps_512:
12553       Opc = X86::VSCATTERQPSZmr; break;
12554     case Intrinsic::x86_avx512_scatter_dpd_512:
12555       Opc = X86::VSCATTERDPDZmr; break;
12556     case Intrinsic::x86_avx512_scatter_dps_512:
12557       Opc = X86::VSCATTERDPSZmr; break;
12558     case Intrinsic::x86_avx512_scatter_qpi_512:
12559       Opc = X86::VPSCATTERQDZmr; break;
12560     case Intrinsic::x86_avx512_scatter_qpq_512:
12561       Opc = X86::VPSCATTERQQZmr; break;
12562     case Intrinsic::x86_avx512_scatter_dpq_512:
12563       Opc = X86::VPSCATTERDQZmr; break;
12564     case Intrinsic::x86_avx512_scatter_dpi_512:
12565       Opc = X86::VPSCATTERDDZmr; break;
12566     }
12567     SDValue Chain = Op.getOperand(0);
12568     SDValue Base  = Op.getOperand(2);
12569     SDValue Index = Op.getOperand(3);
12570     SDValue Src   = Op.getOperand(4);
12571     SDValue Scale = Op.getOperand(5);
12572     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12573   }
12574   //int_scatter_mask(base, mask, index, v1, scale);
12575   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12576   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12577   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12578   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12579   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12580   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12581   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12582   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12583     unsigned Opc;
12584     switch (IntNo) {
12585     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12586     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12587       Opc = X86::VSCATTERQPDZmr; break;
12588     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12589       Opc = X86::VSCATTERQPSZmr; break;
12590     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12591       Opc = X86::VSCATTERDPDZmr; break;
12592     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12593       Opc = X86::VSCATTERDPSZmr; break;
12594     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12595       Opc = X86::VPSCATTERQDZmr; break;
12596     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12597       Opc = X86::VPSCATTERQQZmr; break;
12598     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12599       Opc = X86::VPSCATTERDQZmr; break;
12600     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12601       Opc = X86::VPSCATTERDDZmr; break;
12602     }
12603     SDValue Chain = Op.getOperand(0);
12604     SDValue Base  = Op.getOperand(2);
12605     SDValue Mask  = Op.getOperand(3);
12606     SDValue Index = Op.getOperand(4);
12607     SDValue Src   = Op.getOperand(5);
12608     SDValue Scale = Op.getOperand(6);
12609     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12610   }
12611   // Read Time Stamp Counter (RDTSC).
12612   case Intrinsic::x86_rdtsc:
12613   // Read Time Stamp Counter and Processor ID (RDTSCP).
12614   case Intrinsic::x86_rdtscp: {
12615     unsigned Opc;
12616     switch (IntNo) {
12617     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12618     case Intrinsic::x86_rdtsc:
12619       Opc = X86ISD::RDTSC_DAG; break;
12620     case Intrinsic::x86_rdtscp:
12621       Opc = X86ISD::RDTSCP_DAG; break;
12622     }
12623     SmallVector<SDValue, 2> Results;
12624     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12625     return DAG.getMergeValues(&Results[0], Results.size(), dl);
12626   }
12627   // XTEST intrinsics.
12628   case Intrinsic::x86_xtest: {
12629     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12630     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12631     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12632                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12633                                 InTrans);
12634     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12635     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12636                        Ret, SDValue(InTrans.getNode(), 1));
12637   }
12638   }
12639 }
12640
12641 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12642                                            SelectionDAG &DAG) const {
12643   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12644   MFI->setReturnAddressIsTaken(true);
12645
12646   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12647     return SDValue();
12648
12649   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12650   SDLoc dl(Op);
12651   EVT PtrVT = getPointerTy();
12652
12653   if (Depth > 0) {
12654     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12655     const X86RegisterInfo *RegInfo =
12656       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12657     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12658     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12659                        DAG.getNode(ISD::ADD, dl, PtrVT,
12660                                    FrameAddr, Offset),
12661                        MachinePointerInfo(), false, false, false, 0);
12662   }
12663
12664   // Just load the return address.
12665   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12666   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12667                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12668 }
12669
12670 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12671   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12672   MFI->setFrameAddressIsTaken(true);
12673
12674   EVT VT = Op.getValueType();
12675   SDLoc dl(Op);  // FIXME probably not meaningful
12676   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12677   const X86RegisterInfo *RegInfo =
12678     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12679   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12680   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12681           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12682          "Invalid Frame Register!");
12683   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12684   while (Depth--)
12685     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12686                             MachinePointerInfo(),
12687                             false, false, false, 0);
12688   return FrameAddr;
12689 }
12690
12691 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12692                                                      SelectionDAG &DAG) const {
12693   const X86RegisterInfo *RegInfo =
12694     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12695   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12696 }
12697
12698 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12699   SDValue Chain     = Op.getOperand(0);
12700   SDValue Offset    = Op.getOperand(1);
12701   SDValue Handler   = Op.getOperand(2);
12702   SDLoc dl      (Op);
12703
12704   EVT PtrVT = getPointerTy();
12705   const X86RegisterInfo *RegInfo =
12706     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12707   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12708   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12709           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12710          "Invalid Frame Register!");
12711   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12712   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12713
12714   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12715                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12716   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12717   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12718                        false, false, 0);
12719   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12720
12721   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12722                      DAG.getRegister(StoreAddrReg, PtrVT));
12723 }
12724
12725 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12726                                                SelectionDAG &DAG) const {
12727   SDLoc DL(Op);
12728   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12729                      DAG.getVTList(MVT::i32, MVT::Other),
12730                      Op.getOperand(0), Op.getOperand(1));
12731 }
12732
12733 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12734                                                 SelectionDAG &DAG) const {
12735   SDLoc DL(Op);
12736   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12737                      Op.getOperand(0), Op.getOperand(1));
12738 }
12739
12740 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12741   return Op.getOperand(0);
12742 }
12743
12744 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12745                                                 SelectionDAG &DAG) const {
12746   SDValue Root = Op.getOperand(0);
12747   SDValue Trmp = Op.getOperand(1); // trampoline
12748   SDValue FPtr = Op.getOperand(2); // nested function
12749   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12750   SDLoc dl (Op);
12751
12752   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12753   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12754
12755   if (Subtarget->is64Bit()) {
12756     SDValue OutChains[6];
12757
12758     // Large code-model.
12759     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12760     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12761
12762     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12763     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12764
12765     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12766
12767     // Load the pointer to the nested function into R11.
12768     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12769     SDValue Addr = Trmp;
12770     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12771                                 Addr, MachinePointerInfo(TrmpAddr),
12772                                 false, false, 0);
12773
12774     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12775                        DAG.getConstant(2, MVT::i64));
12776     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12777                                 MachinePointerInfo(TrmpAddr, 2),
12778                                 false, false, 2);
12779
12780     // Load the 'nest' parameter value into R10.
12781     // R10 is specified in X86CallingConv.td
12782     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12783     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12784                        DAG.getConstant(10, MVT::i64));
12785     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12786                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12787                                 false, false, 0);
12788
12789     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12790                        DAG.getConstant(12, MVT::i64));
12791     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12792                                 MachinePointerInfo(TrmpAddr, 12),
12793                                 false, false, 2);
12794
12795     // Jump to the nested function.
12796     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12797     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12798                        DAG.getConstant(20, MVT::i64));
12799     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12800                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12801                                 false, false, 0);
12802
12803     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12804     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12805                        DAG.getConstant(22, MVT::i64));
12806     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12807                                 MachinePointerInfo(TrmpAddr, 22),
12808                                 false, false, 0);
12809
12810     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12811   } else {
12812     const Function *Func =
12813       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12814     CallingConv::ID CC = Func->getCallingConv();
12815     unsigned NestReg;
12816
12817     switch (CC) {
12818     default:
12819       llvm_unreachable("Unsupported calling convention");
12820     case CallingConv::C:
12821     case CallingConv::X86_StdCall: {
12822       // Pass 'nest' parameter in ECX.
12823       // Must be kept in sync with X86CallingConv.td
12824       NestReg = X86::ECX;
12825
12826       // Check that ECX wasn't needed by an 'inreg' parameter.
12827       FunctionType *FTy = Func->getFunctionType();
12828       const AttributeSet &Attrs = Func->getAttributes();
12829
12830       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12831         unsigned InRegCount = 0;
12832         unsigned Idx = 1;
12833
12834         for (FunctionType::param_iterator I = FTy->param_begin(),
12835              E = FTy->param_end(); I != E; ++I, ++Idx)
12836           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12837             // FIXME: should only count parameters that are lowered to integers.
12838             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12839
12840         if (InRegCount > 2) {
12841           report_fatal_error("Nest register in use - reduce number of inreg"
12842                              " parameters!");
12843         }
12844       }
12845       break;
12846     }
12847     case CallingConv::X86_FastCall:
12848     case CallingConv::X86_ThisCall:
12849     case CallingConv::Fast:
12850       // Pass 'nest' parameter in EAX.
12851       // Must be kept in sync with X86CallingConv.td
12852       NestReg = X86::EAX;
12853       break;
12854     }
12855
12856     SDValue OutChains[4];
12857     SDValue Addr, Disp;
12858
12859     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12860                        DAG.getConstant(10, MVT::i32));
12861     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12862
12863     // This is storing the opcode for MOV32ri.
12864     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12865     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12866     OutChains[0] = DAG.getStore(Root, dl,
12867                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12868                                 Trmp, MachinePointerInfo(TrmpAddr),
12869                                 false, false, 0);
12870
12871     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12872                        DAG.getConstant(1, MVT::i32));
12873     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12874                                 MachinePointerInfo(TrmpAddr, 1),
12875                                 false, false, 1);
12876
12877     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12878     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12879                        DAG.getConstant(5, MVT::i32));
12880     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12881                                 MachinePointerInfo(TrmpAddr, 5),
12882                                 false, false, 1);
12883
12884     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12885                        DAG.getConstant(6, MVT::i32));
12886     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12887                                 MachinePointerInfo(TrmpAddr, 6),
12888                                 false, false, 1);
12889
12890     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12891   }
12892 }
12893
12894 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12895                                             SelectionDAG &DAG) const {
12896   /*
12897    The rounding mode is in bits 11:10 of FPSR, and has the following
12898    settings:
12899      00 Round to nearest
12900      01 Round to -inf
12901      10 Round to +inf
12902      11 Round to 0
12903
12904   FLT_ROUNDS, on the other hand, expects the following:
12905     -1 Undefined
12906      0 Round to 0
12907      1 Round to nearest
12908      2 Round to +inf
12909      3 Round to -inf
12910
12911   To perform the conversion, we do:
12912     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12913   */
12914
12915   MachineFunction &MF = DAG.getMachineFunction();
12916   const TargetMachine &TM = MF.getTarget();
12917   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12918   unsigned StackAlignment = TFI.getStackAlignment();
12919   MVT VT = Op.getSimpleValueType();
12920   SDLoc DL(Op);
12921
12922   // Save FP Control Word to stack slot
12923   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12924   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12925
12926   MachineMemOperand *MMO =
12927    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12928                            MachineMemOperand::MOStore, 2, 2);
12929
12930   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12931   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12932                                           DAG.getVTList(MVT::Other),
12933                                           Ops, array_lengthof(Ops), MVT::i16,
12934                                           MMO);
12935
12936   // Load FP Control Word from stack slot
12937   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12938                             MachinePointerInfo(), false, false, false, 0);
12939
12940   // Transform as necessary
12941   SDValue CWD1 =
12942     DAG.getNode(ISD::SRL, DL, MVT::i16,
12943                 DAG.getNode(ISD::AND, DL, MVT::i16,
12944                             CWD, DAG.getConstant(0x800, MVT::i16)),
12945                 DAG.getConstant(11, MVT::i8));
12946   SDValue CWD2 =
12947     DAG.getNode(ISD::SRL, DL, MVT::i16,
12948                 DAG.getNode(ISD::AND, DL, MVT::i16,
12949                             CWD, DAG.getConstant(0x400, MVT::i16)),
12950                 DAG.getConstant(9, MVT::i8));
12951
12952   SDValue RetVal =
12953     DAG.getNode(ISD::AND, DL, MVT::i16,
12954                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12955                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12956                             DAG.getConstant(1, MVT::i16)),
12957                 DAG.getConstant(3, MVT::i16));
12958
12959   return DAG.getNode((VT.getSizeInBits() < 16 ?
12960                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12961 }
12962
12963 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12964   MVT VT = Op.getSimpleValueType();
12965   EVT OpVT = VT;
12966   unsigned NumBits = VT.getSizeInBits();
12967   SDLoc dl(Op);
12968
12969   Op = Op.getOperand(0);
12970   if (VT == MVT::i8) {
12971     // Zero extend to i32 since there is not an i8 bsr.
12972     OpVT = MVT::i32;
12973     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12974   }
12975
12976   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12977   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12978   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12979
12980   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12981   SDValue Ops[] = {
12982     Op,
12983     DAG.getConstant(NumBits+NumBits-1, OpVT),
12984     DAG.getConstant(X86::COND_E, MVT::i8),
12985     Op.getValue(1)
12986   };
12987   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12988
12989   // Finally xor with NumBits-1.
12990   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12991
12992   if (VT == MVT::i8)
12993     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12994   return Op;
12995 }
12996
12997 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12998   MVT VT = Op.getSimpleValueType();
12999   EVT OpVT = VT;
13000   unsigned NumBits = VT.getSizeInBits();
13001   SDLoc dl(Op);
13002
13003   Op = Op.getOperand(0);
13004   if (VT == MVT::i8) {
13005     // Zero extend to i32 since there is not an i8 bsr.
13006     OpVT = MVT::i32;
13007     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13008   }
13009
13010   // Issue a bsr (scan bits in reverse).
13011   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13012   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13013
13014   // And xor with NumBits-1.
13015   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13016
13017   if (VT == MVT::i8)
13018     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13019   return Op;
13020 }
13021
13022 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13023   MVT VT = Op.getSimpleValueType();
13024   unsigned NumBits = VT.getSizeInBits();
13025   SDLoc dl(Op);
13026   Op = Op.getOperand(0);
13027
13028   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13029   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13030   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13031
13032   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13033   SDValue Ops[] = {
13034     Op,
13035     DAG.getConstant(NumBits, VT),
13036     DAG.getConstant(X86::COND_E, MVT::i8),
13037     Op.getValue(1)
13038   };
13039   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
13040 }
13041
13042 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13043 // ones, and then concatenate the result back.
13044 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13045   MVT VT = Op.getSimpleValueType();
13046
13047   assert(VT.is256BitVector() && VT.isInteger() &&
13048          "Unsupported value type for operation");
13049
13050   unsigned NumElems = VT.getVectorNumElements();
13051   SDLoc dl(Op);
13052
13053   // Extract the LHS vectors
13054   SDValue LHS = Op.getOperand(0);
13055   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13056   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13057
13058   // Extract the RHS vectors
13059   SDValue RHS = Op.getOperand(1);
13060   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13061   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13062
13063   MVT EltVT = VT.getVectorElementType();
13064   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13065
13066   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13067                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13068                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13069 }
13070
13071 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13072   assert(Op.getSimpleValueType().is256BitVector() &&
13073          Op.getSimpleValueType().isInteger() &&
13074          "Only handle AVX 256-bit vector integer operation");
13075   return Lower256IntArith(Op, DAG);
13076 }
13077
13078 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13079   assert(Op.getSimpleValueType().is256BitVector() &&
13080          Op.getSimpleValueType().isInteger() &&
13081          "Only handle AVX 256-bit vector integer operation");
13082   return Lower256IntArith(Op, DAG);
13083 }
13084
13085 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13086                         SelectionDAG &DAG) {
13087   SDLoc dl(Op);
13088   MVT VT = Op.getSimpleValueType();
13089
13090   // Decompose 256-bit ops into smaller 128-bit ops.
13091   if (VT.is256BitVector() && !Subtarget->hasInt256())
13092     return Lower256IntArith(Op, DAG);
13093
13094   SDValue A = Op.getOperand(0);
13095   SDValue B = Op.getOperand(1);
13096
13097   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13098   if (VT == MVT::v4i32) {
13099     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13100            "Should not custom lower when pmuldq is available!");
13101
13102     // Extract the odd parts.
13103     static const int UnpackMask[] = { 1, -1, 3, -1 };
13104     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13105     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13106
13107     // Multiply the even parts.
13108     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13109     // Now multiply odd parts.
13110     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13111
13112     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13113     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13114
13115     // Merge the two vectors back together with a shuffle. This expands into 2
13116     // shuffles.
13117     static const int ShufMask[] = { 0, 4, 2, 6 };
13118     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13119   }
13120
13121   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13122          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13123
13124   //  Ahi = psrlqi(a, 32);
13125   //  Bhi = psrlqi(b, 32);
13126   //
13127   //  AloBlo = pmuludq(a, b);
13128   //  AloBhi = pmuludq(a, Bhi);
13129   //  AhiBlo = pmuludq(Ahi, b);
13130
13131   //  AloBhi = psllqi(AloBhi, 32);
13132   //  AhiBlo = psllqi(AhiBlo, 32);
13133   //  return AloBlo + AloBhi + AhiBlo;
13134
13135   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13136   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13137
13138   // Bit cast to 32-bit vectors for MULUDQ
13139   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13140                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13141   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13142   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13143   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13144   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13145
13146   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13147   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13148   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13149
13150   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13151   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13152
13153   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13154   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13155 }
13156
13157 static SDValue LowerUMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13158                               SelectionDAG &DAG) {
13159   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13160   EVT VT = Op0.getValueType();
13161   SDLoc dl(Op);
13162
13163   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13164          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13165
13166   // Get the high parts.
13167   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13168   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13169   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13170
13171   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13172   // ints.
13173   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13174   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13175                              DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Op0, Op1));
13176   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13177                              DAG.getNode(X86ISD::PMULUDQ, dl, MulVT, Hi0, Hi1));
13178
13179   // Shuffle it back into the right order.
13180   const int HighMask[] = {1, 3, 5, 7, 9, 11, 13, 15};
13181   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13182   const int LowMask[] = {0, 2, 4, 6, 8, 10, 12, 14};
13183   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13184
13185   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13186 }
13187
13188 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13189                                          const X86Subtarget *Subtarget) {
13190   MVT VT = Op.getSimpleValueType();
13191   SDLoc dl(Op);
13192   SDValue R = Op.getOperand(0);
13193   SDValue Amt = Op.getOperand(1);
13194
13195   // Optimize shl/srl/sra with constant shift amount.
13196   if (isSplatVector(Amt.getNode())) {
13197     SDValue SclrAmt = Amt->getOperand(0);
13198     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13199       uint64_t ShiftAmt = C->getZExtValue();
13200
13201       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13202           (Subtarget->hasInt256() &&
13203            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13204           (Subtarget->hasAVX512() &&
13205            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13206         if (Op.getOpcode() == ISD::SHL)
13207           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13208                                             DAG);
13209         if (Op.getOpcode() == ISD::SRL)
13210           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13211                                             DAG);
13212         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13213           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13214                                             DAG);
13215       }
13216
13217       if (VT == MVT::v16i8) {
13218         if (Op.getOpcode() == ISD::SHL) {
13219           // Make a large shift.
13220           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13221                                                    MVT::v8i16, R, ShiftAmt,
13222                                                    DAG);
13223           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13224           // Zero out the rightmost bits.
13225           SmallVector<SDValue, 16> V(16,
13226                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13227                                                      MVT::i8));
13228           return DAG.getNode(ISD::AND, dl, VT, SHL,
13229                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13230         }
13231         if (Op.getOpcode() == ISD::SRL) {
13232           // Make a large shift.
13233           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13234                                                    MVT::v8i16, R, ShiftAmt,
13235                                                    DAG);
13236           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13237           // Zero out the leftmost bits.
13238           SmallVector<SDValue, 16> V(16,
13239                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13240                                                      MVT::i8));
13241           return DAG.getNode(ISD::AND, dl, VT, SRL,
13242                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13243         }
13244         if (Op.getOpcode() == ISD::SRA) {
13245           if (ShiftAmt == 7) {
13246             // R s>> 7  ===  R s< 0
13247             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13248             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13249           }
13250
13251           // R s>> a === ((R u>> a) ^ m) - m
13252           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13253           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13254                                                          MVT::i8));
13255           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13256           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13257           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13258           return Res;
13259         }
13260         llvm_unreachable("Unknown shift opcode.");
13261       }
13262
13263       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13264         if (Op.getOpcode() == ISD::SHL) {
13265           // Make a large shift.
13266           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13267                                                    MVT::v16i16, R, ShiftAmt,
13268                                                    DAG);
13269           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13270           // Zero out the rightmost bits.
13271           SmallVector<SDValue, 32> V(32,
13272                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13273                                                      MVT::i8));
13274           return DAG.getNode(ISD::AND, dl, VT, SHL,
13275                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13276         }
13277         if (Op.getOpcode() == ISD::SRL) {
13278           // Make a large shift.
13279           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13280                                                    MVT::v16i16, R, ShiftAmt,
13281                                                    DAG);
13282           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13283           // Zero out the leftmost bits.
13284           SmallVector<SDValue, 32> V(32,
13285                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13286                                                      MVT::i8));
13287           return DAG.getNode(ISD::AND, dl, VT, SRL,
13288                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13289         }
13290         if (Op.getOpcode() == ISD::SRA) {
13291           if (ShiftAmt == 7) {
13292             // R s>> 7  ===  R s< 0
13293             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13294             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13295           }
13296
13297           // R s>> a === ((R u>> a) ^ m) - m
13298           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13299           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13300                                                          MVT::i8));
13301           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13302           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13303           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13304           return Res;
13305         }
13306         llvm_unreachable("Unknown shift opcode.");
13307       }
13308     }
13309   }
13310
13311   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13312   if (!Subtarget->is64Bit() &&
13313       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13314       Amt.getOpcode() == ISD::BITCAST &&
13315       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13316     Amt = Amt.getOperand(0);
13317     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13318                      VT.getVectorNumElements();
13319     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13320     uint64_t ShiftAmt = 0;
13321     for (unsigned i = 0; i != Ratio; ++i) {
13322       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13323       if (!C)
13324         return SDValue();
13325       // 6 == Log2(64)
13326       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13327     }
13328     // Check remaining shift amounts.
13329     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13330       uint64_t ShAmt = 0;
13331       for (unsigned j = 0; j != Ratio; ++j) {
13332         ConstantSDNode *C =
13333           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13334         if (!C)
13335           return SDValue();
13336         // 6 == Log2(64)
13337         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13338       }
13339       if (ShAmt != ShiftAmt)
13340         return SDValue();
13341     }
13342     switch (Op.getOpcode()) {
13343     default:
13344       llvm_unreachable("Unknown shift opcode!");
13345     case ISD::SHL:
13346       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13347                                         DAG);
13348     case ISD::SRL:
13349       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13350                                         DAG);
13351     case ISD::SRA:
13352       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13353                                         DAG);
13354     }
13355   }
13356
13357   return SDValue();
13358 }
13359
13360 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13361                                         const X86Subtarget* Subtarget) {
13362   MVT VT = Op.getSimpleValueType();
13363   SDLoc dl(Op);
13364   SDValue R = Op.getOperand(0);
13365   SDValue Amt = Op.getOperand(1);
13366
13367   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13368       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13369       (Subtarget->hasInt256() &&
13370        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13371         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13372        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13373     SDValue BaseShAmt;
13374     EVT EltVT = VT.getVectorElementType();
13375
13376     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13377       unsigned NumElts = VT.getVectorNumElements();
13378       unsigned i, j;
13379       for (i = 0; i != NumElts; ++i) {
13380         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13381           continue;
13382         break;
13383       }
13384       for (j = i; j != NumElts; ++j) {
13385         SDValue Arg = Amt.getOperand(j);
13386         if (Arg.getOpcode() == ISD::UNDEF) continue;
13387         if (Arg != Amt.getOperand(i))
13388           break;
13389       }
13390       if (i != NumElts && j == NumElts)
13391         BaseShAmt = Amt.getOperand(i);
13392     } else {
13393       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13394         Amt = Amt.getOperand(0);
13395       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13396                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13397         SDValue InVec = Amt.getOperand(0);
13398         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13399           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13400           unsigned i = 0;
13401           for (; i != NumElts; ++i) {
13402             SDValue Arg = InVec.getOperand(i);
13403             if (Arg.getOpcode() == ISD::UNDEF) continue;
13404             BaseShAmt = Arg;
13405             break;
13406           }
13407         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13408            if (ConstantSDNode *C =
13409                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13410              unsigned SplatIdx =
13411                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13412              if (C->getZExtValue() == SplatIdx)
13413                BaseShAmt = InVec.getOperand(1);
13414            }
13415         }
13416         if (!BaseShAmt.getNode())
13417           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13418                                   DAG.getIntPtrConstant(0));
13419       }
13420     }
13421
13422     if (BaseShAmt.getNode()) {
13423       if (EltVT.bitsGT(MVT::i32))
13424         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13425       else if (EltVT.bitsLT(MVT::i32))
13426         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13427
13428       switch (Op.getOpcode()) {
13429       default:
13430         llvm_unreachable("Unknown shift opcode!");
13431       case ISD::SHL:
13432         switch (VT.SimpleTy) {
13433         default: return SDValue();
13434         case MVT::v2i64:
13435         case MVT::v4i32:
13436         case MVT::v8i16:
13437         case MVT::v4i64:
13438         case MVT::v8i32:
13439         case MVT::v16i16:
13440         case MVT::v16i32:
13441         case MVT::v8i64:
13442           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13443         }
13444       case ISD::SRA:
13445         switch (VT.SimpleTy) {
13446         default: return SDValue();
13447         case MVT::v4i32:
13448         case MVT::v8i16:
13449         case MVT::v8i32:
13450         case MVT::v16i16:
13451         case MVT::v16i32:
13452         case MVT::v8i64:
13453           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13454         }
13455       case ISD::SRL:
13456         switch (VT.SimpleTy) {
13457         default: return SDValue();
13458         case MVT::v2i64:
13459         case MVT::v4i32:
13460         case MVT::v8i16:
13461         case MVT::v4i64:
13462         case MVT::v8i32:
13463         case MVT::v16i16:
13464         case MVT::v16i32:
13465         case MVT::v8i64:
13466           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13467         }
13468       }
13469     }
13470   }
13471
13472   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13473   if (!Subtarget->is64Bit() &&
13474       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13475       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13476       Amt.getOpcode() == ISD::BITCAST &&
13477       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13478     Amt = Amt.getOperand(0);
13479     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13480                      VT.getVectorNumElements();
13481     std::vector<SDValue> Vals(Ratio);
13482     for (unsigned i = 0; i != Ratio; ++i)
13483       Vals[i] = Amt.getOperand(i);
13484     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13485       for (unsigned j = 0; j != Ratio; ++j)
13486         if (Vals[j] != Amt.getOperand(i + j))
13487           return SDValue();
13488     }
13489     switch (Op.getOpcode()) {
13490     default:
13491       llvm_unreachable("Unknown shift opcode!");
13492     case ISD::SHL:
13493       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13494     case ISD::SRL:
13495       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13496     case ISD::SRA:
13497       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13498     }
13499   }
13500
13501   return SDValue();
13502 }
13503
13504 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13505                           SelectionDAG &DAG) {
13506
13507   MVT VT = Op.getSimpleValueType();
13508   SDLoc dl(Op);
13509   SDValue R = Op.getOperand(0);
13510   SDValue Amt = Op.getOperand(1);
13511   SDValue V;
13512
13513   if (!Subtarget->hasSSE2())
13514     return SDValue();
13515
13516   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13517   if (V.getNode())
13518     return V;
13519
13520   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13521   if (V.getNode())
13522       return V;
13523
13524   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13525     return Op;
13526   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13527   if (Subtarget->hasInt256()) {
13528     if (Op.getOpcode() == ISD::SRL &&
13529         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13530          VT == MVT::v4i64 || VT == MVT::v8i32))
13531       return Op;
13532     if (Op.getOpcode() == ISD::SHL &&
13533         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13534          VT == MVT::v4i64 || VT == MVT::v8i32))
13535       return Op;
13536     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13537       return Op;
13538   }
13539
13540   // If possible, lower this packed shift into a vector multiply instead of
13541   // expanding it into a sequence of scalar shifts.
13542   // Do this only if the vector shift count is a constant build_vector.
13543   if (Op.getOpcode() == ISD::SHL && 
13544       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13545        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13546       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13547     SmallVector<SDValue, 8> Elts;
13548     EVT SVT = VT.getScalarType();
13549     unsigned SVTBits = SVT.getSizeInBits();
13550     const APInt &One = APInt(SVTBits, 1);
13551     unsigned NumElems = VT.getVectorNumElements();
13552
13553     for (unsigned i=0; i !=NumElems; ++i) {
13554       SDValue Op = Amt->getOperand(i);
13555       if (Op->getOpcode() == ISD::UNDEF) {
13556         Elts.push_back(Op);
13557         continue;
13558       }
13559
13560       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13561       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13562       uint64_t ShAmt = C.getZExtValue();
13563       if (ShAmt >= SVTBits) {
13564         Elts.push_back(DAG.getUNDEF(SVT));
13565         continue;
13566       }
13567       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13568     }
13569     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13570     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13571   }
13572
13573   // Lower SHL with variable shift amount.
13574   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13575     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13576
13577     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13578     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13579     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13580     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13581   }
13582
13583   // If possible, lower this shift as a sequence of two shifts by
13584   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13585   // Example:
13586   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13587   //
13588   // Could be rewritten as:
13589   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13590   //
13591   // The advantage is that the two shifts from the example would be
13592   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13593   // the vector shift into four scalar shifts plus four pairs of vector
13594   // insert/extract.
13595   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13596       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13597     unsigned TargetOpcode = X86ISD::MOVSS;
13598     bool CanBeSimplified;
13599     // The splat value for the first packed shift (the 'X' from the example).
13600     SDValue Amt1 = Amt->getOperand(0);
13601     // The splat value for the second packed shift (the 'Y' from the example).
13602     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13603                                         Amt->getOperand(2);
13604
13605     // See if it is possible to replace this node with a sequence of
13606     // two shifts followed by a MOVSS/MOVSD
13607     if (VT == MVT::v4i32) {
13608       // Check if it is legal to use a MOVSS.
13609       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13610                         Amt2 == Amt->getOperand(3);
13611       if (!CanBeSimplified) {
13612         // Otherwise, check if we can still simplify this node using a MOVSD.
13613         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13614                           Amt->getOperand(2) == Amt->getOperand(3);
13615         TargetOpcode = X86ISD::MOVSD;
13616         Amt2 = Amt->getOperand(2);
13617       }
13618     } else {
13619       // Do similar checks for the case where the machine value type
13620       // is MVT::v8i16.
13621       CanBeSimplified = Amt1 == Amt->getOperand(1);
13622       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13623         CanBeSimplified = Amt2 == Amt->getOperand(i);
13624
13625       if (!CanBeSimplified) {
13626         TargetOpcode = X86ISD::MOVSD;
13627         CanBeSimplified = true;
13628         Amt2 = Amt->getOperand(4);
13629         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13630           CanBeSimplified = Amt1 == Amt->getOperand(i);
13631         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13632           CanBeSimplified = Amt2 == Amt->getOperand(j);
13633       }
13634     }
13635     
13636     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13637         isa<ConstantSDNode>(Amt2)) {
13638       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13639       EVT CastVT = MVT::v4i32;
13640       SDValue Splat1 = 
13641         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13642       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13643       SDValue Splat2 = 
13644         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13645       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13646       if (TargetOpcode == X86ISD::MOVSD)
13647         CastVT = MVT::v2i64;
13648       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13649       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13650       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13651                                             BitCast1, DAG);
13652       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13653     }
13654   }
13655
13656   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13657     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13658
13659     // a = a << 5;
13660     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13661     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13662
13663     // Turn 'a' into a mask suitable for VSELECT
13664     SDValue VSelM = DAG.getConstant(0x80, VT);
13665     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13666     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13667
13668     SDValue CM1 = DAG.getConstant(0x0f, VT);
13669     SDValue CM2 = DAG.getConstant(0x3f, VT);
13670
13671     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13672     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13673     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13674     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13675     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13676
13677     // a += a
13678     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13679     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13680     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13681
13682     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13683     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13684     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13685     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13686     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13687
13688     // a += a
13689     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13690     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13691     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13692
13693     // return VSELECT(r, r+r, a);
13694     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13695                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13696     return R;
13697   }
13698
13699   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13700   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13701   // solution better.
13702   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13703     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13704     unsigned ExtOpc =
13705         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13706     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13707     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13708     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13709                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13710     }
13711
13712   // Decompose 256-bit shifts into smaller 128-bit shifts.
13713   if (VT.is256BitVector()) {
13714     unsigned NumElems = VT.getVectorNumElements();
13715     MVT EltVT = VT.getVectorElementType();
13716     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13717
13718     // Extract the two vectors
13719     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13720     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13721
13722     // Recreate the shift amount vectors
13723     SDValue Amt1, Amt2;
13724     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13725       // Constant shift amount
13726       SmallVector<SDValue, 4> Amt1Csts;
13727       SmallVector<SDValue, 4> Amt2Csts;
13728       for (unsigned i = 0; i != NumElems/2; ++i)
13729         Amt1Csts.push_back(Amt->getOperand(i));
13730       for (unsigned i = NumElems/2; i != NumElems; ++i)
13731         Amt2Csts.push_back(Amt->getOperand(i));
13732
13733       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13734                                  &Amt1Csts[0], NumElems/2);
13735       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13736                                  &Amt2Csts[0], NumElems/2);
13737     } else {
13738       // Variable shift amount
13739       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13740       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13741     }
13742
13743     // Issue new vector shifts for the smaller types
13744     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13745     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13746
13747     // Concatenate the result back
13748     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13749   }
13750
13751   return SDValue();
13752 }
13753
13754 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13755   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13756   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13757   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13758   // has only one use.
13759   SDNode *N = Op.getNode();
13760   SDValue LHS = N->getOperand(0);
13761   SDValue RHS = N->getOperand(1);
13762   unsigned BaseOp = 0;
13763   unsigned Cond = 0;
13764   SDLoc DL(Op);
13765   switch (Op.getOpcode()) {
13766   default: llvm_unreachable("Unknown ovf instruction!");
13767   case ISD::SADDO:
13768     // A subtract of one will be selected as a INC. Note that INC doesn't
13769     // set CF, so we can't do this for UADDO.
13770     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13771       if (C->isOne()) {
13772         BaseOp = X86ISD::INC;
13773         Cond = X86::COND_O;
13774         break;
13775       }
13776     BaseOp = X86ISD::ADD;
13777     Cond = X86::COND_O;
13778     break;
13779   case ISD::UADDO:
13780     BaseOp = X86ISD::ADD;
13781     Cond = X86::COND_B;
13782     break;
13783   case ISD::SSUBO:
13784     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13785     // set CF, so we can't do this for USUBO.
13786     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13787       if (C->isOne()) {
13788         BaseOp = X86ISD::DEC;
13789         Cond = X86::COND_O;
13790         break;
13791       }
13792     BaseOp = X86ISD::SUB;
13793     Cond = X86::COND_O;
13794     break;
13795   case ISD::USUBO:
13796     BaseOp = X86ISD::SUB;
13797     Cond = X86::COND_B;
13798     break;
13799   case ISD::SMULO:
13800     BaseOp = X86ISD::SMUL;
13801     Cond = X86::COND_O;
13802     break;
13803   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13804     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13805                                  MVT::i32);
13806     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13807
13808     SDValue SetCC =
13809       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13810                   DAG.getConstant(X86::COND_O, MVT::i32),
13811                   SDValue(Sum.getNode(), 2));
13812
13813     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13814   }
13815   }
13816
13817   // Also sets EFLAGS.
13818   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13819   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13820
13821   SDValue SetCC =
13822     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13823                 DAG.getConstant(Cond, MVT::i32),
13824                 SDValue(Sum.getNode(), 1));
13825
13826   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13827 }
13828
13829 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13830                                                   SelectionDAG &DAG) const {
13831   SDLoc dl(Op);
13832   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13833   MVT VT = Op.getSimpleValueType();
13834
13835   if (!Subtarget->hasSSE2() || !VT.isVector())
13836     return SDValue();
13837
13838   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13839                       ExtraVT.getScalarType().getSizeInBits();
13840
13841   switch (VT.SimpleTy) {
13842     default: return SDValue();
13843     case MVT::v8i32:
13844     case MVT::v16i16:
13845       if (!Subtarget->hasFp256())
13846         return SDValue();
13847       if (!Subtarget->hasInt256()) {
13848         // needs to be split
13849         unsigned NumElems = VT.getVectorNumElements();
13850
13851         // Extract the LHS vectors
13852         SDValue LHS = Op.getOperand(0);
13853         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13854         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13855
13856         MVT EltVT = VT.getVectorElementType();
13857         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13858
13859         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13860         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13861         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13862                                    ExtraNumElems/2);
13863         SDValue Extra = DAG.getValueType(ExtraVT);
13864
13865         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13866         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13867
13868         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13869       }
13870       // fall through
13871     case MVT::v4i32:
13872     case MVT::v8i16: {
13873       SDValue Op0 = Op.getOperand(0);
13874       SDValue Op00 = Op0.getOperand(0);
13875       SDValue Tmp1;
13876       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13877       if (Op0.getOpcode() == ISD::BITCAST &&
13878           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13879         // (sext (vzext x)) -> (vsext x)
13880         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13881         if (Tmp1.getNode()) {
13882           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13883           // This folding is only valid when the in-reg type is a vector of i8,
13884           // i16, or i32.
13885           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13886               ExtraEltVT == MVT::i32) {
13887             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13888             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13889                    "This optimization is invalid without a VZEXT.");
13890             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13891           }
13892           Op0 = Tmp1;
13893         }
13894       }
13895
13896       // If the above didn't work, then just use Shift-Left + Shift-Right.
13897       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13898                                         DAG);
13899       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13900                                         DAG);
13901     }
13902   }
13903 }
13904
13905 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13906                                  SelectionDAG &DAG) {
13907   SDLoc dl(Op);
13908   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13909     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13910   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13911     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13912
13913   // The only fence that needs an instruction is a sequentially-consistent
13914   // cross-thread fence.
13915   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13916     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13917     // no-sse2). There isn't any reason to disable it if the target processor
13918     // supports it.
13919     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13920       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13921
13922     SDValue Chain = Op.getOperand(0);
13923     SDValue Zero = DAG.getConstant(0, MVT::i32);
13924     SDValue Ops[] = {
13925       DAG.getRegister(X86::ESP, MVT::i32), // Base
13926       DAG.getTargetConstant(1, MVT::i8),   // Scale
13927       DAG.getRegister(0, MVT::i32),        // Index
13928       DAG.getTargetConstant(0, MVT::i32),  // Disp
13929       DAG.getRegister(0, MVT::i32),        // Segment.
13930       Zero,
13931       Chain
13932     };
13933     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13934     return SDValue(Res, 0);
13935   }
13936
13937   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13938   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13939 }
13940
13941 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13942                              SelectionDAG &DAG) {
13943   MVT T = Op.getSimpleValueType();
13944   SDLoc DL(Op);
13945   unsigned Reg = 0;
13946   unsigned size = 0;
13947   switch(T.SimpleTy) {
13948   default: llvm_unreachable("Invalid value type!");
13949   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13950   case MVT::i16: Reg = X86::AX;  size = 2; break;
13951   case MVT::i32: Reg = X86::EAX; size = 4; break;
13952   case MVT::i64:
13953     assert(Subtarget->is64Bit() && "Node not type legal!");
13954     Reg = X86::RAX; size = 8;
13955     break;
13956   }
13957   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13958                                     Op.getOperand(2), SDValue());
13959   SDValue Ops[] = { cpIn.getValue(0),
13960                     Op.getOperand(1),
13961                     Op.getOperand(3),
13962                     DAG.getTargetConstant(size, MVT::i8),
13963                     cpIn.getValue(1) };
13964   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13965   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13966   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13967                                            Ops, array_lengthof(Ops), T, MMO);
13968   SDValue cpOut =
13969     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13970   return cpOut;
13971 }
13972
13973 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13974                             SelectionDAG &DAG) {
13975   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13976   MVT DstVT = Op.getSimpleValueType();
13977   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13978          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13979   assert((DstVT == MVT::i64 ||
13980           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13981          "Unexpected custom BITCAST");
13982   // i64 <=> MMX conversions are Legal.
13983   if (SrcVT==MVT::i64 && DstVT.isVector())
13984     return Op;
13985   if (DstVT==MVT::i64 && SrcVT.isVector())
13986     return Op;
13987   // MMX <=> MMX conversions are Legal.
13988   if (SrcVT.isVector() && DstVT.isVector())
13989     return Op;
13990   // All other conversions need to be expanded.
13991   return SDValue();
13992 }
13993
13994 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13995   SDNode *Node = Op.getNode();
13996   SDLoc dl(Node);
13997   EVT T = Node->getValueType(0);
13998   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13999                               DAG.getConstant(0, T), Node->getOperand(2));
14000   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14001                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14002                        Node->getOperand(0),
14003                        Node->getOperand(1), negOp,
14004                        cast<AtomicSDNode>(Node)->getMemOperand(),
14005                        cast<AtomicSDNode>(Node)->getOrdering(),
14006                        cast<AtomicSDNode>(Node)->getSynchScope());
14007 }
14008
14009 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14010   SDNode *Node = Op.getNode();
14011   SDLoc dl(Node);
14012   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14013
14014   // Convert seq_cst store -> xchg
14015   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14016   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14017   //        (The only way to get a 16-byte store is cmpxchg16b)
14018   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14019   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14020       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14021     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14022                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14023                                  Node->getOperand(0),
14024                                  Node->getOperand(1), Node->getOperand(2),
14025                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14026                                  cast<AtomicSDNode>(Node)->getOrdering(),
14027                                  cast<AtomicSDNode>(Node)->getSynchScope());
14028     return Swap.getValue(1);
14029   }
14030   // Other atomic stores have a simple pattern.
14031   return Op;
14032 }
14033
14034 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14035   EVT VT = Op.getNode()->getSimpleValueType(0);
14036
14037   // Let legalize expand this if it isn't a legal type yet.
14038   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14039     return SDValue();
14040
14041   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14042
14043   unsigned Opc;
14044   bool ExtraOp = false;
14045   switch (Op.getOpcode()) {
14046   default: llvm_unreachable("Invalid code");
14047   case ISD::ADDC: Opc = X86ISD::ADD; break;
14048   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14049   case ISD::SUBC: Opc = X86ISD::SUB; break;
14050   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14051   }
14052
14053   if (!ExtraOp)
14054     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14055                        Op.getOperand(1));
14056   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14057                      Op.getOperand(1), Op.getOperand(2));
14058 }
14059
14060 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14061                             SelectionDAG &DAG) {
14062   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14063
14064   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14065   // which returns the values as { float, float } (in XMM0) or
14066   // { double, double } (which is returned in XMM0, XMM1).
14067   SDLoc dl(Op);
14068   SDValue Arg = Op.getOperand(0);
14069   EVT ArgVT = Arg.getValueType();
14070   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14071
14072   TargetLowering::ArgListTy Args;
14073   TargetLowering::ArgListEntry Entry;
14074
14075   Entry.Node = Arg;
14076   Entry.Ty = ArgTy;
14077   Entry.isSExt = false;
14078   Entry.isZExt = false;
14079   Args.push_back(Entry);
14080
14081   bool isF64 = ArgVT == MVT::f64;
14082   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14083   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14084   // the results are returned via SRet in memory.
14085   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14087   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14088
14089   Type *RetTy = isF64
14090     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14091     : (Type*)VectorType::get(ArgTy, 4);
14092   TargetLowering::
14093     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14094                          false, false, false, false, 0,
14095                          CallingConv::C, /*isTaillCall=*/false,
14096                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14097                          Callee, Args, DAG, dl);
14098   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14099
14100   if (isF64)
14101     // Returned in xmm0 and xmm1.
14102     return CallResult.first;
14103
14104   // Returned in bits 0:31 and 32:64 xmm0.
14105   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14106                                CallResult.first, DAG.getIntPtrConstant(0));
14107   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14108                                CallResult.first, DAG.getIntPtrConstant(1));
14109   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14110   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14111 }
14112
14113 /// LowerOperation - Provide custom lowering hooks for some operations.
14114 ///
14115 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14116   switch (Op.getOpcode()) {
14117   default: llvm_unreachable("Should not custom lower this!");
14118   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14119   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14120   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14121   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14122   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14123   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14124   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14125   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14126   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14127   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14128   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14129   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14130   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14131   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14132   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14133   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14134   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14135   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14136   case ISD::SHL_PARTS:
14137   case ISD::SRA_PARTS:
14138   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14139   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14140   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14141   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14142   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14143   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14144   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14145   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14146   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14147   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14148   case ISD::FABS:               return LowerFABS(Op, DAG);
14149   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14150   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14151   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14152   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14153   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14154   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14155   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14156   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14157   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14158   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14159   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14160   case ISD::INTRINSIC_VOID:
14161   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14162   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14163   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14164   case ISD::FRAME_TO_ARGS_OFFSET:
14165                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14166   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14167   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14168   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14169   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14170   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14171   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14172   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14173   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14174   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14175   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14176   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14177   case ISD::UMUL_LOHI:          return LowerUMUL_LOHI(Op, Subtarget, DAG);
14178   case ISD::SRA:
14179   case ISD::SRL:
14180   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14181   case ISD::SADDO:
14182   case ISD::UADDO:
14183   case ISD::SSUBO:
14184   case ISD::USUBO:
14185   case ISD::SMULO:
14186   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14187   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14188   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14189   case ISD::ADDC:
14190   case ISD::ADDE:
14191   case ISD::SUBC:
14192   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14193   case ISD::ADD:                return LowerADD(Op, DAG);
14194   case ISD::SUB:                return LowerSUB(Op, DAG);
14195   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14196   }
14197 }
14198
14199 static void ReplaceATOMIC_LOAD(SDNode *Node,
14200                                   SmallVectorImpl<SDValue> &Results,
14201                                   SelectionDAG &DAG) {
14202   SDLoc dl(Node);
14203   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14204
14205   // Convert wide load -> cmpxchg8b/cmpxchg16b
14206   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14207   //        (The only way to get a 16-byte load is cmpxchg16b)
14208   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14209   SDValue Zero = DAG.getConstant(0, VT);
14210   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14211                                Node->getOperand(0),
14212                                Node->getOperand(1), Zero, Zero,
14213                                cast<AtomicSDNode>(Node)->getMemOperand(),
14214                                cast<AtomicSDNode>(Node)->getOrdering(),
14215                                cast<AtomicSDNode>(Node)->getOrdering(),
14216                                cast<AtomicSDNode>(Node)->getSynchScope());
14217   Results.push_back(Swap.getValue(0));
14218   Results.push_back(Swap.getValue(1));
14219 }
14220
14221 static void
14222 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14223                         SelectionDAG &DAG, unsigned NewOp) {
14224   SDLoc dl(Node);
14225   assert (Node->getValueType(0) == MVT::i64 &&
14226           "Only know how to expand i64 atomics");
14227
14228   SDValue Chain = Node->getOperand(0);
14229   SDValue In1 = Node->getOperand(1);
14230   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14231                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14232   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14233                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14234   SDValue Ops[] = { Chain, In1, In2L, In2H };
14235   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14236   SDValue Result =
14237     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14238                             cast<MemSDNode>(Node)->getMemOperand());
14239   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14240   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14241   Results.push_back(Result.getValue(2));
14242 }
14243
14244 /// ReplaceNodeResults - Replace a node with an illegal result type
14245 /// with a new node built out of custom code.
14246 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14247                                            SmallVectorImpl<SDValue>&Results,
14248                                            SelectionDAG &DAG) const {
14249   SDLoc dl(N);
14250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14251   switch (N->getOpcode()) {
14252   default:
14253     llvm_unreachable("Do not know how to custom type legalize this operation!");
14254   case ISD::SIGN_EXTEND_INREG:
14255   case ISD::ADDC:
14256   case ISD::ADDE:
14257   case ISD::SUBC:
14258   case ISD::SUBE:
14259     // We don't want to expand or promote these.
14260     return;
14261   case ISD::FP_TO_SINT:
14262   case ISD::FP_TO_UINT: {
14263     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14264
14265     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14266       return;
14267
14268     std::pair<SDValue,SDValue> Vals =
14269         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14270     SDValue FIST = Vals.first, StackSlot = Vals.second;
14271     if (FIST.getNode()) {
14272       EVT VT = N->getValueType(0);
14273       // Return a load from the stack slot.
14274       if (StackSlot.getNode())
14275         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14276                                       MachinePointerInfo(),
14277                                       false, false, false, 0));
14278       else
14279         Results.push_back(FIST);
14280     }
14281     return;
14282   }
14283   case ISD::UINT_TO_FP: {
14284     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14285     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14286         N->getValueType(0) != MVT::v2f32)
14287       return;
14288     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14289                                  N->getOperand(0));
14290     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14291                                      MVT::f64);
14292     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14293     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14294                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14295     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14296     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14297     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14298     return;
14299   }
14300   case ISD::FP_ROUND: {
14301     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14302         return;
14303     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14304     Results.push_back(V);
14305     return;
14306   }
14307   case ISD::INTRINSIC_W_CHAIN: {
14308     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14309     switch (IntNo) {
14310     default : llvm_unreachable("Do not know how to custom type "
14311                                "legalize this intrinsic operation!");
14312     case Intrinsic::x86_rdtsc:
14313       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14314                                      Results);
14315     case Intrinsic::x86_rdtscp:
14316       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14317                                      Results);
14318     }
14319   }
14320   case ISD::READCYCLECOUNTER: {
14321     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14322                                    Results);
14323   }
14324   case ISD::ATOMIC_CMP_SWAP: {
14325     EVT T = N->getValueType(0);
14326     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14327     bool Regs64bit = T == MVT::i128;
14328     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14329     SDValue cpInL, cpInH;
14330     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14331                         DAG.getConstant(0, HalfT));
14332     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14333                         DAG.getConstant(1, HalfT));
14334     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14335                              Regs64bit ? X86::RAX : X86::EAX,
14336                              cpInL, SDValue());
14337     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14338                              Regs64bit ? X86::RDX : X86::EDX,
14339                              cpInH, cpInL.getValue(1));
14340     SDValue swapInL, swapInH;
14341     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14342                           DAG.getConstant(0, HalfT));
14343     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14344                           DAG.getConstant(1, HalfT));
14345     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14346                                Regs64bit ? X86::RBX : X86::EBX,
14347                                swapInL, cpInH.getValue(1));
14348     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14349                                Regs64bit ? X86::RCX : X86::ECX,
14350                                swapInH, swapInL.getValue(1));
14351     SDValue Ops[] = { swapInH.getValue(0),
14352                       N->getOperand(1),
14353                       swapInH.getValue(1) };
14354     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14355     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14356     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14357                                   X86ISD::LCMPXCHG8_DAG;
14358     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14359                                              Ops, array_lengthof(Ops), T, MMO);
14360     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14361                                         Regs64bit ? X86::RAX : X86::EAX,
14362                                         HalfT, Result.getValue(1));
14363     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14364                                         Regs64bit ? X86::RDX : X86::EDX,
14365                                         HalfT, cpOutL.getValue(2));
14366     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14367     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14368     Results.push_back(cpOutH.getValue(1));
14369     return;
14370   }
14371   case ISD::ATOMIC_LOAD_ADD:
14372   case ISD::ATOMIC_LOAD_AND:
14373   case ISD::ATOMIC_LOAD_NAND:
14374   case ISD::ATOMIC_LOAD_OR:
14375   case ISD::ATOMIC_LOAD_SUB:
14376   case ISD::ATOMIC_LOAD_XOR:
14377   case ISD::ATOMIC_LOAD_MAX:
14378   case ISD::ATOMIC_LOAD_MIN:
14379   case ISD::ATOMIC_LOAD_UMAX:
14380   case ISD::ATOMIC_LOAD_UMIN:
14381   case ISD::ATOMIC_SWAP: {
14382     unsigned Opc;
14383     switch (N->getOpcode()) {
14384     default: llvm_unreachable("Unexpected opcode");
14385     case ISD::ATOMIC_LOAD_ADD:
14386       Opc = X86ISD::ATOMADD64_DAG;
14387       break;
14388     case ISD::ATOMIC_LOAD_AND:
14389       Opc = X86ISD::ATOMAND64_DAG;
14390       break;
14391     case ISD::ATOMIC_LOAD_NAND:
14392       Opc = X86ISD::ATOMNAND64_DAG;
14393       break;
14394     case ISD::ATOMIC_LOAD_OR:
14395       Opc = X86ISD::ATOMOR64_DAG;
14396       break;
14397     case ISD::ATOMIC_LOAD_SUB:
14398       Opc = X86ISD::ATOMSUB64_DAG;
14399       break;
14400     case ISD::ATOMIC_LOAD_XOR:
14401       Opc = X86ISD::ATOMXOR64_DAG;
14402       break;
14403     case ISD::ATOMIC_LOAD_MAX:
14404       Opc = X86ISD::ATOMMAX64_DAG;
14405       break;
14406     case ISD::ATOMIC_LOAD_MIN:
14407       Opc = X86ISD::ATOMMIN64_DAG;
14408       break;
14409     case ISD::ATOMIC_LOAD_UMAX:
14410       Opc = X86ISD::ATOMUMAX64_DAG;
14411       break;
14412     case ISD::ATOMIC_LOAD_UMIN:
14413       Opc = X86ISD::ATOMUMIN64_DAG;
14414       break;
14415     case ISD::ATOMIC_SWAP:
14416       Opc = X86ISD::ATOMSWAP64_DAG;
14417       break;
14418     }
14419     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14420     return;
14421   }
14422   case ISD::ATOMIC_LOAD:
14423     ReplaceATOMIC_LOAD(N, Results, DAG);
14424   }
14425 }
14426
14427 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14428   switch (Opcode) {
14429   default: return nullptr;
14430   case X86ISD::BSF:                return "X86ISD::BSF";
14431   case X86ISD::BSR:                return "X86ISD::BSR";
14432   case X86ISD::SHLD:               return "X86ISD::SHLD";
14433   case X86ISD::SHRD:               return "X86ISD::SHRD";
14434   case X86ISD::FAND:               return "X86ISD::FAND";
14435   case X86ISD::FANDN:              return "X86ISD::FANDN";
14436   case X86ISD::FOR:                return "X86ISD::FOR";
14437   case X86ISD::FXOR:               return "X86ISD::FXOR";
14438   case X86ISD::FSRL:               return "X86ISD::FSRL";
14439   case X86ISD::FILD:               return "X86ISD::FILD";
14440   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14441   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14442   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14443   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14444   case X86ISD::FLD:                return "X86ISD::FLD";
14445   case X86ISD::FST:                return "X86ISD::FST";
14446   case X86ISD::CALL:               return "X86ISD::CALL";
14447   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14448   case X86ISD::BT:                 return "X86ISD::BT";
14449   case X86ISD::CMP:                return "X86ISD::CMP";
14450   case X86ISD::COMI:               return "X86ISD::COMI";
14451   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14452   case X86ISD::CMPM:               return "X86ISD::CMPM";
14453   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14454   case X86ISD::SETCC:              return "X86ISD::SETCC";
14455   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14456   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14457   case X86ISD::CMOV:               return "X86ISD::CMOV";
14458   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14459   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14460   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14461   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14462   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14463   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14464   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14465   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14466   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14467   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14468   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14469   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14470   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14471   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14472   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14473   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14474   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14475   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14476   case X86ISD::HADD:               return "X86ISD::HADD";
14477   case X86ISD::HSUB:               return "X86ISD::HSUB";
14478   case X86ISD::FHADD:              return "X86ISD::FHADD";
14479   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14480   case X86ISD::UMAX:               return "X86ISD::UMAX";
14481   case X86ISD::UMIN:               return "X86ISD::UMIN";
14482   case X86ISD::SMAX:               return "X86ISD::SMAX";
14483   case X86ISD::SMIN:               return "X86ISD::SMIN";
14484   case X86ISD::FMAX:               return "X86ISD::FMAX";
14485   case X86ISD::FMIN:               return "X86ISD::FMIN";
14486   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14487   case X86ISD::FMINC:              return "X86ISD::FMINC";
14488   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14489   case X86ISD::FRCP:               return "X86ISD::FRCP";
14490   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14491   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14492   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14493   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14494   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14495   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14496   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14497   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14498   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14499   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14500   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14501   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14502   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14503   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14504   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14505   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14506   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14507   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14508   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14509   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14510   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14511   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14512   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14513   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14514   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14515   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14516   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14517   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14518   case X86ISD::VSHL:               return "X86ISD::VSHL";
14519   case X86ISD::VSRL:               return "X86ISD::VSRL";
14520   case X86ISD::VSRA:               return "X86ISD::VSRA";
14521   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14522   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14523   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14524   case X86ISD::CMPP:               return "X86ISD::CMPP";
14525   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14526   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14527   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14528   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14529   case X86ISD::ADD:                return "X86ISD::ADD";
14530   case X86ISD::SUB:                return "X86ISD::SUB";
14531   case X86ISD::ADC:                return "X86ISD::ADC";
14532   case X86ISD::SBB:                return "X86ISD::SBB";
14533   case X86ISD::SMUL:               return "X86ISD::SMUL";
14534   case X86ISD::UMUL:               return "X86ISD::UMUL";
14535   case X86ISD::INC:                return "X86ISD::INC";
14536   case X86ISD::DEC:                return "X86ISD::DEC";
14537   case X86ISD::OR:                 return "X86ISD::OR";
14538   case X86ISD::XOR:                return "X86ISD::XOR";
14539   case X86ISD::AND:                return "X86ISD::AND";
14540   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14541   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14542   case X86ISD::PTEST:              return "X86ISD::PTEST";
14543   case X86ISD::TESTP:              return "X86ISD::TESTP";
14544   case X86ISD::TESTM:              return "X86ISD::TESTM";
14545   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14546   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14547   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14548   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14549   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14550   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14551   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14552   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14553   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14554   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14555   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14556   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14557   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14558   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14559   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14560   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14561   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14562   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14563   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14564   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14565   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14566   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14567   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14568   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14569   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14570   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14571   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14572   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14573   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14574   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14575   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14576   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14577   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14578   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14579   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14580   case X86ISD::SAHF:               return "X86ISD::SAHF";
14581   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14582   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14583   case X86ISD::FMADD:              return "X86ISD::FMADD";
14584   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14585   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14586   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14587   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14588   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14589   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14590   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14591   case X86ISD::XTEST:              return "X86ISD::XTEST";
14592   }
14593 }
14594
14595 // isLegalAddressingMode - Return true if the addressing mode represented
14596 // by AM is legal for this target, for a load/store of the specified type.
14597 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14598                                               Type *Ty) const {
14599   // X86 supports extremely general addressing modes.
14600   CodeModel::Model M = getTargetMachine().getCodeModel();
14601   Reloc::Model R = getTargetMachine().getRelocationModel();
14602
14603   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14604   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14605     return false;
14606
14607   if (AM.BaseGV) {
14608     unsigned GVFlags =
14609       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14610
14611     // If a reference to this global requires an extra load, we can't fold it.
14612     if (isGlobalStubReference(GVFlags))
14613       return false;
14614
14615     // If BaseGV requires a register for the PIC base, we cannot also have a
14616     // BaseReg specified.
14617     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14618       return false;
14619
14620     // If lower 4G is not available, then we must use rip-relative addressing.
14621     if ((M != CodeModel::Small || R != Reloc::Static) &&
14622         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14623       return false;
14624   }
14625
14626   switch (AM.Scale) {
14627   case 0:
14628   case 1:
14629   case 2:
14630   case 4:
14631   case 8:
14632     // These scales always work.
14633     break;
14634   case 3:
14635   case 5:
14636   case 9:
14637     // These scales are formed with basereg+scalereg.  Only accept if there is
14638     // no basereg yet.
14639     if (AM.HasBaseReg)
14640       return false;
14641     break;
14642   default:  // Other stuff never works.
14643     return false;
14644   }
14645
14646   return true;
14647 }
14648
14649 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14650   unsigned Bits = Ty->getScalarSizeInBits();
14651
14652   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14653   // particularly cheaper than those without.
14654   if (Bits == 8)
14655     return false;
14656
14657   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14658   // variable shifts just as cheap as scalar ones.
14659   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14660     return false;
14661
14662   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14663   // fully general vector.
14664   return true;
14665 }
14666
14667 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14668   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14669     return false;
14670   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14671   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14672   return NumBits1 > NumBits2;
14673 }
14674
14675 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14676   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14677     return false;
14678
14679   if (!isTypeLegal(EVT::getEVT(Ty1)))
14680     return false;
14681
14682   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14683
14684   // Assuming the caller doesn't have a zeroext or signext return parameter,
14685   // truncation all the way down to i1 is valid.
14686   return true;
14687 }
14688
14689 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14690   return isInt<32>(Imm);
14691 }
14692
14693 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14694   // Can also use sub to handle negated immediates.
14695   return isInt<32>(Imm);
14696 }
14697
14698 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14699   if (!VT1.isInteger() || !VT2.isInteger())
14700     return false;
14701   unsigned NumBits1 = VT1.getSizeInBits();
14702   unsigned NumBits2 = VT2.getSizeInBits();
14703   return NumBits1 > NumBits2;
14704 }
14705
14706 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14707   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14708   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14709 }
14710
14711 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14712   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14713   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14714 }
14715
14716 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14717   EVT VT1 = Val.getValueType();
14718   if (isZExtFree(VT1, VT2))
14719     return true;
14720
14721   if (Val.getOpcode() != ISD::LOAD)
14722     return false;
14723
14724   if (!VT1.isSimple() || !VT1.isInteger() ||
14725       !VT2.isSimple() || !VT2.isInteger())
14726     return false;
14727
14728   switch (VT1.getSimpleVT().SimpleTy) {
14729   default: break;
14730   case MVT::i8:
14731   case MVT::i16:
14732   case MVT::i32:
14733     // X86 has 8, 16, and 32-bit zero-extending loads.
14734     return true;
14735   }
14736
14737   return false;
14738 }
14739
14740 bool
14741 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14742   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14743     return false;
14744
14745   VT = VT.getScalarType();
14746
14747   if (!VT.isSimple())
14748     return false;
14749
14750   switch (VT.getSimpleVT().SimpleTy) {
14751   case MVT::f32:
14752   case MVT::f64:
14753     return true;
14754   default:
14755     break;
14756   }
14757
14758   return false;
14759 }
14760
14761 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14762   // i16 instructions are longer (0x66 prefix) and potentially slower.
14763   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14764 }
14765
14766 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14767 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14768 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14769 /// are assumed to be legal.
14770 bool
14771 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14772                                       EVT VT) const {
14773   if (!VT.isSimple())
14774     return false;
14775
14776   MVT SVT = VT.getSimpleVT();
14777
14778   // Very little shuffling can be done for 64-bit vectors right now.
14779   if (VT.getSizeInBits() == 64)
14780     return false;
14781
14782   // FIXME: pshufb, blends, shifts.
14783   return (SVT.getVectorNumElements() == 2 ||
14784           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14785           isMOVLMask(M, SVT) ||
14786           isSHUFPMask(M, SVT) ||
14787           isPSHUFDMask(M, SVT) ||
14788           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14789           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14790           isPALIGNRMask(M, SVT, Subtarget) ||
14791           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14792           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14793           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14794           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14795 }
14796
14797 bool
14798 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14799                                           EVT VT) const {
14800   if (!VT.isSimple())
14801     return false;
14802
14803   MVT SVT = VT.getSimpleVT();
14804   unsigned NumElts = SVT.getVectorNumElements();
14805   // FIXME: This collection of masks seems suspect.
14806   if (NumElts == 2)
14807     return true;
14808   if (NumElts == 4 && SVT.is128BitVector()) {
14809     return (isMOVLMask(Mask, SVT)  ||
14810             isCommutedMOVLMask(Mask, SVT, true) ||
14811             isSHUFPMask(Mask, SVT) ||
14812             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14813   }
14814   return false;
14815 }
14816
14817 //===----------------------------------------------------------------------===//
14818 //                           X86 Scheduler Hooks
14819 //===----------------------------------------------------------------------===//
14820
14821 /// Utility function to emit xbegin specifying the start of an RTM region.
14822 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14823                                      const TargetInstrInfo *TII) {
14824   DebugLoc DL = MI->getDebugLoc();
14825
14826   const BasicBlock *BB = MBB->getBasicBlock();
14827   MachineFunction::iterator I = MBB;
14828   ++I;
14829
14830   // For the v = xbegin(), we generate
14831   //
14832   // thisMBB:
14833   //  xbegin sinkMBB
14834   //
14835   // mainMBB:
14836   //  eax = -1
14837   //
14838   // sinkMBB:
14839   //  v = eax
14840
14841   MachineBasicBlock *thisMBB = MBB;
14842   MachineFunction *MF = MBB->getParent();
14843   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14844   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14845   MF->insert(I, mainMBB);
14846   MF->insert(I, sinkMBB);
14847
14848   // Transfer the remainder of BB and its successor edges to sinkMBB.
14849   sinkMBB->splice(sinkMBB->begin(), MBB,
14850                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14851   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14852
14853   // thisMBB:
14854   //  xbegin sinkMBB
14855   //  # fallthrough to mainMBB
14856   //  # abortion to sinkMBB
14857   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14858   thisMBB->addSuccessor(mainMBB);
14859   thisMBB->addSuccessor(sinkMBB);
14860
14861   // mainMBB:
14862   //  EAX = -1
14863   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14864   mainMBB->addSuccessor(sinkMBB);
14865
14866   // sinkMBB:
14867   // EAX is live into the sinkMBB
14868   sinkMBB->addLiveIn(X86::EAX);
14869   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14870           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14871     .addReg(X86::EAX);
14872
14873   MI->eraseFromParent();
14874   return sinkMBB;
14875 }
14876
14877 // Get CMPXCHG opcode for the specified data type.
14878 static unsigned getCmpXChgOpcode(EVT VT) {
14879   switch (VT.getSimpleVT().SimpleTy) {
14880   case MVT::i8:  return X86::LCMPXCHG8;
14881   case MVT::i16: return X86::LCMPXCHG16;
14882   case MVT::i32: return X86::LCMPXCHG32;
14883   case MVT::i64: return X86::LCMPXCHG64;
14884   default:
14885     break;
14886   }
14887   llvm_unreachable("Invalid operand size!");
14888 }
14889
14890 // Get LOAD opcode for the specified data type.
14891 static unsigned getLoadOpcode(EVT VT) {
14892   switch (VT.getSimpleVT().SimpleTy) {
14893   case MVT::i8:  return X86::MOV8rm;
14894   case MVT::i16: return X86::MOV16rm;
14895   case MVT::i32: return X86::MOV32rm;
14896   case MVT::i64: return X86::MOV64rm;
14897   default:
14898     break;
14899   }
14900   llvm_unreachable("Invalid operand size!");
14901 }
14902
14903 // Get opcode of the non-atomic one from the specified atomic instruction.
14904 static unsigned getNonAtomicOpcode(unsigned Opc) {
14905   switch (Opc) {
14906   case X86::ATOMAND8:  return X86::AND8rr;
14907   case X86::ATOMAND16: return X86::AND16rr;
14908   case X86::ATOMAND32: return X86::AND32rr;
14909   case X86::ATOMAND64: return X86::AND64rr;
14910   case X86::ATOMOR8:   return X86::OR8rr;
14911   case X86::ATOMOR16:  return X86::OR16rr;
14912   case X86::ATOMOR32:  return X86::OR32rr;
14913   case X86::ATOMOR64:  return X86::OR64rr;
14914   case X86::ATOMXOR8:  return X86::XOR8rr;
14915   case X86::ATOMXOR16: return X86::XOR16rr;
14916   case X86::ATOMXOR32: return X86::XOR32rr;
14917   case X86::ATOMXOR64: return X86::XOR64rr;
14918   }
14919   llvm_unreachable("Unhandled atomic-load-op opcode!");
14920 }
14921
14922 // Get opcode of the non-atomic one from the specified atomic instruction with
14923 // extra opcode.
14924 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14925                                                unsigned &ExtraOpc) {
14926   switch (Opc) {
14927   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14928   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14929   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14930   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14931   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14932   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14933   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14934   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14935   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14936   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14937   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14938   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14939   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14940   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14941   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14942   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14943   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14944   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14945   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14946   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14947   }
14948   llvm_unreachable("Unhandled atomic-load-op opcode!");
14949 }
14950
14951 // Get opcode of the non-atomic one from the specified atomic instruction for
14952 // 64-bit data type on 32-bit target.
14953 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14954   switch (Opc) {
14955   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14956   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14957   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14958   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14959   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14960   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14961   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14962   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14963   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14964   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14965   }
14966   llvm_unreachable("Unhandled atomic-load-op opcode!");
14967 }
14968
14969 // Get opcode of the non-atomic one from the specified atomic instruction for
14970 // 64-bit data type on 32-bit target with extra opcode.
14971 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14972                                                    unsigned &HiOpc,
14973                                                    unsigned &ExtraOpc) {
14974   switch (Opc) {
14975   case X86::ATOMNAND6432:
14976     ExtraOpc = X86::NOT32r;
14977     HiOpc = X86::AND32rr;
14978     return X86::AND32rr;
14979   }
14980   llvm_unreachable("Unhandled atomic-load-op opcode!");
14981 }
14982
14983 // Get pseudo CMOV opcode from the specified data type.
14984 static unsigned getPseudoCMOVOpc(EVT VT) {
14985   switch (VT.getSimpleVT().SimpleTy) {
14986   case MVT::i8:  return X86::CMOV_GR8;
14987   case MVT::i16: return X86::CMOV_GR16;
14988   case MVT::i32: return X86::CMOV_GR32;
14989   default:
14990     break;
14991   }
14992   llvm_unreachable("Unknown CMOV opcode!");
14993 }
14994
14995 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14996 // They will be translated into a spin-loop or compare-exchange loop from
14997 //
14998 //    ...
14999 //    dst = atomic-fetch-op MI.addr, MI.val
15000 //    ...
15001 //
15002 // to
15003 //
15004 //    ...
15005 //    t1 = LOAD MI.addr
15006 // loop:
15007 //    t4 = phi(t1, t3 / loop)
15008 //    t2 = OP MI.val, t4
15009 //    EAX = t4
15010 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15011 //    t3 = EAX
15012 //    JNE loop
15013 // sink:
15014 //    dst = t3
15015 //    ...
15016 MachineBasicBlock *
15017 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15018                                        MachineBasicBlock *MBB) const {
15019   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15020   DebugLoc DL = MI->getDebugLoc();
15021
15022   MachineFunction *MF = MBB->getParent();
15023   MachineRegisterInfo &MRI = MF->getRegInfo();
15024
15025   const BasicBlock *BB = MBB->getBasicBlock();
15026   MachineFunction::iterator I = MBB;
15027   ++I;
15028
15029   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15030          "Unexpected number of operands");
15031
15032   assert(MI->hasOneMemOperand() &&
15033          "Expected atomic-load-op to have one memoperand");
15034
15035   // Memory Reference
15036   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15037   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15038
15039   unsigned DstReg, SrcReg;
15040   unsigned MemOpndSlot;
15041
15042   unsigned CurOp = 0;
15043
15044   DstReg = MI->getOperand(CurOp++).getReg();
15045   MemOpndSlot = CurOp;
15046   CurOp += X86::AddrNumOperands;
15047   SrcReg = MI->getOperand(CurOp++).getReg();
15048
15049   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15050   MVT::SimpleValueType VT = *RC->vt_begin();
15051   unsigned t1 = MRI.createVirtualRegister(RC);
15052   unsigned t2 = MRI.createVirtualRegister(RC);
15053   unsigned t3 = MRI.createVirtualRegister(RC);
15054   unsigned t4 = MRI.createVirtualRegister(RC);
15055   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15056
15057   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15058   unsigned LOADOpc = getLoadOpcode(VT);
15059
15060   // For the atomic load-arith operator, we generate
15061   //
15062   //  thisMBB:
15063   //    t1 = LOAD [MI.addr]
15064   //  mainMBB:
15065   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15066   //    t1 = OP MI.val, EAX
15067   //    EAX = t4
15068   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15069   //    t3 = EAX
15070   //    JNE mainMBB
15071   //  sinkMBB:
15072   //    dst = t3
15073
15074   MachineBasicBlock *thisMBB = MBB;
15075   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15076   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15077   MF->insert(I, mainMBB);
15078   MF->insert(I, sinkMBB);
15079
15080   MachineInstrBuilder MIB;
15081
15082   // Transfer the remainder of BB and its successor edges to sinkMBB.
15083   sinkMBB->splice(sinkMBB->begin(), MBB,
15084                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15085   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15086
15087   // thisMBB:
15088   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15089   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15090     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15091     if (NewMO.isReg())
15092       NewMO.setIsKill(false);
15093     MIB.addOperand(NewMO);
15094   }
15095   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15096     unsigned flags = (*MMOI)->getFlags();
15097     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15098     MachineMemOperand *MMO =
15099       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15100                                (*MMOI)->getSize(),
15101                                (*MMOI)->getBaseAlignment(),
15102                                (*MMOI)->getTBAAInfo(),
15103                                (*MMOI)->getRanges());
15104     MIB.addMemOperand(MMO);
15105   }
15106
15107   thisMBB->addSuccessor(mainMBB);
15108
15109   // mainMBB:
15110   MachineBasicBlock *origMainMBB = mainMBB;
15111
15112   // Add a PHI.
15113   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15114                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15115
15116   unsigned Opc = MI->getOpcode();
15117   switch (Opc) {
15118   default:
15119     llvm_unreachable("Unhandled atomic-load-op opcode!");
15120   case X86::ATOMAND8:
15121   case X86::ATOMAND16:
15122   case X86::ATOMAND32:
15123   case X86::ATOMAND64:
15124   case X86::ATOMOR8:
15125   case X86::ATOMOR16:
15126   case X86::ATOMOR32:
15127   case X86::ATOMOR64:
15128   case X86::ATOMXOR8:
15129   case X86::ATOMXOR16:
15130   case X86::ATOMXOR32:
15131   case X86::ATOMXOR64: {
15132     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15133     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15134       .addReg(t4);
15135     break;
15136   }
15137   case X86::ATOMNAND8:
15138   case X86::ATOMNAND16:
15139   case X86::ATOMNAND32:
15140   case X86::ATOMNAND64: {
15141     unsigned Tmp = MRI.createVirtualRegister(RC);
15142     unsigned NOTOpc;
15143     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15144     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15145       .addReg(t4);
15146     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15147     break;
15148   }
15149   case X86::ATOMMAX8:
15150   case X86::ATOMMAX16:
15151   case X86::ATOMMAX32:
15152   case X86::ATOMMAX64:
15153   case X86::ATOMMIN8:
15154   case X86::ATOMMIN16:
15155   case X86::ATOMMIN32:
15156   case X86::ATOMMIN64:
15157   case X86::ATOMUMAX8:
15158   case X86::ATOMUMAX16:
15159   case X86::ATOMUMAX32:
15160   case X86::ATOMUMAX64:
15161   case X86::ATOMUMIN8:
15162   case X86::ATOMUMIN16:
15163   case X86::ATOMUMIN32:
15164   case X86::ATOMUMIN64: {
15165     unsigned CMPOpc;
15166     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15167
15168     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15169       .addReg(SrcReg)
15170       .addReg(t4);
15171
15172     if (Subtarget->hasCMov()) {
15173       if (VT != MVT::i8) {
15174         // Native support
15175         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15176           .addReg(SrcReg)
15177           .addReg(t4);
15178       } else {
15179         // Promote i8 to i32 to use CMOV32
15180         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15181         const TargetRegisterClass *RC32 =
15182           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15183         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15184         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15185         unsigned Tmp = MRI.createVirtualRegister(RC32);
15186
15187         unsigned Undef = MRI.createVirtualRegister(RC32);
15188         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15189
15190         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15191           .addReg(Undef)
15192           .addReg(SrcReg)
15193           .addImm(X86::sub_8bit);
15194         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15195           .addReg(Undef)
15196           .addReg(t4)
15197           .addImm(X86::sub_8bit);
15198
15199         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15200           .addReg(SrcReg32)
15201           .addReg(AccReg32);
15202
15203         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15204           .addReg(Tmp, 0, X86::sub_8bit);
15205       }
15206     } else {
15207       // Use pseudo select and lower them.
15208       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15209              "Invalid atomic-load-op transformation!");
15210       unsigned SelOpc = getPseudoCMOVOpc(VT);
15211       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15212       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15213       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15214               .addReg(SrcReg).addReg(t4)
15215               .addImm(CC);
15216       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15217       // Replace the original PHI node as mainMBB is changed after CMOV
15218       // lowering.
15219       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15220         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15221       Phi->eraseFromParent();
15222     }
15223     break;
15224   }
15225   }
15226
15227   // Copy PhyReg back from virtual register.
15228   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15229     .addReg(t4);
15230
15231   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15232   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15233     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15234     if (NewMO.isReg())
15235       NewMO.setIsKill(false);
15236     MIB.addOperand(NewMO);
15237   }
15238   MIB.addReg(t2);
15239   MIB.setMemRefs(MMOBegin, MMOEnd);
15240
15241   // Copy PhyReg back to virtual register.
15242   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15243     .addReg(PhyReg);
15244
15245   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15246
15247   mainMBB->addSuccessor(origMainMBB);
15248   mainMBB->addSuccessor(sinkMBB);
15249
15250   // sinkMBB:
15251   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15252           TII->get(TargetOpcode::COPY), DstReg)
15253     .addReg(t3);
15254
15255   MI->eraseFromParent();
15256   return sinkMBB;
15257 }
15258
15259 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15260 // instructions. They will be translated into a spin-loop or compare-exchange
15261 // loop from
15262 //
15263 //    ...
15264 //    dst = atomic-fetch-op MI.addr, MI.val
15265 //    ...
15266 //
15267 // to
15268 //
15269 //    ...
15270 //    t1L = LOAD [MI.addr + 0]
15271 //    t1H = LOAD [MI.addr + 4]
15272 // loop:
15273 //    t4L = phi(t1L, t3L / loop)
15274 //    t4H = phi(t1H, t3H / loop)
15275 //    t2L = OP MI.val.lo, t4L
15276 //    t2H = OP MI.val.hi, t4H
15277 //    EAX = t4L
15278 //    EDX = t4H
15279 //    EBX = t2L
15280 //    ECX = t2H
15281 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15282 //    t3L = EAX
15283 //    t3H = EDX
15284 //    JNE loop
15285 // sink:
15286 //    dstL = t3L
15287 //    dstH = t3H
15288 //    ...
15289 MachineBasicBlock *
15290 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15291                                            MachineBasicBlock *MBB) const {
15292   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15293   DebugLoc DL = MI->getDebugLoc();
15294
15295   MachineFunction *MF = MBB->getParent();
15296   MachineRegisterInfo &MRI = MF->getRegInfo();
15297
15298   const BasicBlock *BB = MBB->getBasicBlock();
15299   MachineFunction::iterator I = MBB;
15300   ++I;
15301
15302   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15303          "Unexpected number of operands");
15304
15305   assert(MI->hasOneMemOperand() &&
15306          "Expected atomic-load-op32 to have one memoperand");
15307
15308   // Memory Reference
15309   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15310   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15311
15312   unsigned DstLoReg, DstHiReg;
15313   unsigned SrcLoReg, SrcHiReg;
15314   unsigned MemOpndSlot;
15315
15316   unsigned CurOp = 0;
15317
15318   DstLoReg = MI->getOperand(CurOp++).getReg();
15319   DstHiReg = MI->getOperand(CurOp++).getReg();
15320   MemOpndSlot = CurOp;
15321   CurOp += X86::AddrNumOperands;
15322   SrcLoReg = MI->getOperand(CurOp++).getReg();
15323   SrcHiReg = MI->getOperand(CurOp++).getReg();
15324
15325   const TargetRegisterClass *RC = &X86::GR32RegClass;
15326   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15327
15328   unsigned t1L = MRI.createVirtualRegister(RC);
15329   unsigned t1H = MRI.createVirtualRegister(RC);
15330   unsigned t2L = MRI.createVirtualRegister(RC);
15331   unsigned t2H = MRI.createVirtualRegister(RC);
15332   unsigned t3L = MRI.createVirtualRegister(RC);
15333   unsigned t3H = MRI.createVirtualRegister(RC);
15334   unsigned t4L = MRI.createVirtualRegister(RC);
15335   unsigned t4H = MRI.createVirtualRegister(RC);
15336
15337   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15338   unsigned LOADOpc = X86::MOV32rm;
15339
15340   // For the atomic load-arith operator, we generate
15341   //
15342   //  thisMBB:
15343   //    t1L = LOAD [MI.addr + 0]
15344   //    t1H = LOAD [MI.addr + 4]
15345   //  mainMBB:
15346   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15347   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15348   //    t2L = OP MI.val.lo, t4L
15349   //    t2H = OP MI.val.hi, t4H
15350   //    EBX = t2L
15351   //    ECX = t2H
15352   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15353   //    t3L = EAX
15354   //    t3H = EDX
15355   //    JNE loop
15356   //  sinkMBB:
15357   //    dstL = t3L
15358   //    dstH = t3H
15359
15360   MachineBasicBlock *thisMBB = MBB;
15361   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15362   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15363   MF->insert(I, mainMBB);
15364   MF->insert(I, sinkMBB);
15365
15366   MachineInstrBuilder MIB;
15367
15368   // Transfer the remainder of BB and its successor edges to sinkMBB.
15369   sinkMBB->splice(sinkMBB->begin(), MBB,
15370                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15371   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15372
15373   // thisMBB:
15374   // Lo
15375   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15376   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15377     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15378     if (NewMO.isReg())
15379       NewMO.setIsKill(false);
15380     MIB.addOperand(NewMO);
15381   }
15382   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15383     unsigned flags = (*MMOI)->getFlags();
15384     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15385     MachineMemOperand *MMO =
15386       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15387                                (*MMOI)->getSize(),
15388                                (*MMOI)->getBaseAlignment(),
15389                                (*MMOI)->getTBAAInfo(),
15390                                (*MMOI)->getRanges());
15391     MIB.addMemOperand(MMO);
15392   };
15393   MachineInstr *LowMI = MIB;
15394
15395   // Hi
15396   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15397   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15398     if (i == X86::AddrDisp) {
15399       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15400     } else {
15401       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15402       if (NewMO.isReg())
15403         NewMO.setIsKill(false);
15404       MIB.addOperand(NewMO);
15405     }
15406   }
15407   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15408
15409   thisMBB->addSuccessor(mainMBB);
15410
15411   // mainMBB:
15412   MachineBasicBlock *origMainMBB = mainMBB;
15413
15414   // Add PHIs.
15415   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15416                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15417   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15418                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15419
15420   unsigned Opc = MI->getOpcode();
15421   switch (Opc) {
15422   default:
15423     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15424   case X86::ATOMAND6432:
15425   case X86::ATOMOR6432:
15426   case X86::ATOMXOR6432:
15427   case X86::ATOMADD6432:
15428   case X86::ATOMSUB6432: {
15429     unsigned HiOpc;
15430     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15431     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15432       .addReg(SrcLoReg);
15433     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15434       .addReg(SrcHiReg);
15435     break;
15436   }
15437   case X86::ATOMNAND6432: {
15438     unsigned HiOpc, NOTOpc;
15439     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15440     unsigned TmpL = MRI.createVirtualRegister(RC);
15441     unsigned TmpH = MRI.createVirtualRegister(RC);
15442     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15443       .addReg(t4L);
15444     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15445       .addReg(t4H);
15446     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15447     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15448     break;
15449   }
15450   case X86::ATOMMAX6432:
15451   case X86::ATOMMIN6432:
15452   case X86::ATOMUMAX6432:
15453   case X86::ATOMUMIN6432: {
15454     unsigned HiOpc;
15455     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15456     unsigned cL = MRI.createVirtualRegister(RC8);
15457     unsigned cH = MRI.createVirtualRegister(RC8);
15458     unsigned cL32 = MRI.createVirtualRegister(RC);
15459     unsigned cH32 = MRI.createVirtualRegister(RC);
15460     unsigned cc = MRI.createVirtualRegister(RC);
15461     // cl := cmp src_lo, lo
15462     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15463       .addReg(SrcLoReg).addReg(t4L);
15464     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15465     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15466     // ch := cmp src_hi, hi
15467     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15468       .addReg(SrcHiReg).addReg(t4H);
15469     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15470     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15471     // cc := if (src_hi == hi) ? cl : ch;
15472     if (Subtarget->hasCMov()) {
15473       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15474         .addReg(cH32).addReg(cL32);
15475     } else {
15476       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15477               .addReg(cH32).addReg(cL32)
15478               .addImm(X86::COND_E);
15479       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15480     }
15481     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15482     if (Subtarget->hasCMov()) {
15483       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15484         .addReg(SrcLoReg).addReg(t4L);
15485       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15486         .addReg(SrcHiReg).addReg(t4H);
15487     } else {
15488       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15489               .addReg(SrcLoReg).addReg(t4L)
15490               .addImm(X86::COND_NE);
15491       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15492       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15493       // 2nd CMOV lowering.
15494       mainMBB->addLiveIn(X86::EFLAGS);
15495       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15496               .addReg(SrcHiReg).addReg(t4H)
15497               .addImm(X86::COND_NE);
15498       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15499       // Replace the original PHI node as mainMBB is changed after CMOV
15500       // lowering.
15501       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15502         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15503       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15504         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15505       PhiL->eraseFromParent();
15506       PhiH->eraseFromParent();
15507     }
15508     break;
15509   }
15510   case X86::ATOMSWAP6432: {
15511     unsigned HiOpc;
15512     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15513     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15514     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15515     break;
15516   }
15517   }
15518
15519   // Copy EDX:EAX back from HiReg:LoReg
15520   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15521   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15522   // Copy ECX:EBX from t1H:t1L
15523   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15524   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15525
15526   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15527   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15528     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15529     if (NewMO.isReg())
15530       NewMO.setIsKill(false);
15531     MIB.addOperand(NewMO);
15532   }
15533   MIB.setMemRefs(MMOBegin, MMOEnd);
15534
15535   // Copy EDX:EAX back to t3H:t3L
15536   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15537   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15538
15539   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15540
15541   mainMBB->addSuccessor(origMainMBB);
15542   mainMBB->addSuccessor(sinkMBB);
15543
15544   // sinkMBB:
15545   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15546           TII->get(TargetOpcode::COPY), DstLoReg)
15547     .addReg(t3L);
15548   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15549           TII->get(TargetOpcode::COPY), DstHiReg)
15550     .addReg(t3H);
15551
15552   MI->eraseFromParent();
15553   return sinkMBB;
15554 }
15555
15556 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15557 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15558 // in the .td file.
15559 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15560                                        const TargetInstrInfo *TII) {
15561   unsigned Opc;
15562   switch (MI->getOpcode()) {
15563   default: llvm_unreachable("illegal opcode!");
15564   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15565   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15566   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15567   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15568   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15569   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15570   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15571   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15572   }
15573
15574   DebugLoc dl = MI->getDebugLoc();
15575   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15576
15577   unsigned NumArgs = MI->getNumOperands();
15578   for (unsigned i = 1; i < NumArgs; ++i) {
15579     MachineOperand &Op = MI->getOperand(i);
15580     if (!(Op.isReg() && Op.isImplicit()))
15581       MIB.addOperand(Op);
15582   }
15583   if (MI->hasOneMemOperand())
15584     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15585
15586   BuildMI(*BB, MI, dl,
15587     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15588     .addReg(X86::XMM0);
15589
15590   MI->eraseFromParent();
15591   return BB;
15592 }
15593
15594 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15595 // defs in an instruction pattern
15596 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15597                                        const TargetInstrInfo *TII) {
15598   unsigned Opc;
15599   switch (MI->getOpcode()) {
15600   default: llvm_unreachable("illegal opcode!");
15601   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15602   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15603   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15604   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15605   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15606   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15607   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15608   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15609   }
15610
15611   DebugLoc dl = MI->getDebugLoc();
15612   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15613
15614   unsigned NumArgs = MI->getNumOperands(); // remove the results
15615   for (unsigned i = 1; i < NumArgs; ++i) {
15616     MachineOperand &Op = MI->getOperand(i);
15617     if (!(Op.isReg() && Op.isImplicit()))
15618       MIB.addOperand(Op);
15619   }
15620   if (MI->hasOneMemOperand())
15621     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15622
15623   BuildMI(*BB, MI, dl,
15624     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15625     .addReg(X86::ECX);
15626
15627   MI->eraseFromParent();
15628   return BB;
15629 }
15630
15631 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15632                                        const TargetInstrInfo *TII,
15633                                        const X86Subtarget* Subtarget) {
15634   DebugLoc dl = MI->getDebugLoc();
15635
15636   // Address into RAX/EAX, other two args into ECX, EDX.
15637   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15638   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15639   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15640   for (int i = 0; i < X86::AddrNumOperands; ++i)
15641     MIB.addOperand(MI->getOperand(i));
15642
15643   unsigned ValOps = X86::AddrNumOperands;
15644   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15645     .addReg(MI->getOperand(ValOps).getReg());
15646   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15647     .addReg(MI->getOperand(ValOps+1).getReg());
15648
15649   // The instruction doesn't actually take any operands though.
15650   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15651
15652   MI->eraseFromParent(); // The pseudo is gone now.
15653   return BB;
15654 }
15655
15656 MachineBasicBlock *
15657 X86TargetLowering::EmitVAARG64WithCustomInserter(
15658                    MachineInstr *MI,
15659                    MachineBasicBlock *MBB) const {
15660   // Emit va_arg instruction on X86-64.
15661
15662   // Operands to this pseudo-instruction:
15663   // 0  ) Output        : destination address (reg)
15664   // 1-5) Input         : va_list address (addr, i64mem)
15665   // 6  ) ArgSize       : Size (in bytes) of vararg type
15666   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15667   // 8  ) Align         : Alignment of type
15668   // 9  ) EFLAGS (implicit-def)
15669
15670   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15671   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15672
15673   unsigned DestReg = MI->getOperand(0).getReg();
15674   MachineOperand &Base = MI->getOperand(1);
15675   MachineOperand &Scale = MI->getOperand(2);
15676   MachineOperand &Index = MI->getOperand(3);
15677   MachineOperand &Disp = MI->getOperand(4);
15678   MachineOperand &Segment = MI->getOperand(5);
15679   unsigned ArgSize = MI->getOperand(6).getImm();
15680   unsigned ArgMode = MI->getOperand(7).getImm();
15681   unsigned Align = MI->getOperand(8).getImm();
15682
15683   // Memory Reference
15684   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15685   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15686   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15687
15688   // Machine Information
15689   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15690   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15691   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15692   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15693   DebugLoc DL = MI->getDebugLoc();
15694
15695   // struct va_list {
15696   //   i32   gp_offset
15697   //   i32   fp_offset
15698   //   i64   overflow_area (address)
15699   //   i64   reg_save_area (address)
15700   // }
15701   // sizeof(va_list) = 24
15702   // alignment(va_list) = 8
15703
15704   unsigned TotalNumIntRegs = 6;
15705   unsigned TotalNumXMMRegs = 8;
15706   bool UseGPOffset = (ArgMode == 1);
15707   bool UseFPOffset = (ArgMode == 2);
15708   unsigned MaxOffset = TotalNumIntRegs * 8 +
15709                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15710
15711   /* Align ArgSize to a multiple of 8 */
15712   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15713   bool NeedsAlign = (Align > 8);
15714
15715   MachineBasicBlock *thisMBB = MBB;
15716   MachineBasicBlock *overflowMBB;
15717   MachineBasicBlock *offsetMBB;
15718   MachineBasicBlock *endMBB;
15719
15720   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15721   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15722   unsigned OffsetReg = 0;
15723
15724   if (!UseGPOffset && !UseFPOffset) {
15725     // If we only pull from the overflow region, we don't create a branch.
15726     // We don't need to alter control flow.
15727     OffsetDestReg = 0; // unused
15728     OverflowDestReg = DestReg;
15729
15730     offsetMBB = nullptr;
15731     overflowMBB = thisMBB;
15732     endMBB = thisMBB;
15733   } else {
15734     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15735     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15736     // If not, pull from overflow_area. (branch to overflowMBB)
15737     //
15738     //       thisMBB
15739     //         |     .
15740     //         |        .
15741     //     offsetMBB   overflowMBB
15742     //         |        .
15743     //         |     .
15744     //        endMBB
15745
15746     // Registers for the PHI in endMBB
15747     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15748     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15749
15750     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15751     MachineFunction *MF = MBB->getParent();
15752     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15753     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15754     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15755
15756     MachineFunction::iterator MBBIter = MBB;
15757     ++MBBIter;
15758
15759     // Insert the new basic blocks
15760     MF->insert(MBBIter, offsetMBB);
15761     MF->insert(MBBIter, overflowMBB);
15762     MF->insert(MBBIter, endMBB);
15763
15764     // Transfer the remainder of MBB and its successor edges to endMBB.
15765     endMBB->splice(endMBB->begin(), thisMBB,
15766                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15767     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15768
15769     // Make offsetMBB and overflowMBB successors of thisMBB
15770     thisMBB->addSuccessor(offsetMBB);
15771     thisMBB->addSuccessor(overflowMBB);
15772
15773     // endMBB is a successor of both offsetMBB and overflowMBB
15774     offsetMBB->addSuccessor(endMBB);
15775     overflowMBB->addSuccessor(endMBB);
15776
15777     // Load the offset value into a register
15778     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15779     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15780       .addOperand(Base)
15781       .addOperand(Scale)
15782       .addOperand(Index)
15783       .addDisp(Disp, UseFPOffset ? 4 : 0)
15784       .addOperand(Segment)
15785       .setMemRefs(MMOBegin, MMOEnd);
15786
15787     // Check if there is enough room left to pull this argument.
15788     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15789       .addReg(OffsetReg)
15790       .addImm(MaxOffset + 8 - ArgSizeA8);
15791
15792     // Branch to "overflowMBB" if offset >= max
15793     // Fall through to "offsetMBB" otherwise
15794     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15795       .addMBB(overflowMBB);
15796   }
15797
15798   // In offsetMBB, emit code to use the reg_save_area.
15799   if (offsetMBB) {
15800     assert(OffsetReg != 0);
15801
15802     // Read the reg_save_area address.
15803     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15804     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15805       .addOperand(Base)
15806       .addOperand(Scale)
15807       .addOperand(Index)
15808       .addDisp(Disp, 16)
15809       .addOperand(Segment)
15810       .setMemRefs(MMOBegin, MMOEnd);
15811
15812     // Zero-extend the offset
15813     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15814       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15815         .addImm(0)
15816         .addReg(OffsetReg)
15817         .addImm(X86::sub_32bit);
15818
15819     // Add the offset to the reg_save_area to get the final address.
15820     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15821       .addReg(OffsetReg64)
15822       .addReg(RegSaveReg);
15823
15824     // Compute the offset for the next argument
15825     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15826     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15827       .addReg(OffsetReg)
15828       .addImm(UseFPOffset ? 16 : 8);
15829
15830     // Store it back into the va_list.
15831     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15832       .addOperand(Base)
15833       .addOperand(Scale)
15834       .addOperand(Index)
15835       .addDisp(Disp, UseFPOffset ? 4 : 0)
15836       .addOperand(Segment)
15837       .addReg(NextOffsetReg)
15838       .setMemRefs(MMOBegin, MMOEnd);
15839
15840     // Jump to endMBB
15841     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15842       .addMBB(endMBB);
15843   }
15844
15845   //
15846   // Emit code to use overflow area
15847   //
15848
15849   // Load the overflow_area address into a register.
15850   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15851   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15852     .addOperand(Base)
15853     .addOperand(Scale)
15854     .addOperand(Index)
15855     .addDisp(Disp, 8)
15856     .addOperand(Segment)
15857     .setMemRefs(MMOBegin, MMOEnd);
15858
15859   // If we need to align it, do so. Otherwise, just copy the address
15860   // to OverflowDestReg.
15861   if (NeedsAlign) {
15862     // Align the overflow address
15863     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15864     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15865
15866     // aligned_addr = (addr + (align-1)) & ~(align-1)
15867     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15868       .addReg(OverflowAddrReg)
15869       .addImm(Align-1);
15870
15871     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15872       .addReg(TmpReg)
15873       .addImm(~(uint64_t)(Align-1));
15874   } else {
15875     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15876       .addReg(OverflowAddrReg);
15877   }
15878
15879   // Compute the next overflow address after this argument.
15880   // (the overflow address should be kept 8-byte aligned)
15881   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15882   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15883     .addReg(OverflowDestReg)
15884     .addImm(ArgSizeA8);
15885
15886   // Store the new overflow address.
15887   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15888     .addOperand(Base)
15889     .addOperand(Scale)
15890     .addOperand(Index)
15891     .addDisp(Disp, 8)
15892     .addOperand(Segment)
15893     .addReg(NextAddrReg)
15894     .setMemRefs(MMOBegin, MMOEnd);
15895
15896   // If we branched, emit the PHI to the front of endMBB.
15897   if (offsetMBB) {
15898     BuildMI(*endMBB, endMBB->begin(), DL,
15899             TII->get(X86::PHI), DestReg)
15900       .addReg(OffsetDestReg).addMBB(offsetMBB)
15901       .addReg(OverflowDestReg).addMBB(overflowMBB);
15902   }
15903
15904   // Erase the pseudo instruction
15905   MI->eraseFromParent();
15906
15907   return endMBB;
15908 }
15909
15910 MachineBasicBlock *
15911 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15912                                                  MachineInstr *MI,
15913                                                  MachineBasicBlock *MBB) const {
15914   // Emit code to save XMM registers to the stack. The ABI says that the
15915   // number of registers to save is given in %al, so it's theoretically
15916   // possible to do an indirect jump trick to avoid saving all of them,
15917   // however this code takes a simpler approach and just executes all
15918   // of the stores if %al is non-zero. It's less code, and it's probably
15919   // easier on the hardware branch predictor, and stores aren't all that
15920   // expensive anyway.
15921
15922   // Create the new basic blocks. One block contains all the XMM stores,
15923   // and one block is the final destination regardless of whether any
15924   // stores were performed.
15925   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15926   MachineFunction *F = MBB->getParent();
15927   MachineFunction::iterator MBBIter = MBB;
15928   ++MBBIter;
15929   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15930   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15931   F->insert(MBBIter, XMMSaveMBB);
15932   F->insert(MBBIter, EndMBB);
15933
15934   // Transfer the remainder of MBB and its successor edges to EndMBB.
15935   EndMBB->splice(EndMBB->begin(), MBB,
15936                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15937   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15938
15939   // The original block will now fall through to the XMM save block.
15940   MBB->addSuccessor(XMMSaveMBB);
15941   // The XMMSaveMBB will fall through to the end block.
15942   XMMSaveMBB->addSuccessor(EndMBB);
15943
15944   // Now add the instructions.
15945   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15946   DebugLoc DL = MI->getDebugLoc();
15947
15948   unsigned CountReg = MI->getOperand(0).getReg();
15949   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15950   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15951
15952   if (!Subtarget->isTargetWin64()) {
15953     // If %al is 0, branch around the XMM save block.
15954     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15955     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15956     MBB->addSuccessor(EndMBB);
15957   }
15958
15959   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15960   // that was just emitted, but clearly shouldn't be "saved".
15961   assert((MI->getNumOperands() <= 3 ||
15962           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15963           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15964          && "Expected last argument to be EFLAGS");
15965   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15966   // In the XMM save block, save all the XMM argument registers.
15967   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15968     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15969     MachineMemOperand *MMO =
15970       F->getMachineMemOperand(
15971           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15972         MachineMemOperand::MOStore,
15973         /*Size=*/16, /*Align=*/16);
15974     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15975       .addFrameIndex(RegSaveFrameIndex)
15976       .addImm(/*Scale=*/1)
15977       .addReg(/*IndexReg=*/0)
15978       .addImm(/*Disp=*/Offset)
15979       .addReg(/*Segment=*/0)
15980       .addReg(MI->getOperand(i).getReg())
15981       .addMemOperand(MMO);
15982   }
15983
15984   MI->eraseFromParent();   // The pseudo instruction is gone now.
15985
15986   return EndMBB;
15987 }
15988
15989 // The EFLAGS operand of SelectItr might be missing a kill marker
15990 // because there were multiple uses of EFLAGS, and ISel didn't know
15991 // which to mark. Figure out whether SelectItr should have had a
15992 // kill marker, and set it if it should. Returns the correct kill
15993 // marker value.
15994 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15995                                      MachineBasicBlock* BB,
15996                                      const TargetRegisterInfo* TRI) {
15997   // Scan forward through BB for a use/def of EFLAGS.
15998   MachineBasicBlock::iterator miI(std::next(SelectItr));
15999   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16000     const MachineInstr& mi = *miI;
16001     if (mi.readsRegister(X86::EFLAGS))
16002       return false;
16003     if (mi.definesRegister(X86::EFLAGS))
16004       break; // Should have kill-flag - update below.
16005   }
16006
16007   // If we hit the end of the block, check whether EFLAGS is live into a
16008   // successor.
16009   if (miI == BB->end()) {
16010     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16011                                           sEnd = BB->succ_end();
16012          sItr != sEnd; ++sItr) {
16013       MachineBasicBlock* succ = *sItr;
16014       if (succ->isLiveIn(X86::EFLAGS))
16015         return false;
16016     }
16017   }
16018
16019   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16020   // out. SelectMI should have a kill flag on EFLAGS.
16021   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16022   return true;
16023 }
16024
16025 MachineBasicBlock *
16026 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16027                                      MachineBasicBlock *BB) const {
16028   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16029   DebugLoc DL = MI->getDebugLoc();
16030
16031   // To "insert" a SELECT_CC instruction, we actually have to insert the
16032   // diamond control-flow pattern.  The incoming instruction knows the
16033   // destination vreg to set, the condition code register to branch on, the
16034   // true/false values to select between, and a branch opcode to use.
16035   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16036   MachineFunction::iterator It = BB;
16037   ++It;
16038
16039   //  thisMBB:
16040   //  ...
16041   //   TrueVal = ...
16042   //   cmpTY ccX, r1, r2
16043   //   bCC copy1MBB
16044   //   fallthrough --> copy0MBB
16045   MachineBasicBlock *thisMBB = BB;
16046   MachineFunction *F = BB->getParent();
16047   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16048   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16049   F->insert(It, copy0MBB);
16050   F->insert(It, sinkMBB);
16051
16052   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16053   // live into the sink and copy blocks.
16054   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16055   if (!MI->killsRegister(X86::EFLAGS) &&
16056       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16057     copy0MBB->addLiveIn(X86::EFLAGS);
16058     sinkMBB->addLiveIn(X86::EFLAGS);
16059   }
16060
16061   // Transfer the remainder of BB and its successor edges to sinkMBB.
16062   sinkMBB->splice(sinkMBB->begin(), BB,
16063                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16064   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16065
16066   // Add the true and fallthrough blocks as its successors.
16067   BB->addSuccessor(copy0MBB);
16068   BB->addSuccessor(sinkMBB);
16069
16070   // Create the conditional branch instruction.
16071   unsigned Opc =
16072     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16073   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16074
16075   //  copy0MBB:
16076   //   %FalseValue = ...
16077   //   # fallthrough to sinkMBB
16078   copy0MBB->addSuccessor(sinkMBB);
16079
16080   //  sinkMBB:
16081   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16082   //  ...
16083   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16084           TII->get(X86::PHI), MI->getOperand(0).getReg())
16085     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16086     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16087
16088   MI->eraseFromParent();   // The pseudo instruction is gone now.
16089   return sinkMBB;
16090 }
16091
16092 MachineBasicBlock *
16093 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16094                                         bool Is64Bit) const {
16095   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16096   DebugLoc DL = MI->getDebugLoc();
16097   MachineFunction *MF = BB->getParent();
16098   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16099
16100   assert(MF->shouldSplitStack());
16101
16102   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16103   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16104
16105   // BB:
16106   //  ... [Till the alloca]
16107   // If stacklet is not large enough, jump to mallocMBB
16108   //
16109   // bumpMBB:
16110   //  Allocate by subtracting from RSP
16111   //  Jump to continueMBB
16112   //
16113   // mallocMBB:
16114   //  Allocate by call to runtime
16115   //
16116   // continueMBB:
16117   //  ...
16118   //  [rest of original BB]
16119   //
16120
16121   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16122   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16123   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16124
16125   MachineRegisterInfo &MRI = MF->getRegInfo();
16126   const TargetRegisterClass *AddrRegClass =
16127     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16128
16129   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16130     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16131     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16132     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16133     sizeVReg = MI->getOperand(1).getReg(),
16134     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16135
16136   MachineFunction::iterator MBBIter = BB;
16137   ++MBBIter;
16138
16139   MF->insert(MBBIter, bumpMBB);
16140   MF->insert(MBBIter, mallocMBB);
16141   MF->insert(MBBIter, continueMBB);
16142
16143   continueMBB->splice(continueMBB->begin(), BB,
16144                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16145   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16146
16147   // Add code to the main basic block to check if the stack limit has been hit,
16148   // and if so, jump to mallocMBB otherwise to bumpMBB.
16149   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16150   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16151     .addReg(tmpSPVReg).addReg(sizeVReg);
16152   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16153     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16154     .addReg(SPLimitVReg);
16155   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16156
16157   // bumpMBB simply decreases the stack pointer, since we know the current
16158   // stacklet has enough space.
16159   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16160     .addReg(SPLimitVReg);
16161   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16162     .addReg(SPLimitVReg);
16163   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16164
16165   // Calls into a routine in libgcc to allocate more space from the heap.
16166   const uint32_t *RegMask =
16167     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16168   if (Is64Bit) {
16169     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16170       .addReg(sizeVReg);
16171     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16172       .addExternalSymbol("__morestack_allocate_stack_space")
16173       .addRegMask(RegMask)
16174       .addReg(X86::RDI, RegState::Implicit)
16175       .addReg(X86::RAX, RegState::ImplicitDefine);
16176   } else {
16177     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16178       .addImm(12);
16179     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16180     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16181       .addExternalSymbol("__morestack_allocate_stack_space")
16182       .addRegMask(RegMask)
16183       .addReg(X86::EAX, RegState::ImplicitDefine);
16184   }
16185
16186   if (!Is64Bit)
16187     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16188       .addImm(16);
16189
16190   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16191     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16192   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16193
16194   // Set up the CFG correctly.
16195   BB->addSuccessor(bumpMBB);
16196   BB->addSuccessor(mallocMBB);
16197   mallocMBB->addSuccessor(continueMBB);
16198   bumpMBB->addSuccessor(continueMBB);
16199
16200   // Take care of the PHI nodes.
16201   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16202           MI->getOperand(0).getReg())
16203     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16204     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16205
16206   // Delete the original pseudo instruction.
16207   MI->eraseFromParent();
16208
16209   // And we're done.
16210   return continueMBB;
16211 }
16212
16213 MachineBasicBlock *
16214 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16215                                           MachineBasicBlock *BB) const {
16216   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16217   DebugLoc DL = MI->getDebugLoc();
16218
16219   assert(!Subtarget->isTargetMacho());
16220
16221   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16222   // non-trivial part is impdef of ESP.
16223
16224   if (Subtarget->isTargetWin64()) {
16225     if (Subtarget->isTargetCygMing()) {
16226       // ___chkstk(Mingw64):
16227       // Clobbers R10, R11, RAX and EFLAGS.
16228       // Updates RSP.
16229       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16230         .addExternalSymbol("___chkstk")
16231         .addReg(X86::RAX, RegState::Implicit)
16232         .addReg(X86::RSP, RegState::Implicit)
16233         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16234         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16235         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16236     } else {
16237       // __chkstk(MSVCRT): does not update stack pointer.
16238       // Clobbers R10, R11 and EFLAGS.
16239       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16240         .addExternalSymbol("__chkstk")
16241         .addReg(X86::RAX, RegState::Implicit)
16242         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16243       // RAX has the offset to be subtracted from RSP.
16244       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16245         .addReg(X86::RSP)
16246         .addReg(X86::RAX);
16247     }
16248   } else {
16249     const char *StackProbeSymbol =
16250       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16251
16252     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16253       .addExternalSymbol(StackProbeSymbol)
16254       .addReg(X86::EAX, RegState::Implicit)
16255       .addReg(X86::ESP, RegState::Implicit)
16256       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16257       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16258       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16259   }
16260
16261   MI->eraseFromParent();   // The pseudo instruction is gone now.
16262   return BB;
16263 }
16264
16265 MachineBasicBlock *
16266 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16267                                       MachineBasicBlock *BB) const {
16268   // This is pretty easy.  We're taking the value that we received from
16269   // our load from the relocation, sticking it in either RDI (x86-64)
16270   // or EAX and doing an indirect call.  The return value will then
16271   // be in the normal return register.
16272   const X86InstrInfo *TII
16273     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16274   DebugLoc DL = MI->getDebugLoc();
16275   MachineFunction *F = BB->getParent();
16276
16277   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16278   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16279
16280   // Get a register mask for the lowered call.
16281   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16282   // proper register mask.
16283   const uint32_t *RegMask =
16284     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16285   if (Subtarget->is64Bit()) {
16286     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16287                                       TII->get(X86::MOV64rm), X86::RDI)
16288     .addReg(X86::RIP)
16289     .addImm(0).addReg(0)
16290     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16291                       MI->getOperand(3).getTargetFlags())
16292     .addReg(0);
16293     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16294     addDirectMem(MIB, X86::RDI);
16295     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16296   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16297     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16298                                       TII->get(X86::MOV32rm), X86::EAX)
16299     .addReg(0)
16300     .addImm(0).addReg(0)
16301     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16302                       MI->getOperand(3).getTargetFlags())
16303     .addReg(0);
16304     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16305     addDirectMem(MIB, X86::EAX);
16306     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16307   } else {
16308     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16309                                       TII->get(X86::MOV32rm), X86::EAX)
16310     .addReg(TII->getGlobalBaseReg(F))
16311     .addImm(0).addReg(0)
16312     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16313                       MI->getOperand(3).getTargetFlags())
16314     .addReg(0);
16315     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16316     addDirectMem(MIB, X86::EAX);
16317     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16318   }
16319
16320   MI->eraseFromParent(); // The pseudo instruction is gone now.
16321   return BB;
16322 }
16323
16324 MachineBasicBlock *
16325 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16326                                     MachineBasicBlock *MBB) const {
16327   DebugLoc DL = MI->getDebugLoc();
16328   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16329
16330   MachineFunction *MF = MBB->getParent();
16331   MachineRegisterInfo &MRI = MF->getRegInfo();
16332
16333   const BasicBlock *BB = MBB->getBasicBlock();
16334   MachineFunction::iterator I = MBB;
16335   ++I;
16336
16337   // Memory Reference
16338   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16339   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16340
16341   unsigned DstReg;
16342   unsigned MemOpndSlot = 0;
16343
16344   unsigned CurOp = 0;
16345
16346   DstReg = MI->getOperand(CurOp++).getReg();
16347   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16348   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16349   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16350   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16351
16352   MemOpndSlot = CurOp;
16353
16354   MVT PVT = getPointerTy();
16355   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16356          "Invalid Pointer Size!");
16357
16358   // For v = setjmp(buf), we generate
16359   //
16360   // thisMBB:
16361   //  buf[LabelOffset] = restoreMBB
16362   //  SjLjSetup restoreMBB
16363   //
16364   // mainMBB:
16365   //  v_main = 0
16366   //
16367   // sinkMBB:
16368   //  v = phi(main, restore)
16369   //
16370   // restoreMBB:
16371   //  v_restore = 1
16372
16373   MachineBasicBlock *thisMBB = MBB;
16374   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16375   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16376   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16377   MF->insert(I, mainMBB);
16378   MF->insert(I, sinkMBB);
16379   MF->push_back(restoreMBB);
16380
16381   MachineInstrBuilder MIB;
16382
16383   // Transfer the remainder of BB and its successor edges to sinkMBB.
16384   sinkMBB->splice(sinkMBB->begin(), MBB,
16385                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16386   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16387
16388   // thisMBB:
16389   unsigned PtrStoreOpc = 0;
16390   unsigned LabelReg = 0;
16391   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16392   Reloc::Model RM = getTargetMachine().getRelocationModel();
16393   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16394                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16395
16396   // Prepare IP either in reg or imm.
16397   if (!UseImmLabel) {
16398     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16399     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16400     LabelReg = MRI.createVirtualRegister(PtrRC);
16401     if (Subtarget->is64Bit()) {
16402       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16403               .addReg(X86::RIP)
16404               .addImm(0)
16405               .addReg(0)
16406               .addMBB(restoreMBB)
16407               .addReg(0);
16408     } else {
16409       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16410       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16411               .addReg(XII->getGlobalBaseReg(MF))
16412               .addImm(0)
16413               .addReg(0)
16414               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16415               .addReg(0);
16416     }
16417   } else
16418     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16419   // Store IP
16420   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16421   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16422     if (i == X86::AddrDisp)
16423       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16424     else
16425       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16426   }
16427   if (!UseImmLabel)
16428     MIB.addReg(LabelReg);
16429   else
16430     MIB.addMBB(restoreMBB);
16431   MIB.setMemRefs(MMOBegin, MMOEnd);
16432   // Setup
16433   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16434           .addMBB(restoreMBB);
16435
16436   const X86RegisterInfo *RegInfo =
16437     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16438   MIB.addRegMask(RegInfo->getNoPreservedMask());
16439   thisMBB->addSuccessor(mainMBB);
16440   thisMBB->addSuccessor(restoreMBB);
16441
16442   // mainMBB:
16443   //  EAX = 0
16444   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16445   mainMBB->addSuccessor(sinkMBB);
16446
16447   // sinkMBB:
16448   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16449           TII->get(X86::PHI), DstReg)
16450     .addReg(mainDstReg).addMBB(mainMBB)
16451     .addReg(restoreDstReg).addMBB(restoreMBB);
16452
16453   // restoreMBB:
16454   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16455   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16456   restoreMBB->addSuccessor(sinkMBB);
16457
16458   MI->eraseFromParent();
16459   return sinkMBB;
16460 }
16461
16462 MachineBasicBlock *
16463 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16464                                      MachineBasicBlock *MBB) const {
16465   DebugLoc DL = MI->getDebugLoc();
16466   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16467
16468   MachineFunction *MF = MBB->getParent();
16469   MachineRegisterInfo &MRI = MF->getRegInfo();
16470
16471   // Memory Reference
16472   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16473   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16474
16475   MVT PVT = getPointerTy();
16476   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16477          "Invalid Pointer Size!");
16478
16479   const TargetRegisterClass *RC =
16480     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16481   unsigned Tmp = MRI.createVirtualRegister(RC);
16482   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16483   const X86RegisterInfo *RegInfo =
16484     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16485   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16486   unsigned SP = RegInfo->getStackRegister();
16487
16488   MachineInstrBuilder MIB;
16489
16490   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16491   const int64_t SPOffset = 2 * PVT.getStoreSize();
16492
16493   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16494   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16495
16496   // Reload FP
16497   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16498   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16499     MIB.addOperand(MI->getOperand(i));
16500   MIB.setMemRefs(MMOBegin, MMOEnd);
16501   // Reload IP
16502   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16503   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16504     if (i == X86::AddrDisp)
16505       MIB.addDisp(MI->getOperand(i), LabelOffset);
16506     else
16507       MIB.addOperand(MI->getOperand(i));
16508   }
16509   MIB.setMemRefs(MMOBegin, MMOEnd);
16510   // Reload SP
16511   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16512   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16513     if (i == X86::AddrDisp)
16514       MIB.addDisp(MI->getOperand(i), SPOffset);
16515     else
16516       MIB.addOperand(MI->getOperand(i));
16517   }
16518   MIB.setMemRefs(MMOBegin, MMOEnd);
16519   // Jump
16520   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16521
16522   MI->eraseFromParent();
16523   return MBB;
16524 }
16525
16526 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16527 // accumulator loops. Writing back to the accumulator allows the coalescer
16528 // to remove extra copies in the loop.   
16529 MachineBasicBlock *
16530 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16531                                  MachineBasicBlock *MBB) const {
16532   MachineOperand &AddendOp = MI->getOperand(3);
16533
16534   // Bail out early if the addend isn't a register - we can't switch these.
16535   if (!AddendOp.isReg())
16536     return MBB;
16537
16538   MachineFunction &MF = *MBB->getParent();
16539   MachineRegisterInfo &MRI = MF.getRegInfo();
16540
16541   // Check whether the addend is defined by a PHI:
16542   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16543   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16544   if (!AddendDef.isPHI())
16545     return MBB;
16546
16547   // Look for the following pattern:
16548   // loop:
16549   //   %addend = phi [%entry, 0], [%loop, %result]
16550   //   ...
16551   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16552
16553   // Replace with:
16554   //   loop:
16555   //   %addend = phi [%entry, 0], [%loop, %result]
16556   //   ...
16557   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16558
16559   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16560     assert(AddendDef.getOperand(i).isReg());
16561     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16562     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16563     if (&PHISrcInst == MI) {
16564       // Found a matching instruction.
16565       unsigned NewFMAOpc = 0;
16566       switch (MI->getOpcode()) {
16567         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16568         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16569         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16570         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16571         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16572         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16573         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16574         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16575         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16576         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16577         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16578         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16579         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16580         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16581         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16582         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16583         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16584         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16585         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16586         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16587         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16588         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16589         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16590         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16591         default: llvm_unreachable("Unrecognized FMA variant.");
16592       }
16593
16594       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16595       MachineInstrBuilder MIB =
16596         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16597         .addOperand(MI->getOperand(0))
16598         .addOperand(MI->getOperand(3))
16599         .addOperand(MI->getOperand(2))
16600         .addOperand(MI->getOperand(1));
16601       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16602       MI->eraseFromParent();
16603     }
16604   }
16605
16606   return MBB;
16607 }
16608
16609 MachineBasicBlock *
16610 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16611                                                MachineBasicBlock *BB) const {
16612   switch (MI->getOpcode()) {
16613   default: llvm_unreachable("Unexpected instr type to insert");
16614   case X86::TAILJMPd64:
16615   case X86::TAILJMPr64:
16616   case X86::TAILJMPm64:
16617     llvm_unreachable("TAILJMP64 would not be touched here.");
16618   case X86::TCRETURNdi64:
16619   case X86::TCRETURNri64:
16620   case X86::TCRETURNmi64:
16621     return BB;
16622   case X86::WIN_ALLOCA:
16623     return EmitLoweredWinAlloca(MI, BB);
16624   case X86::SEG_ALLOCA_32:
16625     return EmitLoweredSegAlloca(MI, BB, false);
16626   case X86::SEG_ALLOCA_64:
16627     return EmitLoweredSegAlloca(MI, BB, true);
16628   case X86::TLSCall_32:
16629   case X86::TLSCall_64:
16630     return EmitLoweredTLSCall(MI, BB);
16631   case X86::CMOV_GR8:
16632   case X86::CMOV_FR32:
16633   case X86::CMOV_FR64:
16634   case X86::CMOV_V4F32:
16635   case X86::CMOV_V2F64:
16636   case X86::CMOV_V2I64:
16637   case X86::CMOV_V8F32:
16638   case X86::CMOV_V4F64:
16639   case X86::CMOV_V4I64:
16640   case X86::CMOV_V16F32:
16641   case X86::CMOV_V8F64:
16642   case X86::CMOV_V8I64:
16643   case X86::CMOV_GR16:
16644   case X86::CMOV_GR32:
16645   case X86::CMOV_RFP32:
16646   case X86::CMOV_RFP64:
16647   case X86::CMOV_RFP80:
16648     return EmitLoweredSelect(MI, BB);
16649
16650   case X86::FP32_TO_INT16_IN_MEM:
16651   case X86::FP32_TO_INT32_IN_MEM:
16652   case X86::FP32_TO_INT64_IN_MEM:
16653   case X86::FP64_TO_INT16_IN_MEM:
16654   case X86::FP64_TO_INT32_IN_MEM:
16655   case X86::FP64_TO_INT64_IN_MEM:
16656   case X86::FP80_TO_INT16_IN_MEM:
16657   case X86::FP80_TO_INT32_IN_MEM:
16658   case X86::FP80_TO_INT64_IN_MEM: {
16659     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16660     DebugLoc DL = MI->getDebugLoc();
16661
16662     // Change the floating point control register to use "round towards zero"
16663     // mode when truncating to an integer value.
16664     MachineFunction *F = BB->getParent();
16665     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16666     addFrameReference(BuildMI(*BB, MI, DL,
16667                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16668
16669     // Load the old value of the high byte of the control word...
16670     unsigned OldCW =
16671       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16672     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16673                       CWFrameIdx);
16674
16675     // Set the high part to be round to zero...
16676     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16677       .addImm(0xC7F);
16678
16679     // Reload the modified control word now...
16680     addFrameReference(BuildMI(*BB, MI, DL,
16681                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16682
16683     // Restore the memory image of control word to original value
16684     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16685       .addReg(OldCW);
16686
16687     // Get the X86 opcode to use.
16688     unsigned Opc;
16689     switch (MI->getOpcode()) {
16690     default: llvm_unreachable("illegal opcode!");
16691     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16692     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16693     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16694     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16695     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16696     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16697     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16698     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16699     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16700     }
16701
16702     X86AddressMode AM;
16703     MachineOperand &Op = MI->getOperand(0);
16704     if (Op.isReg()) {
16705       AM.BaseType = X86AddressMode::RegBase;
16706       AM.Base.Reg = Op.getReg();
16707     } else {
16708       AM.BaseType = X86AddressMode::FrameIndexBase;
16709       AM.Base.FrameIndex = Op.getIndex();
16710     }
16711     Op = MI->getOperand(1);
16712     if (Op.isImm())
16713       AM.Scale = Op.getImm();
16714     Op = MI->getOperand(2);
16715     if (Op.isImm())
16716       AM.IndexReg = Op.getImm();
16717     Op = MI->getOperand(3);
16718     if (Op.isGlobal()) {
16719       AM.GV = Op.getGlobal();
16720     } else {
16721       AM.Disp = Op.getImm();
16722     }
16723     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16724                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16725
16726     // Reload the original control word now.
16727     addFrameReference(BuildMI(*BB, MI, DL,
16728                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16729
16730     MI->eraseFromParent();   // The pseudo instruction is gone now.
16731     return BB;
16732   }
16733     // String/text processing lowering.
16734   case X86::PCMPISTRM128REG:
16735   case X86::VPCMPISTRM128REG:
16736   case X86::PCMPISTRM128MEM:
16737   case X86::VPCMPISTRM128MEM:
16738   case X86::PCMPESTRM128REG:
16739   case X86::VPCMPESTRM128REG:
16740   case X86::PCMPESTRM128MEM:
16741   case X86::VPCMPESTRM128MEM:
16742     assert(Subtarget->hasSSE42() &&
16743            "Target must have SSE4.2 or AVX features enabled");
16744     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16745
16746   // String/text processing lowering.
16747   case X86::PCMPISTRIREG:
16748   case X86::VPCMPISTRIREG:
16749   case X86::PCMPISTRIMEM:
16750   case X86::VPCMPISTRIMEM:
16751   case X86::PCMPESTRIREG:
16752   case X86::VPCMPESTRIREG:
16753   case X86::PCMPESTRIMEM:
16754   case X86::VPCMPESTRIMEM:
16755     assert(Subtarget->hasSSE42() &&
16756            "Target must have SSE4.2 or AVX features enabled");
16757     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16758
16759   // Thread synchronization.
16760   case X86::MONITOR:
16761     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16762
16763   // xbegin
16764   case X86::XBEGIN:
16765     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16766
16767   // Atomic Lowering.
16768   case X86::ATOMAND8:
16769   case X86::ATOMAND16:
16770   case X86::ATOMAND32:
16771   case X86::ATOMAND64:
16772     // Fall through
16773   case X86::ATOMOR8:
16774   case X86::ATOMOR16:
16775   case X86::ATOMOR32:
16776   case X86::ATOMOR64:
16777     // Fall through
16778   case X86::ATOMXOR16:
16779   case X86::ATOMXOR8:
16780   case X86::ATOMXOR32:
16781   case X86::ATOMXOR64:
16782     // Fall through
16783   case X86::ATOMNAND8:
16784   case X86::ATOMNAND16:
16785   case X86::ATOMNAND32:
16786   case X86::ATOMNAND64:
16787     // Fall through
16788   case X86::ATOMMAX8:
16789   case X86::ATOMMAX16:
16790   case X86::ATOMMAX32:
16791   case X86::ATOMMAX64:
16792     // Fall through
16793   case X86::ATOMMIN8:
16794   case X86::ATOMMIN16:
16795   case X86::ATOMMIN32:
16796   case X86::ATOMMIN64:
16797     // Fall through
16798   case X86::ATOMUMAX8:
16799   case X86::ATOMUMAX16:
16800   case X86::ATOMUMAX32:
16801   case X86::ATOMUMAX64:
16802     // Fall through
16803   case X86::ATOMUMIN8:
16804   case X86::ATOMUMIN16:
16805   case X86::ATOMUMIN32:
16806   case X86::ATOMUMIN64:
16807     return EmitAtomicLoadArith(MI, BB);
16808
16809   // This group does 64-bit operations on a 32-bit host.
16810   case X86::ATOMAND6432:
16811   case X86::ATOMOR6432:
16812   case X86::ATOMXOR6432:
16813   case X86::ATOMNAND6432:
16814   case X86::ATOMADD6432:
16815   case X86::ATOMSUB6432:
16816   case X86::ATOMMAX6432:
16817   case X86::ATOMMIN6432:
16818   case X86::ATOMUMAX6432:
16819   case X86::ATOMUMIN6432:
16820   case X86::ATOMSWAP6432:
16821     return EmitAtomicLoadArith6432(MI, BB);
16822
16823   case X86::VASTART_SAVE_XMM_REGS:
16824     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16825
16826   case X86::VAARG_64:
16827     return EmitVAARG64WithCustomInserter(MI, BB);
16828
16829   case X86::EH_SjLj_SetJmp32:
16830   case X86::EH_SjLj_SetJmp64:
16831     return emitEHSjLjSetJmp(MI, BB);
16832
16833   case X86::EH_SjLj_LongJmp32:
16834   case X86::EH_SjLj_LongJmp64:
16835     return emitEHSjLjLongJmp(MI, BB);
16836
16837   case TargetOpcode::STACKMAP:
16838   case TargetOpcode::PATCHPOINT:
16839     return emitPatchPoint(MI, BB);
16840
16841   case X86::VFMADDPDr213r:
16842   case X86::VFMADDPSr213r:
16843   case X86::VFMADDSDr213r:
16844   case X86::VFMADDSSr213r:
16845   case X86::VFMSUBPDr213r:
16846   case X86::VFMSUBPSr213r:
16847   case X86::VFMSUBSDr213r:
16848   case X86::VFMSUBSSr213r:
16849   case X86::VFNMADDPDr213r:
16850   case X86::VFNMADDPSr213r:
16851   case X86::VFNMADDSDr213r:
16852   case X86::VFNMADDSSr213r:
16853   case X86::VFNMSUBPDr213r:
16854   case X86::VFNMSUBPSr213r:
16855   case X86::VFNMSUBSDr213r:
16856   case X86::VFNMSUBSSr213r:
16857   case X86::VFMADDPDr213rY:
16858   case X86::VFMADDPSr213rY:
16859   case X86::VFMSUBPDr213rY:
16860   case X86::VFMSUBPSr213rY:
16861   case X86::VFNMADDPDr213rY:
16862   case X86::VFNMADDPSr213rY:
16863   case X86::VFNMSUBPDr213rY:
16864   case X86::VFNMSUBPSr213rY:
16865     return emitFMA3Instr(MI, BB);
16866   }
16867 }
16868
16869 //===----------------------------------------------------------------------===//
16870 //                           X86 Optimization Hooks
16871 //===----------------------------------------------------------------------===//
16872
16873 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16874                                                        APInt &KnownZero,
16875                                                        APInt &KnownOne,
16876                                                        const SelectionDAG &DAG,
16877                                                        unsigned Depth) const {
16878   unsigned BitWidth = KnownZero.getBitWidth();
16879   unsigned Opc = Op.getOpcode();
16880   assert((Opc >= ISD::BUILTIN_OP_END ||
16881           Opc == ISD::INTRINSIC_WO_CHAIN ||
16882           Opc == ISD::INTRINSIC_W_CHAIN ||
16883           Opc == ISD::INTRINSIC_VOID) &&
16884          "Should use MaskedValueIsZero if you don't know whether Op"
16885          " is a target node!");
16886
16887   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16888   switch (Opc) {
16889   default: break;
16890   case X86ISD::ADD:
16891   case X86ISD::SUB:
16892   case X86ISD::ADC:
16893   case X86ISD::SBB:
16894   case X86ISD::SMUL:
16895   case X86ISD::UMUL:
16896   case X86ISD::INC:
16897   case X86ISD::DEC:
16898   case X86ISD::OR:
16899   case X86ISD::XOR:
16900   case X86ISD::AND:
16901     // These nodes' second result is a boolean.
16902     if (Op.getResNo() == 0)
16903       break;
16904     // Fallthrough
16905   case X86ISD::SETCC:
16906     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16907     break;
16908   case ISD::INTRINSIC_WO_CHAIN: {
16909     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16910     unsigned NumLoBits = 0;
16911     switch (IntId) {
16912     default: break;
16913     case Intrinsic::x86_sse_movmsk_ps:
16914     case Intrinsic::x86_avx_movmsk_ps_256:
16915     case Intrinsic::x86_sse2_movmsk_pd:
16916     case Intrinsic::x86_avx_movmsk_pd_256:
16917     case Intrinsic::x86_mmx_pmovmskb:
16918     case Intrinsic::x86_sse2_pmovmskb_128:
16919     case Intrinsic::x86_avx2_pmovmskb: {
16920       // High bits of movmskp{s|d}, pmovmskb are known zero.
16921       switch (IntId) {
16922         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16923         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16924         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16925         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16926         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16927         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16928         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16929         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16930       }
16931       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16932       break;
16933     }
16934     }
16935     break;
16936   }
16937   }
16938 }
16939
16940 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16941   SDValue Op,
16942   const SelectionDAG &,
16943   unsigned Depth) const {
16944   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16945   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16946     return Op.getValueType().getScalarType().getSizeInBits();
16947
16948   // Fallback case.
16949   return 1;
16950 }
16951
16952 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16953 /// node is a GlobalAddress + offset.
16954 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16955                                        const GlobalValue* &GA,
16956                                        int64_t &Offset) const {
16957   if (N->getOpcode() == X86ISD::Wrapper) {
16958     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16959       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16960       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16961       return true;
16962     }
16963   }
16964   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16965 }
16966
16967 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16968 /// same as extracting the high 128-bit part of 256-bit vector and then
16969 /// inserting the result into the low part of a new 256-bit vector
16970 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16971   EVT VT = SVOp->getValueType(0);
16972   unsigned NumElems = VT.getVectorNumElements();
16973
16974   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16975   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16976     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16977         SVOp->getMaskElt(j) >= 0)
16978       return false;
16979
16980   return true;
16981 }
16982
16983 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16984 /// same as extracting the low 128-bit part of 256-bit vector and then
16985 /// inserting the result into the high part of a new 256-bit vector
16986 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16987   EVT VT = SVOp->getValueType(0);
16988   unsigned NumElems = VT.getVectorNumElements();
16989
16990   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16991   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16992     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16993         SVOp->getMaskElt(j) >= 0)
16994       return false;
16995
16996   return true;
16997 }
16998
16999 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17000 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17001                                         TargetLowering::DAGCombinerInfo &DCI,
17002                                         const X86Subtarget* Subtarget) {
17003   SDLoc dl(N);
17004   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17005   SDValue V1 = SVOp->getOperand(0);
17006   SDValue V2 = SVOp->getOperand(1);
17007   EVT VT = SVOp->getValueType(0);
17008   unsigned NumElems = VT.getVectorNumElements();
17009
17010   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17011       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17012     //
17013     //                   0,0,0,...
17014     //                      |
17015     //    V      UNDEF    BUILD_VECTOR    UNDEF
17016     //     \      /           \           /
17017     //  CONCAT_VECTOR         CONCAT_VECTOR
17018     //         \                  /
17019     //          \                /
17020     //          RESULT: V + zero extended
17021     //
17022     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17023         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17024         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17025       return SDValue();
17026
17027     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17028       return SDValue();
17029
17030     // To match the shuffle mask, the first half of the mask should
17031     // be exactly the first vector, and all the rest a splat with the
17032     // first element of the second one.
17033     for (unsigned i = 0; i != NumElems/2; ++i)
17034       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17035           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17036         return SDValue();
17037
17038     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17039     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17040       if (Ld->hasNUsesOfValue(1, 0)) {
17041         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17042         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17043         SDValue ResNode =
17044           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17045                                   array_lengthof(Ops),
17046                                   Ld->getMemoryVT(),
17047                                   Ld->getPointerInfo(),
17048                                   Ld->getAlignment(),
17049                                   false/*isVolatile*/, true/*ReadMem*/,
17050                                   false/*WriteMem*/);
17051
17052         // Make sure the newly-created LOAD is in the same position as Ld in
17053         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17054         // and update uses of Ld's output chain to use the TokenFactor.
17055         if (Ld->hasAnyUseOfValue(1)) {
17056           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17057                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17058           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17059           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17060                                  SDValue(ResNode.getNode(), 1));
17061         }
17062
17063         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17064       }
17065     }
17066
17067     // Emit a zeroed vector and insert the desired subvector on its
17068     // first half.
17069     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17070     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17071     return DCI.CombineTo(N, InsV);
17072   }
17073
17074   //===--------------------------------------------------------------------===//
17075   // Combine some shuffles into subvector extracts and inserts:
17076   //
17077
17078   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17079   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17080     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17081     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17082     return DCI.CombineTo(N, InsV);
17083   }
17084
17085   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17086   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17087     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17088     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17089     return DCI.CombineTo(N, InsV);
17090   }
17091
17092   return SDValue();
17093 }
17094
17095 /// PerformShuffleCombine - Performs several different shuffle combines.
17096 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17097                                      TargetLowering::DAGCombinerInfo &DCI,
17098                                      const X86Subtarget *Subtarget) {
17099   SDLoc dl(N);
17100   EVT VT = N->getValueType(0);
17101
17102   // Don't create instructions with illegal types after legalize types has run.
17103   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17104   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17105     return SDValue();
17106
17107   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17108   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17109       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17110     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17111
17112   // Only handle 128 wide vector from here on.
17113   if (!VT.is128BitVector())
17114     return SDValue();
17115
17116   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17117   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17118   // consecutive, non-overlapping, and in the right order.
17119   SmallVector<SDValue, 16> Elts;
17120   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17121     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17122
17123   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17124 }
17125
17126 /// PerformTruncateCombine - Converts truncate operation to
17127 /// a sequence of vector shuffle operations.
17128 /// It is possible when we truncate 256-bit vector to 128-bit vector
17129 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17130                                       TargetLowering::DAGCombinerInfo &DCI,
17131                                       const X86Subtarget *Subtarget)  {
17132   return SDValue();
17133 }
17134
17135 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17136 /// specific shuffle of a load can be folded into a single element load.
17137 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17138 /// shuffles have been customed lowered so we need to handle those here.
17139 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17140                                          TargetLowering::DAGCombinerInfo &DCI) {
17141   if (DCI.isBeforeLegalizeOps())
17142     return SDValue();
17143
17144   SDValue InVec = N->getOperand(0);
17145   SDValue EltNo = N->getOperand(1);
17146
17147   if (!isa<ConstantSDNode>(EltNo))
17148     return SDValue();
17149
17150   EVT VT = InVec.getValueType();
17151
17152   bool HasShuffleIntoBitcast = false;
17153   if (InVec.getOpcode() == ISD::BITCAST) {
17154     // Don't duplicate a load with other uses.
17155     if (!InVec.hasOneUse())
17156       return SDValue();
17157     EVT BCVT = InVec.getOperand(0).getValueType();
17158     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17159       return SDValue();
17160     InVec = InVec.getOperand(0);
17161     HasShuffleIntoBitcast = true;
17162   }
17163
17164   if (!isTargetShuffle(InVec.getOpcode()))
17165     return SDValue();
17166
17167   // Don't duplicate a load with other uses.
17168   if (!InVec.hasOneUse())
17169     return SDValue();
17170
17171   SmallVector<int, 16> ShuffleMask;
17172   bool UnaryShuffle;
17173   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17174                             UnaryShuffle))
17175     return SDValue();
17176
17177   // Select the input vector, guarding against out of range extract vector.
17178   unsigned NumElems = VT.getVectorNumElements();
17179   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17180   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17181   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17182                                          : InVec.getOperand(1);
17183
17184   // If inputs to shuffle are the same for both ops, then allow 2 uses
17185   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17186
17187   if (LdNode.getOpcode() == ISD::BITCAST) {
17188     // Don't duplicate a load with other uses.
17189     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17190       return SDValue();
17191
17192     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17193     LdNode = LdNode.getOperand(0);
17194   }
17195
17196   if (!ISD::isNormalLoad(LdNode.getNode()))
17197     return SDValue();
17198
17199   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17200
17201   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17202     return SDValue();
17203
17204   if (HasShuffleIntoBitcast) {
17205     // If there's a bitcast before the shuffle, check if the load type and
17206     // alignment is valid.
17207     unsigned Align = LN0->getAlignment();
17208     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17209     unsigned NewAlign = TLI.getDataLayout()->
17210       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17211
17212     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17213       return SDValue();
17214   }
17215
17216   // All checks match so transform back to vector_shuffle so that DAG combiner
17217   // can finish the job
17218   SDLoc dl(N);
17219
17220   // Create shuffle node taking into account the case that its a unary shuffle
17221   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17222   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17223                                  InVec.getOperand(0), Shuffle,
17224                                  &ShuffleMask[0]);
17225   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17226   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17227                      EltNo);
17228 }
17229
17230 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17231 /// generation and convert it from being a bunch of shuffles and extracts
17232 /// to a simple store and scalar loads to extract the elements.
17233 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17234                                          TargetLowering::DAGCombinerInfo &DCI) {
17235   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17236   if (NewOp.getNode())
17237     return NewOp;
17238
17239   SDValue InputVector = N->getOperand(0);
17240
17241   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17242   // from mmx to v2i32 has a single usage.
17243   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17244       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17245       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17246     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17247                        N->getValueType(0),
17248                        InputVector.getNode()->getOperand(0));
17249
17250   // Only operate on vectors of 4 elements, where the alternative shuffling
17251   // gets to be more expensive.
17252   if (InputVector.getValueType() != MVT::v4i32)
17253     return SDValue();
17254
17255   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17256   // single use which is a sign-extend or zero-extend, and all elements are
17257   // used.
17258   SmallVector<SDNode *, 4> Uses;
17259   unsigned ExtractedElements = 0;
17260   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17261        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17262     if (UI.getUse().getResNo() != InputVector.getResNo())
17263       return SDValue();
17264
17265     SDNode *Extract = *UI;
17266     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17267       return SDValue();
17268
17269     if (Extract->getValueType(0) != MVT::i32)
17270       return SDValue();
17271     if (!Extract->hasOneUse())
17272       return SDValue();
17273     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17274         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17275       return SDValue();
17276     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17277       return SDValue();
17278
17279     // Record which element was extracted.
17280     ExtractedElements |=
17281       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17282
17283     Uses.push_back(Extract);
17284   }
17285
17286   // If not all the elements were used, this may not be worthwhile.
17287   if (ExtractedElements != 15)
17288     return SDValue();
17289
17290   // Ok, we've now decided to do the transformation.
17291   SDLoc dl(InputVector);
17292
17293   // Store the value to a temporary stack slot.
17294   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17295   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17296                             MachinePointerInfo(), false, false, 0);
17297
17298   // Replace each use (extract) with a load of the appropriate element.
17299   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17300        UE = Uses.end(); UI != UE; ++UI) {
17301     SDNode *Extract = *UI;
17302
17303     // cOMpute the element's address.
17304     SDValue Idx = Extract->getOperand(1);
17305     unsigned EltSize =
17306         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17307     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17308     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17309     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17310
17311     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17312                                      StackPtr, OffsetVal);
17313
17314     // Load the scalar.
17315     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17316                                      ScalarAddr, MachinePointerInfo(),
17317                                      false, false, false, 0);
17318
17319     // Replace the exact with the load.
17320     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17321   }
17322
17323   // The replacement was made in place; don't return anything.
17324   return SDValue();
17325 }
17326
17327 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17328 static std::pair<unsigned, bool>
17329 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17330                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17331   if (!VT.isVector())
17332     return std::make_pair(0, false);
17333
17334   bool NeedSplit = false;
17335   switch (VT.getSimpleVT().SimpleTy) {
17336   default: return std::make_pair(0, false);
17337   case MVT::v32i8:
17338   case MVT::v16i16:
17339   case MVT::v8i32:
17340     if (!Subtarget->hasAVX2())
17341       NeedSplit = true;
17342     if (!Subtarget->hasAVX())
17343       return std::make_pair(0, false);
17344     break;
17345   case MVT::v16i8:
17346   case MVT::v8i16:
17347   case MVT::v4i32:
17348     if (!Subtarget->hasSSE2())
17349       return std::make_pair(0, false);
17350   }
17351
17352   // SSE2 has only a small subset of the operations.
17353   bool hasUnsigned = Subtarget->hasSSE41() ||
17354                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17355   bool hasSigned = Subtarget->hasSSE41() ||
17356                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17357
17358   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17359
17360   unsigned Opc = 0;
17361   // Check for x CC y ? x : y.
17362   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17363       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17364     switch (CC) {
17365     default: break;
17366     case ISD::SETULT:
17367     case ISD::SETULE:
17368       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17369     case ISD::SETUGT:
17370     case ISD::SETUGE:
17371       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17372     case ISD::SETLT:
17373     case ISD::SETLE:
17374       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17375     case ISD::SETGT:
17376     case ISD::SETGE:
17377       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17378     }
17379   // Check for x CC y ? y : x -- a min/max with reversed arms.
17380   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17381              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17382     switch (CC) {
17383     default: break;
17384     case ISD::SETULT:
17385     case ISD::SETULE:
17386       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17387     case ISD::SETUGT:
17388     case ISD::SETUGE:
17389       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17390     case ISD::SETLT:
17391     case ISD::SETLE:
17392       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17393     case ISD::SETGT:
17394     case ISD::SETGE:
17395       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17396     }
17397   }
17398
17399   return std::make_pair(Opc, NeedSplit);
17400 }
17401
17402 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17403 /// nodes.
17404 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17405                                     TargetLowering::DAGCombinerInfo &DCI,
17406                                     const X86Subtarget *Subtarget) {
17407   SDLoc DL(N);
17408   SDValue Cond = N->getOperand(0);
17409   // Get the LHS/RHS of the select.
17410   SDValue LHS = N->getOperand(1);
17411   SDValue RHS = N->getOperand(2);
17412   EVT VT = LHS.getValueType();
17413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17414
17415   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17416   // instructions match the semantics of the common C idiom x<y?x:y but not
17417   // x<=y?x:y, because of how they handle negative zero (which can be
17418   // ignored in unsafe-math mode).
17419   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17420       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17421       (Subtarget->hasSSE2() ||
17422        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17423     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17424
17425     unsigned Opcode = 0;
17426     // Check for x CC y ? x : y.
17427     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17428         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17429       switch (CC) {
17430       default: break;
17431       case ISD::SETULT:
17432         // Converting this to a min would handle NaNs incorrectly, and swapping
17433         // the operands would cause it to handle comparisons between positive
17434         // and negative zero incorrectly.
17435         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17436           if (!DAG.getTarget().Options.UnsafeFPMath &&
17437               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17438             break;
17439           std::swap(LHS, RHS);
17440         }
17441         Opcode = X86ISD::FMIN;
17442         break;
17443       case ISD::SETOLE:
17444         // Converting this to a min would handle comparisons between positive
17445         // and negative zero incorrectly.
17446         if (!DAG.getTarget().Options.UnsafeFPMath &&
17447             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17448           break;
17449         Opcode = X86ISD::FMIN;
17450         break;
17451       case ISD::SETULE:
17452         // Converting this to a min would handle both negative zeros and NaNs
17453         // incorrectly, but we can swap the operands to fix both.
17454         std::swap(LHS, RHS);
17455       case ISD::SETOLT:
17456       case ISD::SETLT:
17457       case ISD::SETLE:
17458         Opcode = X86ISD::FMIN;
17459         break;
17460
17461       case ISD::SETOGE:
17462         // Converting this to a max would handle comparisons between positive
17463         // and negative zero incorrectly.
17464         if (!DAG.getTarget().Options.UnsafeFPMath &&
17465             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17466           break;
17467         Opcode = X86ISD::FMAX;
17468         break;
17469       case ISD::SETUGT:
17470         // Converting this to a max would handle NaNs incorrectly, and swapping
17471         // the operands would cause it to handle comparisons between positive
17472         // and negative zero incorrectly.
17473         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17474           if (!DAG.getTarget().Options.UnsafeFPMath &&
17475               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17476             break;
17477           std::swap(LHS, RHS);
17478         }
17479         Opcode = X86ISD::FMAX;
17480         break;
17481       case ISD::SETUGE:
17482         // Converting this to a max would handle both negative zeros and NaNs
17483         // incorrectly, but we can swap the operands to fix both.
17484         std::swap(LHS, RHS);
17485       case ISD::SETOGT:
17486       case ISD::SETGT:
17487       case ISD::SETGE:
17488         Opcode = X86ISD::FMAX;
17489         break;
17490       }
17491     // Check for x CC y ? y : x -- a min/max with reversed arms.
17492     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17493                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17494       switch (CC) {
17495       default: break;
17496       case ISD::SETOGE:
17497         // Converting this to a min would handle comparisons between positive
17498         // and negative zero incorrectly, and swapping the operands would
17499         // cause it to handle NaNs incorrectly.
17500         if (!DAG.getTarget().Options.UnsafeFPMath &&
17501             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17502           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17503             break;
17504           std::swap(LHS, RHS);
17505         }
17506         Opcode = X86ISD::FMIN;
17507         break;
17508       case ISD::SETUGT:
17509         // Converting this to a min would handle NaNs incorrectly.
17510         if (!DAG.getTarget().Options.UnsafeFPMath &&
17511             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17512           break;
17513         Opcode = X86ISD::FMIN;
17514         break;
17515       case ISD::SETUGE:
17516         // Converting this to a min would handle both negative zeros and NaNs
17517         // incorrectly, but we can swap the operands to fix both.
17518         std::swap(LHS, RHS);
17519       case ISD::SETOGT:
17520       case ISD::SETGT:
17521       case ISD::SETGE:
17522         Opcode = X86ISD::FMIN;
17523         break;
17524
17525       case ISD::SETULT:
17526         // Converting this to a max would handle NaNs incorrectly.
17527         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17528           break;
17529         Opcode = X86ISD::FMAX;
17530         break;
17531       case ISD::SETOLE:
17532         // Converting this to a max would handle comparisons between positive
17533         // and negative zero incorrectly, and swapping the operands would
17534         // cause it to handle NaNs incorrectly.
17535         if (!DAG.getTarget().Options.UnsafeFPMath &&
17536             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17537           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17538             break;
17539           std::swap(LHS, RHS);
17540         }
17541         Opcode = X86ISD::FMAX;
17542         break;
17543       case ISD::SETULE:
17544         // Converting this to a max would handle both negative zeros and NaNs
17545         // incorrectly, but we can swap the operands to fix both.
17546         std::swap(LHS, RHS);
17547       case ISD::SETOLT:
17548       case ISD::SETLT:
17549       case ISD::SETLE:
17550         Opcode = X86ISD::FMAX;
17551         break;
17552       }
17553     }
17554
17555     if (Opcode)
17556       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17557   }
17558
17559   EVT CondVT = Cond.getValueType();
17560   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17561       CondVT.getVectorElementType() == MVT::i1) {
17562     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17563     // lowering on AVX-512. In this case we convert it to
17564     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17565     // The same situation for all 128 and 256-bit vectors of i8 and i16
17566     EVT OpVT = LHS.getValueType();
17567     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17568         (OpVT.getVectorElementType() == MVT::i8 ||
17569          OpVT.getVectorElementType() == MVT::i16)) {
17570       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17571       DCI.AddToWorklist(Cond.getNode());
17572       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17573     }
17574   }
17575   // If this is a select between two integer constants, try to do some
17576   // optimizations.
17577   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17578     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17579       // Don't do this for crazy integer types.
17580       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17581         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17582         // so that TrueC (the true value) is larger than FalseC.
17583         bool NeedsCondInvert = false;
17584
17585         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17586             // Efficiently invertible.
17587             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17588              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17589               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17590           NeedsCondInvert = true;
17591           std::swap(TrueC, FalseC);
17592         }
17593
17594         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17595         if (FalseC->getAPIntValue() == 0 &&
17596             TrueC->getAPIntValue().isPowerOf2()) {
17597           if (NeedsCondInvert) // Invert the condition if needed.
17598             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17599                                DAG.getConstant(1, Cond.getValueType()));
17600
17601           // Zero extend the condition if needed.
17602           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17603
17604           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17605           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17606                              DAG.getConstant(ShAmt, MVT::i8));
17607         }
17608
17609         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17610         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17611           if (NeedsCondInvert) // Invert the condition if needed.
17612             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17613                                DAG.getConstant(1, Cond.getValueType()));
17614
17615           // Zero extend the condition if needed.
17616           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17617                              FalseC->getValueType(0), Cond);
17618           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17619                              SDValue(FalseC, 0));
17620         }
17621
17622         // Optimize cases that will turn into an LEA instruction.  This requires
17623         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17624         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17625           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17626           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17627
17628           bool isFastMultiplier = false;
17629           if (Diff < 10) {
17630             switch ((unsigned char)Diff) {
17631               default: break;
17632               case 1:  // result = add base, cond
17633               case 2:  // result = lea base(    , cond*2)
17634               case 3:  // result = lea base(cond, cond*2)
17635               case 4:  // result = lea base(    , cond*4)
17636               case 5:  // result = lea base(cond, cond*4)
17637               case 8:  // result = lea base(    , cond*8)
17638               case 9:  // result = lea base(cond, cond*8)
17639                 isFastMultiplier = true;
17640                 break;
17641             }
17642           }
17643
17644           if (isFastMultiplier) {
17645             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17646             if (NeedsCondInvert) // Invert the condition if needed.
17647               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17648                                  DAG.getConstant(1, Cond.getValueType()));
17649
17650             // Zero extend the condition if needed.
17651             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17652                                Cond);
17653             // Scale the condition by the difference.
17654             if (Diff != 1)
17655               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17656                                  DAG.getConstant(Diff, Cond.getValueType()));
17657
17658             // Add the base if non-zero.
17659             if (FalseC->getAPIntValue() != 0)
17660               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17661                                  SDValue(FalseC, 0));
17662             return Cond;
17663           }
17664         }
17665       }
17666   }
17667
17668   // Canonicalize max and min:
17669   // (x > y) ? x : y -> (x >= y) ? x : y
17670   // (x < y) ? x : y -> (x <= y) ? x : y
17671   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17672   // the need for an extra compare
17673   // against zero. e.g.
17674   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17675   // subl   %esi, %edi
17676   // testl  %edi, %edi
17677   // movl   $0, %eax
17678   // cmovgl %edi, %eax
17679   // =>
17680   // xorl   %eax, %eax
17681   // subl   %esi, $edi
17682   // cmovsl %eax, %edi
17683   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17684       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17685       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17686     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17687     switch (CC) {
17688     default: break;
17689     case ISD::SETLT:
17690     case ISD::SETGT: {
17691       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17692       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17693                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17694       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17695     }
17696     }
17697   }
17698
17699   // Early exit check
17700   if (!TLI.isTypeLegal(VT))
17701     return SDValue();
17702
17703   // Match VSELECTs into subs with unsigned saturation.
17704   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17705       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17706       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17707        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17708     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17709
17710     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17711     // left side invert the predicate to simplify logic below.
17712     SDValue Other;
17713     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17714       Other = RHS;
17715       CC = ISD::getSetCCInverse(CC, true);
17716     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17717       Other = LHS;
17718     }
17719
17720     if (Other.getNode() && Other->getNumOperands() == 2 &&
17721         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17722       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17723       SDValue CondRHS = Cond->getOperand(1);
17724
17725       // Look for a general sub with unsigned saturation first.
17726       // x >= y ? x-y : 0 --> subus x, y
17727       // x >  y ? x-y : 0 --> subus x, y
17728       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17729           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17730         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17731
17732       // If the RHS is a constant we have to reverse the const canonicalization.
17733       // x > C-1 ? x+-C : 0 --> subus x, C
17734       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17735           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17736         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17737         if (CondRHS.getConstantOperandVal(0) == -A-1)
17738           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17739                              DAG.getConstant(-A, VT));
17740       }
17741
17742       // Another special case: If C was a sign bit, the sub has been
17743       // canonicalized into a xor.
17744       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17745       //        it's safe to decanonicalize the xor?
17746       // x s< 0 ? x^C : 0 --> subus x, C
17747       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17748           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17749           isSplatVector(OpRHS.getNode())) {
17750         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17751         if (A.isSignBit())
17752           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17753       }
17754     }
17755   }
17756
17757   // Try to match a min/max vector operation.
17758   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17759     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17760     unsigned Opc = ret.first;
17761     bool NeedSplit = ret.second;
17762
17763     if (Opc && NeedSplit) {
17764       unsigned NumElems = VT.getVectorNumElements();
17765       // Extract the LHS vectors
17766       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17767       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17768
17769       // Extract the RHS vectors
17770       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17771       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17772
17773       // Create min/max for each subvector
17774       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17775       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17776
17777       // Merge the result
17778       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17779     } else if (Opc)
17780       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17781   }
17782
17783   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17784   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17785       // Check if SETCC has already been promoted
17786       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17787       // Check that condition value type matches vselect operand type
17788       CondVT == VT) { 
17789
17790     assert(Cond.getValueType().isVector() &&
17791            "vector select expects a vector selector!");
17792
17793     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17794     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17795
17796     if (!TValIsAllOnes && !FValIsAllZeros) {
17797       // Try invert the condition if true value is not all 1s and false value
17798       // is not all 0s.
17799       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17800       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17801
17802       if (TValIsAllZeros || FValIsAllOnes) {
17803         SDValue CC = Cond.getOperand(2);
17804         ISD::CondCode NewCC =
17805           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17806                                Cond.getOperand(0).getValueType().isInteger());
17807         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17808         std::swap(LHS, RHS);
17809         TValIsAllOnes = FValIsAllOnes;
17810         FValIsAllZeros = TValIsAllZeros;
17811       }
17812     }
17813
17814     if (TValIsAllOnes || FValIsAllZeros) {
17815       SDValue Ret;
17816
17817       if (TValIsAllOnes && FValIsAllZeros)
17818         Ret = Cond;
17819       else if (TValIsAllOnes)
17820         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17821                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17822       else if (FValIsAllZeros)
17823         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17824                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17825
17826       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17827     }
17828   }
17829
17830   // Try to fold this VSELECT into a MOVSS/MOVSD
17831   if (N->getOpcode() == ISD::VSELECT &&
17832       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17833     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17834         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17835       bool CanFold = false;
17836       unsigned NumElems = Cond.getNumOperands();
17837       SDValue A = LHS;
17838       SDValue B = RHS;
17839       
17840       if (isZero(Cond.getOperand(0))) {
17841         CanFold = true;
17842
17843         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17844         // fold (vselect <0,-1> -> (movsd A, B)
17845         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17846           CanFold = isAllOnes(Cond.getOperand(i));
17847       } else if (isAllOnes(Cond.getOperand(0))) {
17848         CanFold = true;
17849         std::swap(A, B);
17850
17851         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17852         // fold (vselect <-1,0> -> (movsd B, A)
17853         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17854           CanFold = isZero(Cond.getOperand(i));
17855       }
17856
17857       if (CanFold) {
17858         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17859           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17860         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17861       }
17862
17863       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17864         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17865         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17866         //                             (v2i64 (bitcast B)))))
17867         //
17868         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17869         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17870         //                             (v2f64 (bitcast B)))))
17871         //
17872         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17873         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17874         //                             (v2i64 (bitcast A)))))
17875         //
17876         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17877         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17878         //                             (v2f64 (bitcast A)))))
17879
17880         CanFold = (isZero(Cond.getOperand(0)) &&
17881                    isZero(Cond.getOperand(1)) &&
17882                    isAllOnes(Cond.getOperand(2)) &&
17883                    isAllOnes(Cond.getOperand(3)));
17884
17885         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17886             isAllOnes(Cond.getOperand(1)) &&
17887             isZero(Cond.getOperand(2)) &&
17888             isZero(Cond.getOperand(3))) {
17889           CanFold = true;
17890           std::swap(LHS, RHS);
17891         }
17892
17893         if (CanFold) {
17894           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17895           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17896           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17897           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17898                                                 NewB, DAG);
17899           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17900         }
17901       }
17902     }
17903   }
17904
17905   // If we know that this node is legal then we know that it is going to be
17906   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17907   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17908   // to simplify previous instructions.
17909   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17910       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17911     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17912
17913     // Don't optimize vector selects that map to mask-registers.
17914     if (BitWidth == 1)
17915       return SDValue();
17916
17917     // Check all uses of that condition operand to check whether it will be
17918     // consumed by non-BLEND instructions, which may depend on all bits are set
17919     // properly.
17920     for (SDNode::use_iterator I = Cond->use_begin(),
17921                               E = Cond->use_end(); I != E; ++I)
17922       if (I->getOpcode() != ISD::VSELECT)
17923         // TODO: Add other opcodes eventually lowered into BLEND.
17924         return SDValue();
17925
17926     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17927     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17928
17929     APInt KnownZero, KnownOne;
17930     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17931                                           DCI.isBeforeLegalizeOps());
17932     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17933         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17934       DCI.CommitTargetLoweringOpt(TLO);
17935   }
17936
17937   return SDValue();
17938 }
17939
17940 // Check whether a boolean test is testing a boolean value generated by
17941 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17942 // code.
17943 //
17944 // Simplify the following patterns:
17945 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17946 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17947 // to (Op EFLAGS Cond)
17948 //
17949 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17950 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17951 // to (Op EFLAGS !Cond)
17952 //
17953 // where Op could be BRCOND or CMOV.
17954 //
17955 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17956   // Quit if not CMP and SUB with its value result used.
17957   if (Cmp.getOpcode() != X86ISD::CMP &&
17958       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17959       return SDValue();
17960
17961   // Quit if not used as a boolean value.
17962   if (CC != X86::COND_E && CC != X86::COND_NE)
17963     return SDValue();
17964
17965   // Check CMP operands. One of them should be 0 or 1 and the other should be
17966   // an SetCC or extended from it.
17967   SDValue Op1 = Cmp.getOperand(0);
17968   SDValue Op2 = Cmp.getOperand(1);
17969
17970   SDValue SetCC;
17971   const ConstantSDNode* C = nullptr;
17972   bool needOppositeCond = (CC == X86::COND_E);
17973   bool checkAgainstTrue = false; // Is it a comparison against 1?
17974
17975   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17976     SetCC = Op2;
17977   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17978     SetCC = Op1;
17979   else // Quit if all operands are not constants.
17980     return SDValue();
17981
17982   if (C->getZExtValue() == 1) {
17983     needOppositeCond = !needOppositeCond;
17984     checkAgainstTrue = true;
17985   } else if (C->getZExtValue() != 0)
17986     // Quit if the constant is neither 0 or 1.
17987     return SDValue();
17988
17989   bool truncatedToBoolWithAnd = false;
17990   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17991   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17992          SetCC.getOpcode() == ISD::TRUNCATE ||
17993          SetCC.getOpcode() == ISD::AND) {
17994     if (SetCC.getOpcode() == ISD::AND) {
17995       int OpIdx = -1;
17996       ConstantSDNode *CS;
17997       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17998           CS->getZExtValue() == 1)
17999         OpIdx = 1;
18000       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18001           CS->getZExtValue() == 1)
18002         OpIdx = 0;
18003       if (OpIdx == -1)
18004         break;
18005       SetCC = SetCC.getOperand(OpIdx);
18006       truncatedToBoolWithAnd = true;
18007     } else
18008       SetCC = SetCC.getOperand(0);
18009   }
18010
18011   switch (SetCC.getOpcode()) {
18012   case X86ISD::SETCC_CARRY:
18013     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18014     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18015     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18016     // truncated to i1 using 'and'.
18017     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18018       break;
18019     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18020            "Invalid use of SETCC_CARRY!");
18021     // FALL THROUGH
18022   case X86ISD::SETCC:
18023     // Set the condition code or opposite one if necessary.
18024     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18025     if (needOppositeCond)
18026       CC = X86::GetOppositeBranchCondition(CC);
18027     return SetCC.getOperand(1);
18028   case X86ISD::CMOV: {
18029     // Check whether false/true value has canonical one, i.e. 0 or 1.
18030     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18031     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18032     // Quit if true value is not a constant.
18033     if (!TVal)
18034       return SDValue();
18035     // Quit if false value is not a constant.
18036     if (!FVal) {
18037       SDValue Op = SetCC.getOperand(0);
18038       // Skip 'zext' or 'trunc' node.
18039       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18040           Op.getOpcode() == ISD::TRUNCATE)
18041         Op = Op.getOperand(0);
18042       // A special case for rdrand/rdseed, where 0 is set if false cond is
18043       // found.
18044       if ((Op.getOpcode() != X86ISD::RDRAND &&
18045            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18046         return SDValue();
18047     }
18048     // Quit if false value is not the constant 0 or 1.
18049     bool FValIsFalse = true;
18050     if (FVal && FVal->getZExtValue() != 0) {
18051       if (FVal->getZExtValue() != 1)
18052         return SDValue();
18053       // If FVal is 1, opposite cond is needed.
18054       needOppositeCond = !needOppositeCond;
18055       FValIsFalse = false;
18056     }
18057     // Quit if TVal is not the constant opposite of FVal.
18058     if (FValIsFalse && TVal->getZExtValue() != 1)
18059       return SDValue();
18060     if (!FValIsFalse && TVal->getZExtValue() != 0)
18061       return SDValue();
18062     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18063     if (needOppositeCond)
18064       CC = X86::GetOppositeBranchCondition(CC);
18065     return SetCC.getOperand(3);
18066   }
18067   }
18068
18069   return SDValue();
18070 }
18071
18072 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18073 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18074                                   TargetLowering::DAGCombinerInfo &DCI,
18075                                   const X86Subtarget *Subtarget) {
18076   SDLoc DL(N);
18077
18078   // If the flag operand isn't dead, don't touch this CMOV.
18079   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18080     return SDValue();
18081
18082   SDValue FalseOp = N->getOperand(0);
18083   SDValue TrueOp = N->getOperand(1);
18084   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18085   SDValue Cond = N->getOperand(3);
18086
18087   if (CC == X86::COND_E || CC == X86::COND_NE) {
18088     switch (Cond.getOpcode()) {
18089     default: break;
18090     case X86ISD::BSR:
18091     case X86ISD::BSF:
18092       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18093       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18094         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18095     }
18096   }
18097
18098   SDValue Flags;
18099
18100   Flags = checkBoolTestSetCCCombine(Cond, CC);
18101   if (Flags.getNode() &&
18102       // Extra check as FCMOV only supports a subset of X86 cond.
18103       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18104     SDValue Ops[] = { FalseOp, TrueOp,
18105                       DAG.getConstant(CC, MVT::i8), Flags };
18106     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
18107                        Ops, array_lengthof(Ops));
18108   }
18109
18110   // If this is a select between two integer constants, try to do some
18111   // optimizations.  Note that the operands are ordered the opposite of SELECT
18112   // operands.
18113   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18114     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18115       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18116       // larger than FalseC (the false value).
18117       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18118         CC = X86::GetOppositeBranchCondition(CC);
18119         std::swap(TrueC, FalseC);
18120         std::swap(TrueOp, FalseOp);
18121       }
18122
18123       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18124       // This is efficient for any integer data type (including i8/i16) and
18125       // shift amount.
18126       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18127         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18128                            DAG.getConstant(CC, MVT::i8), Cond);
18129
18130         // Zero extend the condition if needed.
18131         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18132
18133         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18134         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18135                            DAG.getConstant(ShAmt, MVT::i8));
18136         if (N->getNumValues() == 2)  // Dead flag value?
18137           return DCI.CombineTo(N, Cond, SDValue());
18138         return Cond;
18139       }
18140
18141       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18142       // for any integer data type, including i8/i16.
18143       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18144         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18145                            DAG.getConstant(CC, MVT::i8), Cond);
18146
18147         // Zero extend the condition if needed.
18148         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18149                            FalseC->getValueType(0), Cond);
18150         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18151                            SDValue(FalseC, 0));
18152
18153         if (N->getNumValues() == 2)  // Dead flag value?
18154           return DCI.CombineTo(N, Cond, SDValue());
18155         return Cond;
18156       }
18157
18158       // Optimize cases that will turn into an LEA instruction.  This requires
18159       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18160       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18161         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18162         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18163
18164         bool isFastMultiplier = false;
18165         if (Diff < 10) {
18166           switch ((unsigned char)Diff) {
18167           default: break;
18168           case 1:  // result = add base, cond
18169           case 2:  // result = lea base(    , cond*2)
18170           case 3:  // result = lea base(cond, cond*2)
18171           case 4:  // result = lea base(    , cond*4)
18172           case 5:  // result = lea base(cond, cond*4)
18173           case 8:  // result = lea base(    , cond*8)
18174           case 9:  // result = lea base(cond, cond*8)
18175             isFastMultiplier = true;
18176             break;
18177           }
18178         }
18179
18180         if (isFastMultiplier) {
18181           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18182           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18183                              DAG.getConstant(CC, MVT::i8), Cond);
18184           // Zero extend the condition if needed.
18185           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18186                              Cond);
18187           // Scale the condition by the difference.
18188           if (Diff != 1)
18189             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18190                                DAG.getConstant(Diff, Cond.getValueType()));
18191
18192           // Add the base if non-zero.
18193           if (FalseC->getAPIntValue() != 0)
18194             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18195                                SDValue(FalseC, 0));
18196           if (N->getNumValues() == 2)  // Dead flag value?
18197             return DCI.CombineTo(N, Cond, SDValue());
18198           return Cond;
18199         }
18200       }
18201     }
18202   }
18203
18204   // Handle these cases:
18205   //   (select (x != c), e, c) -> select (x != c), e, x),
18206   //   (select (x == c), c, e) -> select (x == c), x, e)
18207   // where the c is an integer constant, and the "select" is the combination
18208   // of CMOV and CMP.
18209   //
18210   // The rationale for this change is that the conditional-move from a constant
18211   // needs two instructions, however, conditional-move from a register needs
18212   // only one instruction.
18213   //
18214   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18215   //  some instruction-combining opportunities. This opt needs to be
18216   //  postponed as late as possible.
18217   //
18218   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18219     // the DCI.xxxx conditions are provided to postpone the optimization as
18220     // late as possible.
18221
18222     ConstantSDNode *CmpAgainst = nullptr;
18223     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18224         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18225         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18226
18227       if (CC == X86::COND_NE &&
18228           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18229         CC = X86::GetOppositeBranchCondition(CC);
18230         std::swap(TrueOp, FalseOp);
18231       }
18232
18233       if (CC == X86::COND_E &&
18234           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18235         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18236                           DAG.getConstant(CC, MVT::i8), Cond };
18237         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18238                            array_lengthof(Ops));
18239       }
18240     }
18241   }
18242
18243   return SDValue();
18244 }
18245
18246 /// PerformMulCombine - Optimize a single multiply with constant into two
18247 /// in order to implement it with two cheaper instructions, e.g.
18248 /// LEA + SHL, LEA + LEA.
18249 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18250                                  TargetLowering::DAGCombinerInfo &DCI) {
18251   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18252     return SDValue();
18253
18254   EVT VT = N->getValueType(0);
18255   if (VT != MVT::i64)
18256     return SDValue();
18257
18258   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18259   if (!C)
18260     return SDValue();
18261   uint64_t MulAmt = C->getZExtValue();
18262   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18263     return SDValue();
18264
18265   uint64_t MulAmt1 = 0;
18266   uint64_t MulAmt2 = 0;
18267   if ((MulAmt % 9) == 0) {
18268     MulAmt1 = 9;
18269     MulAmt2 = MulAmt / 9;
18270   } else if ((MulAmt % 5) == 0) {
18271     MulAmt1 = 5;
18272     MulAmt2 = MulAmt / 5;
18273   } else if ((MulAmt % 3) == 0) {
18274     MulAmt1 = 3;
18275     MulAmt2 = MulAmt / 3;
18276   }
18277   if (MulAmt2 &&
18278       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18279     SDLoc DL(N);
18280
18281     if (isPowerOf2_64(MulAmt2) &&
18282         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18283       // If second multiplifer is pow2, issue it first. We want the multiply by
18284       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18285       // is an add.
18286       std::swap(MulAmt1, MulAmt2);
18287
18288     SDValue NewMul;
18289     if (isPowerOf2_64(MulAmt1))
18290       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18291                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18292     else
18293       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18294                            DAG.getConstant(MulAmt1, VT));
18295
18296     if (isPowerOf2_64(MulAmt2))
18297       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18298                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18299     else
18300       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18301                            DAG.getConstant(MulAmt2, VT));
18302
18303     // Do not add new nodes to DAG combiner worklist.
18304     DCI.CombineTo(N, NewMul, false);
18305   }
18306   return SDValue();
18307 }
18308
18309 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18310   SDValue N0 = N->getOperand(0);
18311   SDValue N1 = N->getOperand(1);
18312   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18313   EVT VT = N0.getValueType();
18314
18315   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18316   // since the result of setcc_c is all zero's or all ones.
18317   if (VT.isInteger() && !VT.isVector() &&
18318       N1C && N0.getOpcode() == ISD::AND &&
18319       N0.getOperand(1).getOpcode() == ISD::Constant) {
18320     SDValue N00 = N0.getOperand(0);
18321     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18322         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18323           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18324          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18325       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18326       APInt ShAmt = N1C->getAPIntValue();
18327       Mask = Mask.shl(ShAmt);
18328       if (Mask != 0)
18329         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18330                            N00, DAG.getConstant(Mask, VT));
18331     }
18332   }
18333
18334   // Hardware support for vector shifts is sparse which makes us scalarize the
18335   // vector operations in many cases. Also, on sandybridge ADD is faster than
18336   // shl.
18337   // (shl V, 1) -> add V,V
18338   if (isSplatVector(N1.getNode())) {
18339     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18340     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18341     // We shift all of the values by one. In many cases we do not have
18342     // hardware support for this operation. This is better expressed as an ADD
18343     // of two values.
18344     if (N1C && (1 == N1C->getZExtValue())) {
18345       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18346     }
18347   }
18348
18349   return SDValue();
18350 }
18351
18352 /// \brief Returns a vector of 0s if the node in input is a vector logical
18353 /// shift by a constant amount which is known to be bigger than or equal
18354 /// to the vector element size in bits.
18355 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18356                                       const X86Subtarget *Subtarget) {
18357   EVT VT = N->getValueType(0);
18358
18359   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18360       (!Subtarget->hasInt256() ||
18361        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18362     return SDValue();
18363
18364   SDValue Amt = N->getOperand(1);
18365   SDLoc DL(N);
18366   if (isSplatVector(Amt.getNode())) {
18367     SDValue SclrAmt = Amt->getOperand(0);
18368     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18369       APInt ShiftAmt = C->getAPIntValue();
18370       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18371
18372       // SSE2/AVX2 logical shifts always return a vector of 0s
18373       // if the shift amount is bigger than or equal to
18374       // the element size. The constant shift amount will be
18375       // encoded as a 8-bit immediate.
18376       if (ShiftAmt.trunc(8).uge(MaxAmount))
18377         return getZeroVector(VT, Subtarget, DAG, DL);
18378     }
18379   }
18380
18381   return SDValue();
18382 }
18383
18384 /// PerformShiftCombine - Combine shifts.
18385 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18386                                    TargetLowering::DAGCombinerInfo &DCI,
18387                                    const X86Subtarget *Subtarget) {
18388   if (N->getOpcode() == ISD::SHL) {
18389     SDValue V = PerformSHLCombine(N, DAG);
18390     if (V.getNode()) return V;
18391   }
18392
18393   if (N->getOpcode() != ISD::SRA) {
18394     // Try to fold this logical shift into a zero vector.
18395     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18396     if (V.getNode()) return V;
18397   }
18398
18399   return SDValue();
18400 }
18401
18402 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18403 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18404 // and friends.  Likewise for OR -> CMPNEQSS.
18405 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18406                             TargetLowering::DAGCombinerInfo &DCI,
18407                             const X86Subtarget *Subtarget) {
18408   unsigned opcode;
18409
18410   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18411   // we're requiring SSE2 for both.
18412   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18413     SDValue N0 = N->getOperand(0);
18414     SDValue N1 = N->getOperand(1);
18415     SDValue CMP0 = N0->getOperand(1);
18416     SDValue CMP1 = N1->getOperand(1);
18417     SDLoc DL(N);
18418
18419     // The SETCCs should both refer to the same CMP.
18420     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18421       return SDValue();
18422
18423     SDValue CMP00 = CMP0->getOperand(0);
18424     SDValue CMP01 = CMP0->getOperand(1);
18425     EVT     VT    = CMP00.getValueType();
18426
18427     if (VT == MVT::f32 || VT == MVT::f64) {
18428       bool ExpectingFlags = false;
18429       // Check for any users that want flags:
18430       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18431            !ExpectingFlags && UI != UE; ++UI)
18432         switch (UI->getOpcode()) {
18433         default:
18434         case ISD::BR_CC:
18435         case ISD::BRCOND:
18436         case ISD::SELECT:
18437           ExpectingFlags = true;
18438           break;
18439         case ISD::CopyToReg:
18440         case ISD::SIGN_EXTEND:
18441         case ISD::ZERO_EXTEND:
18442         case ISD::ANY_EXTEND:
18443           break;
18444         }
18445
18446       if (!ExpectingFlags) {
18447         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18448         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18449
18450         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18451           X86::CondCode tmp = cc0;
18452           cc0 = cc1;
18453           cc1 = tmp;
18454         }
18455
18456         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18457             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18458           // FIXME: need symbolic constants for these magic numbers.
18459           // See X86ATTInstPrinter.cpp:printSSECC().
18460           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18461           if (Subtarget->hasAVX512()) {
18462             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18463                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18464             if (N->getValueType(0) != MVT::i1)
18465               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18466                                  FSetCC);
18467             return FSetCC;
18468           }
18469           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18470                                               CMP00.getValueType(), CMP00, CMP01,
18471                                               DAG.getConstant(x86cc, MVT::i8));
18472
18473           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18474           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18475
18476           if (is64BitFP && !Subtarget->is64Bit()) {
18477             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18478             // 64-bit integer, since that's not a legal type. Since
18479             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18480             // bits, but can do this little dance to extract the lowest 32 bits
18481             // and work with those going forward.
18482             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18483                                            OnesOrZeroesF);
18484             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18485                                            Vector64);
18486             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18487                                         Vector32, DAG.getIntPtrConstant(0));
18488             IntVT = MVT::i32;
18489           }
18490
18491           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18492           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18493                                       DAG.getConstant(1, IntVT));
18494           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18495           return OneBitOfTruth;
18496         }
18497       }
18498     }
18499   }
18500   return SDValue();
18501 }
18502
18503 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18504 /// so it can be folded inside ANDNP.
18505 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18506   EVT VT = N->getValueType(0);
18507
18508   // Match direct AllOnes for 128 and 256-bit vectors
18509   if (ISD::isBuildVectorAllOnes(N))
18510     return true;
18511
18512   // Look through a bit convert.
18513   if (N->getOpcode() == ISD::BITCAST)
18514     N = N->getOperand(0).getNode();
18515
18516   // Sometimes the operand may come from a insert_subvector building a 256-bit
18517   // allones vector
18518   if (VT.is256BitVector() &&
18519       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18520     SDValue V1 = N->getOperand(0);
18521     SDValue V2 = N->getOperand(1);
18522
18523     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18524         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18525         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18526         ISD::isBuildVectorAllOnes(V2.getNode()))
18527       return true;
18528   }
18529
18530   return false;
18531 }
18532
18533 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18534 // register. In most cases we actually compare or select YMM-sized registers
18535 // and mixing the two types creates horrible code. This method optimizes
18536 // some of the transition sequences.
18537 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18538                                  TargetLowering::DAGCombinerInfo &DCI,
18539                                  const X86Subtarget *Subtarget) {
18540   EVT VT = N->getValueType(0);
18541   if (!VT.is256BitVector())
18542     return SDValue();
18543
18544   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18545           N->getOpcode() == ISD::ZERO_EXTEND ||
18546           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18547
18548   SDValue Narrow = N->getOperand(0);
18549   EVT NarrowVT = Narrow->getValueType(0);
18550   if (!NarrowVT.is128BitVector())
18551     return SDValue();
18552
18553   if (Narrow->getOpcode() != ISD::XOR &&
18554       Narrow->getOpcode() != ISD::AND &&
18555       Narrow->getOpcode() != ISD::OR)
18556     return SDValue();
18557
18558   SDValue N0  = Narrow->getOperand(0);
18559   SDValue N1  = Narrow->getOperand(1);
18560   SDLoc DL(Narrow);
18561
18562   // The Left side has to be a trunc.
18563   if (N0.getOpcode() != ISD::TRUNCATE)
18564     return SDValue();
18565
18566   // The type of the truncated inputs.
18567   EVT WideVT = N0->getOperand(0)->getValueType(0);
18568   if (WideVT != VT)
18569     return SDValue();
18570
18571   // The right side has to be a 'trunc' or a constant vector.
18572   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18573   bool RHSConst = (isSplatVector(N1.getNode()) &&
18574                    isa<ConstantSDNode>(N1->getOperand(0)));
18575   if (!RHSTrunc && !RHSConst)
18576     return SDValue();
18577
18578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18579
18580   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18581     return SDValue();
18582
18583   // Set N0 and N1 to hold the inputs to the new wide operation.
18584   N0 = N0->getOperand(0);
18585   if (RHSConst) {
18586     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18587                      N1->getOperand(0));
18588     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18589     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18590   } else if (RHSTrunc) {
18591     N1 = N1->getOperand(0);
18592   }
18593
18594   // Generate the wide operation.
18595   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18596   unsigned Opcode = N->getOpcode();
18597   switch (Opcode) {
18598   case ISD::ANY_EXTEND:
18599     return Op;
18600   case ISD::ZERO_EXTEND: {
18601     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18602     APInt Mask = APInt::getAllOnesValue(InBits);
18603     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18604     return DAG.getNode(ISD::AND, DL, VT,
18605                        Op, DAG.getConstant(Mask, VT));
18606   }
18607   case ISD::SIGN_EXTEND:
18608     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18609                        Op, DAG.getValueType(NarrowVT));
18610   default:
18611     llvm_unreachable("Unexpected opcode");
18612   }
18613 }
18614
18615 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18616                                  TargetLowering::DAGCombinerInfo &DCI,
18617                                  const X86Subtarget *Subtarget) {
18618   EVT VT = N->getValueType(0);
18619   if (DCI.isBeforeLegalizeOps())
18620     return SDValue();
18621
18622   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18623   if (R.getNode())
18624     return R;
18625
18626   // Create BEXTR instructions
18627   // BEXTR is ((X >> imm) & (2**size-1))
18628   if (VT == MVT::i32 || VT == MVT::i64) {
18629     SDValue N0 = N->getOperand(0);
18630     SDValue N1 = N->getOperand(1);
18631     SDLoc DL(N);
18632
18633     // Check for BEXTR.
18634     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18635         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18636       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18637       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18638       if (MaskNode && ShiftNode) {
18639         uint64_t Mask = MaskNode->getZExtValue();
18640         uint64_t Shift = ShiftNode->getZExtValue();
18641         if (isMask_64(Mask)) {
18642           uint64_t MaskSize = CountPopulation_64(Mask);
18643           if (Shift + MaskSize <= VT.getSizeInBits())
18644             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18645                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18646         }
18647       }
18648     } // BEXTR
18649
18650     return SDValue();
18651   }
18652
18653   // Want to form ANDNP nodes:
18654   // 1) In the hopes of then easily combining them with OR and AND nodes
18655   //    to form PBLEND/PSIGN.
18656   // 2) To match ANDN packed intrinsics
18657   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18658     return SDValue();
18659
18660   SDValue N0 = N->getOperand(0);
18661   SDValue N1 = N->getOperand(1);
18662   SDLoc DL(N);
18663
18664   // Check LHS for vnot
18665   if (N0.getOpcode() == ISD::XOR &&
18666       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18667       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18668     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18669
18670   // Check RHS for vnot
18671   if (N1.getOpcode() == ISD::XOR &&
18672       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18673       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18674     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18675
18676   return SDValue();
18677 }
18678
18679 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18680                                 TargetLowering::DAGCombinerInfo &DCI,
18681                                 const X86Subtarget *Subtarget) {
18682   if (DCI.isBeforeLegalizeOps())
18683     return SDValue();
18684
18685   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18686   if (R.getNode())
18687     return R;
18688
18689   SDValue N0 = N->getOperand(0);
18690   SDValue N1 = N->getOperand(1);
18691   EVT VT = N->getValueType(0);
18692
18693   // look for psign/blend
18694   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18695     if (!Subtarget->hasSSSE3() ||
18696         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18697       return SDValue();
18698
18699     // Canonicalize pandn to RHS
18700     if (N0.getOpcode() == X86ISD::ANDNP)
18701       std::swap(N0, N1);
18702     // or (and (m, y), (pandn m, x))
18703     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18704       SDValue Mask = N1.getOperand(0);
18705       SDValue X    = N1.getOperand(1);
18706       SDValue Y;
18707       if (N0.getOperand(0) == Mask)
18708         Y = N0.getOperand(1);
18709       if (N0.getOperand(1) == Mask)
18710         Y = N0.getOperand(0);
18711
18712       // Check to see if the mask appeared in both the AND and ANDNP and
18713       if (!Y.getNode())
18714         return SDValue();
18715
18716       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18717       // Look through mask bitcast.
18718       if (Mask.getOpcode() == ISD::BITCAST)
18719         Mask = Mask.getOperand(0);
18720       if (X.getOpcode() == ISD::BITCAST)
18721         X = X.getOperand(0);
18722       if (Y.getOpcode() == ISD::BITCAST)
18723         Y = Y.getOperand(0);
18724
18725       EVT MaskVT = Mask.getValueType();
18726
18727       // Validate that the Mask operand is a vector sra node.
18728       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18729       // there is no psrai.b
18730       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18731       unsigned SraAmt = ~0;
18732       if (Mask.getOpcode() == ISD::SRA) {
18733         SDValue Amt = Mask.getOperand(1);
18734         if (isSplatVector(Amt.getNode())) {
18735           SDValue SclrAmt = Amt->getOperand(0);
18736           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18737             SraAmt = C->getZExtValue();
18738         }
18739       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18740         SDValue SraC = Mask.getOperand(1);
18741         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18742       }
18743       if ((SraAmt + 1) != EltBits)
18744         return SDValue();
18745
18746       SDLoc DL(N);
18747
18748       // Now we know we at least have a plendvb with the mask val.  See if
18749       // we can form a psignb/w/d.
18750       // psign = x.type == y.type == mask.type && y = sub(0, x);
18751       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18752           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18753           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18754         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18755                "Unsupported VT for PSIGN");
18756         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18757         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18758       }
18759       // PBLENDVB only available on SSE 4.1
18760       if (!Subtarget->hasSSE41())
18761         return SDValue();
18762
18763       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18764
18765       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18766       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18767       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18768       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18769       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18770     }
18771   }
18772
18773   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18774     return SDValue();
18775
18776   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18777   MachineFunction &MF = DAG.getMachineFunction();
18778   bool OptForSize = MF.getFunction()->getAttributes().
18779     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18780
18781   // SHLD/SHRD instructions have lower register pressure, but on some
18782   // platforms they have higher latency than the equivalent
18783   // series of shifts/or that would otherwise be generated.
18784   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18785   // have higher latencies and we are not optimizing for size.
18786   if (!OptForSize && Subtarget->isSHLDSlow())
18787     return SDValue();
18788
18789   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18790     std::swap(N0, N1);
18791   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18792     return SDValue();
18793   if (!N0.hasOneUse() || !N1.hasOneUse())
18794     return SDValue();
18795
18796   SDValue ShAmt0 = N0.getOperand(1);
18797   if (ShAmt0.getValueType() != MVT::i8)
18798     return SDValue();
18799   SDValue ShAmt1 = N1.getOperand(1);
18800   if (ShAmt1.getValueType() != MVT::i8)
18801     return SDValue();
18802   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18803     ShAmt0 = ShAmt0.getOperand(0);
18804   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18805     ShAmt1 = ShAmt1.getOperand(0);
18806
18807   SDLoc DL(N);
18808   unsigned Opc = X86ISD::SHLD;
18809   SDValue Op0 = N0.getOperand(0);
18810   SDValue Op1 = N1.getOperand(0);
18811   if (ShAmt0.getOpcode() == ISD::SUB) {
18812     Opc = X86ISD::SHRD;
18813     std::swap(Op0, Op1);
18814     std::swap(ShAmt0, ShAmt1);
18815   }
18816
18817   unsigned Bits = VT.getSizeInBits();
18818   if (ShAmt1.getOpcode() == ISD::SUB) {
18819     SDValue Sum = ShAmt1.getOperand(0);
18820     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18821       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18822       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18823         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18824       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18825         return DAG.getNode(Opc, DL, VT,
18826                            Op0, Op1,
18827                            DAG.getNode(ISD::TRUNCATE, DL,
18828                                        MVT::i8, ShAmt0));
18829     }
18830   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18831     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18832     if (ShAmt0C &&
18833         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18834       return DAG.getNode(Opc, DL, VT,
18835                          N0.getOperand(0), N1.getOperand(0),
18836                          DAG.getNode(ISD::TRUNCATE, DL,
18837                                        MVT::i8, ShAmt0));
18838   }
18839
18840   return SDValue();
18841 }
18842
18843 // Generate NEG and CMOV for integer abs.
18844 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18845   EVT VT = N->getValueType(0);
18846
18847   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18848   // 8-bit integer abs to NEG and CMOV.
18849   if (VT.isInteger() && VT.getSizeInBits() == 8)
18850     return SDValue();
18851
18852   SDValue N0 = N->getOperand(0);
18853   SDValue N1 = N->getOperand(1);
18854   SDLoc DL(N);
18855
18856   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18857   // and change it to SUB and CMOV.
18858   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18859       N0.getOpcode() == ISD::ADD &&
18860       N0.getOperand(1) == N1 &&
18861       N1.getOpcode() == ISD::SRA &&
18862       N1.getOperand(0) == N0.getOperand(0))
18863     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18864       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18865         // Generate SUB & CMOV.
18866         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18867                                   DAG.getConstant(0, VT), N0.getOperand(0));
18868
18869         SDValue Ops[] = { N0.getOperand(0), Neg,
18870                           DAG.getConstant(X86::COND_GE, MVT::i8),
18871                           SDValue(Neg.getNode(), 1) };
18872         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18873                            Ops, array_lengthof(Ops));
18874       }
18875   return SDValue();
18876 }
18877
18878 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18879 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18880                                  TargetLowering::DAGCombinerInfo &DCI,
18881                                  const X86Subtarget *Subtarget) {
18882   if (DCI.isBeforeLegalizeOps())
18883     return SDValue();
18884
18885   if (Subtarget->hasCMov()) {
18886     SDValue RV = performIntegerAbsCombine(N, DAG);
18887     if (RV.getNode())
18888       return RV;
18889   }
18890
18891   return SDValue();
18892 }
18893
18894 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18895 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18896                                   TargetLowering::DAGCombinerInfo &DCI,
18897                                   const X86Subtarget *Subtarget) {
18898   LoadSDNode *Ld = cast<LoadSDNode>(N);
18899   EVT RegVT = Ld->getValueType(0);
18900   EVT MemVT = Ld->getMemoryVT();
18901   SDLoc dl(Ld);
18902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18903   unsigned RegSz = RegVT.getSizeInBits();
18904
18905   // On Sandybridge unaligned 256bit loads are inefficient.
18906   ISD::LoadExtType Ext = Ld->getExtensionType();
18907   unsigned Alignment = Ld->getAlignment();
18908   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18909   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18910       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18911     unsigned NumElems = RegVT.getVectorNumElements();
18912     if (NumElems < 2)
18913       return SDValue();
18914
18915     SDValue Ptr = Ld->getBasePtr();
18916     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18917
18918     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18919                                   NumElems/2);
18920     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18921                                 Ld->getPointerInfo(), Ld->isVolatile(),
18922                                 Ld->isNonTemporal(), Ld->isInvariant(),
18923                                 Alignment);
18924     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18925     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18926                                 Ld->getPointerInfo(), Ld->isVolatile(),
18927                                 Ld->isNonTemporal(), Ld->isInvariant(),
18928                                 std::min(16U, Alignment));
18929     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18930                              Load1.getValue(1),
18931                              Load2.getValue(1));
18932
18933     SDValue NewVec = DAG.getUNDEF(RegVT);
18934     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18935     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18936     return DCI.CombineTo(N, NewVec, TF, true);
18937   }
18938
18939   // If this is a vector EXT Load then attempt to optimize it using a
18940   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18941   // expansion is still better than scalar code.
18942   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18943   // emit a shuffle and a arithmetic shift.
18944   // TODO: It is possible to support ZExt by zeroing the undef values
18945   // during the shuffle phase or after the shuffle.
18946   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18947       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18948     assert(MemVT != RegVT && "Cannot extend to the same type");
18949     assert(MemVT.isVector() && "Must load a vector from memory");
18950
18951     unsigned NumElems = RegVT.getVectorNumElements();
18952     unsigned MemSz = MemVT.getSizeInBits();
18953     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18954
18955     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18956       return SDValue();
18957
18958     // All sizes must be a power of two.
18959     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18960       return SDValue();
18961
18962     // Attempt to load the original value using scalar loads.
18963     // Find the largest scalar type that divides the total loaded size.
18964     MVT SclrLoadTy = MVT::i8;
18965     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18966          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18967       MVT Tp = (MVT::SimpleValueType)tp;
18968       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18969         SclrLoadTy = Tp;
18970       }
18971     }
18972
18973     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18974     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18975         (64 <= MemSz))
18976       SclrLoadTy = MVT::f64;
18977
18978     // Calculate the number of scalar loads that we need to perform
18979     // in order to load our vector from memory.
18980     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18981     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18982       return SDValue();
18983
18984     unsigned loadRegZize = RegSz;
18985     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18986       loadRegZize /= 2;
18987
18988     // Represent our vector as a sequence of elements which are the
18989     // largest scalar that we can load.
18990     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18991       loadRegZize/SclrLoadTy.getSizeInBits());
18992
18993     // Represent the data using the same element type that is stored in
18994     // memory. In practice, we ''widen'' MemVT.
18995     EVT WideVecVT =
18996           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18997                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18998
18999     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19000       "Invalid vector type");
19001
19002     // We can't shuffle using an illegal type.
19003     if (!TLI.isTypeLegal(WideVecVT))
19004       return SDValue();
19005
19006     SmallVector<SDValue, 8> Chains;
19007     SDValue Ptr = Ld->getBasePtr();
19008     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19009                                         TLI.getPointerTy());
19010     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19011
19012     for (unsigned i = 0; i < NumLoads; ++i) {
19013       // Perform a single load.
19014       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19015                                        Ptr, Ld->getPointerInfo(),
19016                                        Ld->isVolatile(), Ld->isNonTemporal(),
19017                                        Ld->isInvariant(), Ld->getAlignment());
19018       Chains.push_back(ScalarLoad.getValue(1));
19019       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19020       // another round of DAGCombining.
19021       if (i == 0)
19022         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19023       else
19024         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19025                           ScalarLoad, DAG.getIntPtrConstant(i));
19026
19027       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19028     }
19029
19030     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19031                                Chains.size());
19032
19033     // Bitcast the loaded value to a vector of the original element type, in
19034     // the size of the target vector type.
19035     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19036     unsigned SizeRatio = RegSz/MemSz;
19037
19038     if (Ext == ISD::SEXTLOAD) {
19039       // If we have SSE4.1 we can directly emit a VSEXT node.
19040       if (Subtarget->hasSSE41()) {
19041         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19042         return DCI.CombineTo(N, Sext, TF, true);
19043       }
19044
19045       // Otherwise we'll shuffle the small elements in the high bits of the
19046       // larger type and perform an arithmetic shift. If the shift is not legal
19047       // it's better to scalarize.
19048       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19049         return SDValue();
19050
19051       // Redistribute the loaded elements into the different locations.
19052       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19053       for (unsigned i = 0; i != NumElems; ++i)
19054         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19055
19056       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19057                                            DAG.getUNDEF(WideVecVT),
19058                                            &ShuffleVec[0]);
19059
19060       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19061
19062       // Build the arithmetic shift.
19063       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19064                      MemVT.getVectorElementType().getSizeInBits();
19065       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19066                           DAG.getConstant(Amt, RegVT));
19067
19068       return DCI.CombineTo(N, Shuff, TF, true);
19069     }
19070
19071     // Redistribute the loaded elements into the different locations.
19072     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19073     for (unsigned i = 0; i != NumElems; ++i)
19074       ShuffleVec[i*SizeRatio] = i;
19075
19076     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19077                                          DAG.getUNDEF(WideVecVT),
19078                                          &ShuffleVec[0]);
19079
19080     // Bitcast to the requested type.
19081     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19082     // Replace the original load with the new sequence
19083     // and return the new chain.
19084     return DCI.CombineTo(N, Shuff, TF, true);
19085   }
19086
19087   return SDValue();
19088 }
19089
19090 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19091 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19092                                    const X86Subtarget *Subtarget) {
19093   StoreSDNode *St = cast<StoreSDNode>(N);
19094   EVT VT = St->getValue().getValueType();
19095   EVT StVT = St->getMemoryVT();
19096   SDLoc dl(St);
19097   SDValue StoredVal = St->getOperand(1);
19098   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19099
19100   // If we are saving a concatenation of two XMM registers, perform two stores.
19101   // On Sandy Bridge, 256-bit memory operations are executed by two
19102   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19103   // memory  operation.
19104   unsigned Alignment = St->getAlignment();
19105   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19106   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19107       StVT == VT && !IsAligned) {
19108     unsigned NumElems = VT.getVectorNumElements();
19109     if (NumElems < 2)
19110       return SDValue();
19111
19112     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19113     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19114
19115     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19116     SDValue Ptr0 = St->getBasePtr();
19117     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19118
19119     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19120                                 St->getPointerInfo(), St->isVolatile(),
19121                                 St->isNonTemporal(), Alignment);
19122     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19123                                 St->getPointerInfo(), St->isVolatile(),
19124                                 St->isNonTemporal(),
19125                                 std::min(16U, Alignment));
19126     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19127   }
19128
19129   // Optimize trunc store (of multiple scalars) to shuffle and store.
19130   // First, pack all of the elements in one place. Next, store to memory
19131   // in fewer chunks.
19132   if (St->isTruncatingStore() && VT.isVector()) {
19133     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19134     unsigned NumElems = VT.getVectorNumElements();
19135     assert(StVT != VT && "Cannot truncate to the same type");
19136     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19137     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19138
19139     // From, To sizes and ElemCount must be pow of two
19140     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19141     // We are going to use the original vector elt for storing.
19142     // Accumulated smaller vector elements must be a multiple of the store size.
19143     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19144
19145     unsigned SizeRatio  = FromSz / ToSz;
19146
19147     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19148
19149     // Create a type on which we perform the shuffle
19150     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19151             StVT.getScalarType(), NumElems*SizeRatio);
19152
19153     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19154
19155     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19156     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19157     for (unsigned i = 0; i != NumElems; ++i)
19158       ShuffleVec[i] = i * SizeRatio;
19159
19160     // Can't shuffle using an illegal type.
19161     if (!TLI.isTypeLegal(WideVecVT))
19162       return SDValue();
19163
19164     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19165                                          DAG.getUNDEF(WideVecVT),
19166                                          &ShuffleVec[0]);
19167     // At this point all of the data is stored at the bottom of the
19168     // register. We now need to save it to mem.
19169
19170     // Find the largest store unit
19171     MVT StoreType = MVT::i8;
19172     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19173          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19174       MVT Tp = (MVT::SimpleValueType)tp;
19175       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19176         StoreType = Tp;
19177     }
19178
19179     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19180     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19181         (64 <= NumElems * ToSz))
19182       StoreType = MVT::f64;
19183
19184     // Bitcast the original vector into a vector of store-size units
19185     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19186             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19187     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19188     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19189     SmallVector<SDValue, 8> Chains;
19190     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19191                                         TLI.getPointerTy());
19192     SDValue Ptr = St->getBasePtr();
19193
19194     // Perform one or more big stores into memory.
19195     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19196       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19197                                    StoreType, ShuffWide,
19198                                    DAG.getIntPtrConstant(i));
19199       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19200                                 St->getPointerInfo(), St->isVolatile(),
19201                                 St->isNonTemporal(), St->getAlignment());
19202       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19203       Chains.push_back(Ch);
19204     }
19205
19206     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19207                                Chains.size());
19208   }
19209
19210   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19211   // the FP state in cases where an emms may be missing.
19212   // A preferable solution to the general problem is to figure out the right
19213   // places to insert EMMS.  This qualifies as a quick hack.
19214
19215   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19216   if (VT.getSizeInBits() != 64)
19217     return SDValue();
19218
19219   const Function *F = DAG.getMachineFunction().getFunction();
19220   bool NoImplicitFloatOps = F->getAttributes().
19221     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19222   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19223                      && Subtarget->hasSSE2();
19224   if ((VT.isVector() ||
19225        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19226       isa<LoadSDNode>(St->getValue()) &&
19227       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19228       St->getChain().hasOneUse() && !St->isVolatile()) {
19229     SDNode* LdVal = St->getValue().getNode();
19230     LoadSDNode *Ld = nullptr;
19231     int TokenFactorIndex = -1;
19232     SmallVector<SDValue, 8> Ops;
19233     SDNode* ChainVal = St->getChain().getNode();
19234     // Must be a store of a load.  We currently handle two cases:  the load
19235     // is a direct child, and it's under an intervening TokenFactor.  It is
19236     // possible to dig deeper under nested TokenFactors.
19237     if (ChainVal == LdVal)
19238       Ld = cast<LoadSDNode>(St->getChain());
19239     else if (St->getValue().hasOneUse() &&
19240              ChainVal->getOpcode() == ISD::TokenFactor) {
19241       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19242         if (ChainVal->getOperand(i).getNode() == LdVal) {
19243           TokenFactorIndex = i;
19244           Ld = cast<LoadSDNode>(St->getValue());
19245         } else
19246           Ops.push_back(ChainVal->getOperand(i));
19247       }
19248     }
19249
19250     if (!Ld || !ISD::isNormalLoad(Ld))
19251       return SDValue();
19252
19253     // If this is not the MMX case, i.e. we are just turning i64 load/store
19254     // into f64 load/store, avoid the transformation if there are multiple
19255     // uses of the loaded value.
19256     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19257       return SDValue();
19258
19259     SDLoc LdDL(Ld);
19260     SDLoc StDL(N);
19261     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19262     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19263     // pair instead.
19264     if (Subtarget->is64Bit() || F64IsLegal) {
19265       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19266       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19267                                   Ld->getPointerInfo(), Ld->isVolatile(),
19268                                   Ld->isNonTemporal(), Ld->isInvariant(),
19269                                   Ld->getAlignment());
19270       SDValue NewChain = NewLd.getValue(1);
19271       if (TokenFactorIndex != -1) {
19272         Ops.push_back(NewChain);
19273         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19274                                Ops.size());
19275       }
19276       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19277                           St->getPointerInfo(),
19278                           St->isVolatile(), St->isNonTemporal(),
19279                           St->getAlignment());
19280     }
19281
19282     // Otherwise, lower to two pairs of 32-bit loads / stores.
19283     SDValue LoAddr = Ld->getBasePtr();
19284     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19285                                  DAG.getConstant(4, MVT::i32));
19286
19287     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19288                                Ld->getPointerInfo(),
19289                                Ld->isVolatile(), Ld->isNonTemporal(),
19290                                Ld->isInvariant(), Ld->getAlignment());
19291     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19292                                Ld->getPointerInfo().getWithOffset(4),
19293                                Ld->isVolatile(), Ld->isNonTemporal(),
19294                                Ld->isInvariant(),
19295                                MinAlign(Ld->getAlignment(), 4));
19296
19297     SDValue NewChain = LoLd.getValue(1);
19298     if (TokenFactorIndex != -1) {
19299       Ops.push_back(LoLd);
19300       Ops.push_back(HiLd);
19301       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19302                              Ops.size());
19303     }
19304
19305     LoAddr = St->getBasePtr();
19306     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19307                          DAG.getConstant(4, MVT::i32));
19308
19309     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19310                                 St->getPointerInfo(),
19311                                 St->isVolatile(), St->isNonTemporal(),
19312                                 St->getAlignment());
19313     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19314                                 St->getPointerInfo().getWithOffset(4),
19315                                 St->isVolatile(),
19316                                 St->isNonTemporal(),
19317                                 MinAlign(St->getAlignment(), 4));
19318     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19319   }
19320   return SDValue();
19321 }
19322
19323 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19324 /// and return the operands for the horizontal operation in LHS and RHS.  A
19325 /// horizontal operation performs the binary operation on successive elements
19326 /// of its first operand, then on successive elements of its second operand,
19327 /// returning the resulting values in a vector.  For example, if
19328 ///   A = < float a0, float a1, float a2, float a3 >
19329 /// and
19330 ///   B = < float b0, float b1, float b2, float b3 >
19331 /// then the result of doing a horizontal operation on A and B is
19332 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19333 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19334 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19335 /// set to A, RHS to B, and the routine returns 'true'.
19336 /// Note that the binary operation should have the property that if one of the
19337 /// operands is UNDEF then the result is UNDEF.
19338 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19339   // Look for the following pattern: if
19340   //   A = < float a0, float a1, float a2, float a3 >
19341   //   B = < float b0, float b1, float b2, float b3 >
19342   // and
19343   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19344   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19345   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19346   // which is A horizontal-op B.
19347
19348   // At least one of the operands should be a vector shuffle.
19349   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19350       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19351     return false;
19352
19353   MVT VT = LHS.getSimpleValueType();
19354
19355   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19356          "Unsupported vector type for horizontal add/sub");
19357
19358   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19359   // operate independently on 128-bit lanes.
19360   unsigned NumElts = VT.getVectorNumElements();
19361   unsigned NumLanes = VT.getSizeInBits()/128;
19362   unsigned NumLaneElts = NumElts / NumLanes;
19363   assert((NumLaneElts % 2 == 0) &&
19364          "Vector type should have an even number of elements in each lane");
19365   unsigned HalfLaneElts = NumLaneElts/2;
19366
19367   // View LHS in the form
19368   //   LHS = VECTOR_SHUFFLE A, B, LMask
19369   // If LHS is not a shuffle then pretend it is the shuffle
19370   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19371   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19372   // type VT.
19373   SDValue A, B;
19374   SmallVector<int, 16> LMask(NumElts);
19375   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19376     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19377       A = LHS.getOperand(0);
19378     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19379       B = LHS.getOperand(1);
19380     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19381     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19382   } else {
19383     if (LHS.getOpcode() != ISD::UNDEF)
19384       A = LHS;
19385     for (unsigned i = 0; i != NumElts; ++i)
19386       LMask[i] = i;
19387   }
19388
19389   // Likewise, view RHS in the form
19390   //   RHS = VECTOR_SHUFFLE C, D, RMask
19391   SDValue C, D;
19392   SmallVector<int, 16> RMask(NumElts);
19393   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19394     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19395       C = RHS.getOperand(0);
19396     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19397       D = RHS.getOperand(1);
19398     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19399     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19400   } else {
19401     if (RHS.getOpcode() != ISD::UNDEF)
19402       C = RHS;
19403     for (unsigned i = 0; i != NumElts; ++i)
19404       RMask[i] = i;
19405   }
19406
19407   // Check that the shuffles are both shuffling the same vectors.
19408   if (!(A == C && B == D) && !(A == D && B == C))
19409     return false;
19410
19411   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19412   if (!A.getNode() && !B.getNode())
19413     return false;
19414
19415   // If A and B occur in reverse order in RHS, then "swap" them (which means
19416   // rewriting the mask).
19417   if (A != C)
19418     CommuteVectorShuffleMask(RMask, NumElts);
19419
19420   // At this point LHS and RHS are equivalent to
19421   //   LHS = VECTOR_SHUFFLE A, B, LMask
19422   //   RHS = VECTOR_SHUFFLE A, B, RMask
19423   // Check that the masks correspond to performing a horizontal operation.
19424   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19425     for (unsigned i = 0; i != NumLaneElts; ++i) {
19426       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19427
19428       // Ignore any UNDEF components.
19429       if (LIdx < 0 || RIdx < 0 ||
19430           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19431           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19432         continue;
19433
19434       // Check that successive elements are being operated on.  If not, this is
19435       // not a horizontal operation.
19436       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19437       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19438       if (!(LIdx == Index && RIdx == Index + 1) &&
19439           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19440         return false;
19441     }
19442   }
19443
19444   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19445   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19446   return true;
19447 }
19448
19449 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19450 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19451                                   const X86Subtarget *Subtarget) {
19452   EVT VT = N->getValueType(0);
19453   SDValue LHS = N->getOperand(0);
19454   SDValue RHS = N->getOperand(1);
19455
19456   // Try to synthesize horizontal adds from adds of shuffles.
19457   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19458        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19459       isHorizontalBinOp(LHS, RHS, true))
19460     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19461   return SDValue();
19462 }
19463
19464 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19465 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19466                                   const X86Subtarget *Subtarget) {
19467   EVT VT = N->getValueType(0);
19468   SDValue LHS = N->getOperand(0);
19469   SDValue RHS = N->getOperand(1);
19470
19471   // Try to synthesize horizontal subs from subs of shuffles.
19472   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19473        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19474       isHorizontalBinOp(LHS, RHS, false))
19475     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19476   return SDValue();
19477 }
19478
19479 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19480 /// X86ISD::FXOR nodes.
19481 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19482   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19483   // F[X]OR(0.0, x) -> x
19484   // F[X]OR(x, 0.0) -> x
19485   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19486     if (C->getValueAPF().isPosZero())
19487       return N->getOperand(1);
19488   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19489     if (C->getValueAPF().isPosZero())
19490       return N->getOperand(0);
19491   return SDValue();
19492 }
19493
19494 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19495 /// X86ISD::FMAX nodes.
19496 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19497   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19498
19499   // Only perform optimizations if UnsafeMath is used.
19500   if (!DAG.getTarget().Options.UnsafeFPMath)
19501     return SDValue();
19502
19503   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19504   // into FMINC and FMAXC, which are Commutative operations.
19505   unsigned NewOp = 0;
19506   switch (N->getOpcode()) {
19507     default: llvm_unreachable("unknown opcode");
19508     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19509     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19510   }
19511
19512   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19513                      N->getOperand(0), N->getOperand(1));
19514 }
19515
19516 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19517 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19518   // FAND(0.0, x) -> 0.0
19519   // FAND(x, 0.0) -> 0.0
19520   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19521     if (C->getValueAPF().isPosZero())
19522       return N->getOperand(0);
19523   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19524     if (C->getValueAPF().isPosZero())
19525       return N->getOperand(1);
19526   return SDValue();
19527 }
19528
19529 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19530 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19531   // FANDN(x, 0.0) -> 0.0
19532   // FANDN(0.0, x) -> x
19533   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19534     if (C->getValueAPF().isPosZero())
19535       return N->getOperand(1);
19536   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19537     if (C->getValueAPF().isPosZero())
19538       return N->getOperand(1);
19539   return SDValue();
19540 }
19541
19542 static SDValue PerformBTCombine(SDNode *N,
19543                                 SelectionDAG &DAG,
19544                                 TargetLowering::DAGCombinerInfo &DCI) {
19545   // BT ignores high bits in the bit index operand.
19546   SDValue Op1 = N->getOperand(1);
19547   if (Op1.hasOneUse()) {
19548     unsigned BitWidth = Op1.getValueSizeInBits();
19549     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19550     APInt KnownZero, KnownOne;
19551     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19552                                           !DCI.isBeforeLegalizeOps());
19553     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19554     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19555         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19556       DCI.CommitTargetLoweringOpt(TLO);
19557   }
19558   return SDValue();
19559 }
19560
19561 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19562   SDValue Op = N->getOperand(0);
19563   if (Op.getOpcode() == ISD::BITCAST)
19564     Op = Op.getOperand(0);
19565   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19566   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19567       VT.getVectorElementType().getSizeInBits() ==
19568       OpVT.getVectorElementType().getSizeInBits()) {
19569     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19570   }
19571   return SDValue();
19572 }
19573
19574 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19575                                                const X86Subtarget *Subtarget) {
19576   EVT VT = N->getValueType(0);
19577   if (!VT.isVector())
19578     return SDValue();
19579
19580   SDValue N0 = N->getOperand(0);
19581   SDValue N1 = N->getOperand(1);
19582   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19583   SDLoc dl(N);
19584
19585   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19586   // both SSE and AVX2 since there is no sign-extended shift right
19587   // operation on a vector with 64-bit elements.
19588   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19589   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19590   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19591       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19592     SDValue N00 = N0.getOperand(0);
19593
19594     // EXTLOAD has a better solution on AVX2,
19595     // it may be replaced with X86ISD::VSEXT node.
19596     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19597       if (!ISD::isNormalLoad(N00.getNode()))
19598         return SDValue();
19599
19600     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19601         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19602                                   N00, N1);
19603       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19604     }
19605   }
19606   return SDValue();
19607 }
19608
19609 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19610                                   TargetLowering::DAGCombinerInfo &DCI,
19611                                   const X86Subtarget *Subtarget) {
19612   if (!DCI.isBeforeLegalizeOps())
19613     return SDValue();
19614
19615   if (!Subtarget->hasFp256())
19616     return SDValue();
19617
19618   EVT VT = N->getValueType(0);
19619   if (VT.isVector() && VT.getSizeInBits() == 256) {
19620     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19621     if (R.getNode())
19622       return R;
19623   }
19624
19625   return SDValue();
19626 }
19627
19628 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19629                                  const X86Subtarget* Subtarget) {
19630   SDLoc dl(N);
19631   EVT VT = N->getValueType(0);
19632
19633   // Let legalize expand this if it isn't a legal type yet.
19634   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19635     return SDValue();
19636
19637   EVT ScalarVT = VT.getScalarType();
19638   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19639       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19640     return SDValue();
19641
19642   SDValue A = N->getOperand(0);
19643   SDValue B = N->getOperand(1);
19644   SDValue C = N->getOperand(2);
19645
19646   bool NegA = (A.getOpcode() == ISD::FNEG);
19647   bool NegB = (B.getOpcode() == ISD::FNEG);
19648   bool NegC = (C.getOpcode() == ISD::FNEG);
19649
19650   // Negative multiplication when NegA xor NegB
19651   bool NegMul = (NegA != NegB);
19652   if (NegA)
19653     A = A.getOperand(0);
19654   if (NegB)
19655     B = B.getOperand(0);
19656   if (NegC)
19657     C = C.getOperand(0);
19658
19659   unsigned Opcode;
19660   if (!NegMul)
19661     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19662   else
19663     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19664
19665   return DAG.getNode(Opcode, dl, VT, A, B, C);
19666 }
19667
19668 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19669                                   TargetLowering::DAGCombinerInfo &DCI,
19670                                   const X86Subtarget *Subtarget) {
19671   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19672   //           (and (i32 x86isd::setcc_carry), 1)
19673   // This eliminates the zext. This transformation is necessary because
19674   // ISD::SETCC is always legalized to i8.
19675   SDLoc dl(N);
19676   SDValue N0 = N->getOperand(0);
19677   EVT VT = N->getValueType(0);
19678
19679   if (N0.getOpcode() == ISD::AND &&
19680       N0.hasOneUse() &&
19681       N0.getOperand(0).hasOneUse()) {
19682     SDValue N00 = N0.getOperand(0);
19683     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19684       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19685       if (!C || C->getZExtValue() != 1)
19686         return SDValue();
19687       return DAG.getNode(ISD::AND, dl, VT,
19688                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19689                                      N00.getOperand(0), N00.getOperand(1)),
19690                          DAG.getConstant(1, VT));
19691     }
19692   }
19693
19694   if (N0.getOpcode() == ISD::TRUNCATE &&
19695       N0.hasOneUse() &&
19696       N0.getOperand(0).hasOneUse()) {
19697     SDValue N00 = N0.getOperand(0);
19698     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19699       return DAG.getNode(ISD::AND, dl, VT,
19700                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19701                                      N00.getOperand(0), N00.getOperand(1)),
19702                          DAG.getConstant(1, VT));
19703     }
19704   }
19705   if (VT.is256BitVector()) {
19706     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19707     if (R.getNode())
19708       return R;
19709   }
19710
19711   return SDValue();
19712 }
19713
19714 // Optimize x == -y --> x+y == 0
19715 //          x != -y --> x+y != 0
19716 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19717                                       const X86Subtarget* Subtarget) {
19718   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19719   SDValue LHS = N->getOperand(0);
19720   SDValue RHS = N->getOperand(1);
19721   EVT VT = N->getValueType(0);
19722   SDLoc DL(N);
19723
19724   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19725     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19726       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19727         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19728                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19729         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19730                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19731       }
19732   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19733     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19734       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19735         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19736                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19737         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19738                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19739       }
19740
19741   if (VT.getScalarType() == MVT::i1) {
19742     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19743       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19744     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19745     if (!IsSEXT0 && !IsVZero0)
19746       return SDValue();
19747     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19748       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19749     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19750
19751     if (!IsSEXT1 && !IsVZero1)
19752       return SDValue();
19753
19754     if (IsSEXT0 && IsVZero1) {
19755       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19756       if (CC == ISD::SETEQ)
19757         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19758       return LHS.getOperand(0);
19759     }
19760     if (IsSEXT1 && IsVZero0) {
19761       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19762       if (CC == ISD::SETEQ)
19763         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19764       return RHS.getOperand(0);
19765     }
19766   }
19767
19768   return SDValue();
19769 }
19770
19771 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19772 // as "sbb reg,reg", since it can be extended without zext and produces
19773 // an all-ones bit which is more useful than 0/1 in some cases.
19774 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19775                                MVT VT) {
19776   if (VT == MVT::i8)
19777     return DAG.getNode(ISD::AND, DL, VT,
19778                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19779                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19780                        DAG.getConstant(1, VT));
19781   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19782   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19783                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19784                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19785 }
19786
19787 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19788 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19789                                    TargetLowering::DAGCombinerInfo &DCI,
19790                                    const X86Subtarget *Subtarget) {
19791   SDLoc DL(N);
19792   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19793   SDValue EFLAGS = N->getOperand(1);
19794
19795   if (CC == X86::COND_A) {
19796     // Try to convert COND_A into COND_B in an attempt to facilitate
19797     // materializing "setb reg".
19798     //
19799     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19800     // cannot take an immediate as its first operand.
19801     //
19802     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19803         EFLAGS.getValueType().isInteger() &&
19804         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19805       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19806                                    EFLAGS.getNode()->getVTList(),
19807                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19808       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19809       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19810     }
19811   }
19812
19813   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19814   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19815   // cases.
19816   if (CC == X86::COND_B)
19817     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19818
19819   SDValue Flags;
19820
19821   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19822   if (Flags.getNode()) {
19823     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19824     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19825   }
19826
19827   return SDValue();
19828 }
19829
19830 // Optimize branch condition evaluation.
19831 //
19832 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19833                                     TargetLowering::DAGCombinerInfo &DCI,
19834                                     const X86Subtarget *Subtarget) {
19835   SDLoc DL(N);
19836   SDValue Chain = N->getOperand(0);
19837   SDValue Dest = N->getOperand(1);
19838   SDValue EFLAGS = N->getOperand(3);
19839   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19840
19841   SDValue Flags;
19842
19843   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19844   if (Flags.getNode()) {
19845     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19846     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19847                        Flags);
19848   }
19849
19850   return SDValue();
19851 }
19852
19853 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19854                                         const X86TargetLowering *XTLI) {
19855   SDValue Op0 = N->getOperand(0);
19856   EVT InVT = Op0->getValueType(0);
19857
19858   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19859   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19860     SDLoc dl(N);
19861     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19862     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19863     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19864   }
19865
19866   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19867   // a 32-bit target where SSE doesn't support i64->FP operations.
19868   if (Op0.getOpcode() == ISD::LOAD) {
19869     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19870     EVT VT = Ld->getValueType(0);
19871     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19872         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19873         !XTLI->getSubtarget()->is64Bit() &&
19874         VT == MVT::i64) {
19875       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19876                                           Ld->getChain(), Op0, DAG);
19877       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19878       return FILDChain;
19879     }
19880   }
19881   return SDValue();
19882 }
19883
19884 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19885 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19886                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19887   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19888   // the result is either zero or one (depending on the input carry bit).
19889   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19890   if (X86::isZeroNode(N->getOperand(0)) &&
19891       X86::isZeroNode(N->getOperand(1)) &&
19892       // We don't have a good way to replace an EFLAGS use, so only do this when
19893       // dead right now.
19894       SDValue(N, 1).use_empty()) {
19895     SDLoc DL(N);
19896     EVT VT = N->getValueType(0);
19897     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19898     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19899                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19900                                            DAG.getConstant(X86::COND_B,MVT::i8),
19901                                            N->getOperand(2)),
19902                                DAG.getConstant(1, VT));
19903     return DCI.CombineTo(N, Res1, CarryOut);
19904   }
19905
19906   return SDValue();
19907 }
19908
19909 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19910 //      (add Y, (setne X, 0)) -> sbb -1, Y
19911 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19912 //      (sub (setne X, 0), Y) -> adc -1, Y
19913 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19914   SDLoc DL(N);
19915
19916   // Look through ZExts.
19917   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19918   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19919     return SDValue();
19920
19921   SDValue SetCC = Ext.getOperand(0);
19922   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19923     return SDValue();
19924
19925   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19926   if (CC != X86::COND_E && CC != X86::COND_NE)
19927     return SDValue();
19928
19929   SDValue Cmp = SetCC.getOperand(1);
19930   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19931       !X86::isZeroNode(Cmp.getOperand(1)) ||
19932       !Cmp.getOperand(0).getValueType().isInteger())
19933     return SDValue();
19934
19935   SDValue CmpOp0 = Cmp.getOperand(0);
19936   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19937                                DAG.getConstant(1, CmpOp0.getValueType()));
19938
19939   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19940   if (CC == X86::COND_NE)
19941     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19942                        DL, OtherVal.getValueType(), OtherVal,
19943                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19944   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19945                      DL, OtherVal.getValueType(), OtherVal,
19946                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19947 }
19948
19949 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19950 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19951                                  const X86Subtarget *Subtarget) {
19952   EVT VT = N->getValueType(0);
19953   SDValue Op0 = N->getOperand(0);
19954   SDValue Op1 = N->getOperand(1);
19955
19956   // Try to synthesize horizontal adds from adds of shuffles.
19957   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19958        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19959       isHorizontalBinOp(Op0, Op1, true))
19960     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19961
19962   return OptimizeConditionalInDecrement(N, DAG);
19963 }
19964
19965 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19966                                  const X86Subtarget *Subtarget) {
19967   SDValue Op0 = N->getOperand(0);
19968   SDValue Op1 = N->getOperand(1);
19969
19970   // X86 can't encode an immediate LHS of a sub. See if we can push the
19971   // negation into a preceding instruction.
19972   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19973     // If the RHS of the sub is a XOR with one use and a constant, invert the
19974     // immediate. Then add one to the LHS of the sub so we can turn
19975     // X-Y -> X+~Y+1, saving one register.
19976     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19977         isa<ConstantSDNode>(Op1.getOperand(1))) {
19978       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19979       EVT VT = Op0.getValueType();
19980       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19981                                    Op1.getOperand(0),
19982                                    DAG.getConstant(~XorC, VT));
19983       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19984                          DAG.getConstant(C->getAPIntValue()+1, VT));
19985     }
19986   }
19987
19988   // Try to synthesize horizontal adds from adds of shuffles.
19989   EVT VT = N->getValueType(0);
19990   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19991        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19992       isHorizontalBinOp(Op0, Op1, true))
19993     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19994
19995   return OptimizeConditionalInDecrement(N, DAG);
19996 }
19997
19998 /// performVZEXTCombine - Performs build vector combines
19999 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20000                                         TargetLowering::DAGCombinerInfo &DCI,
20001                                         const X86Subtarget *Subtarget) {
20002   // (vzext (bitcast (vzext (x)) -> (vzext x)
20003   SDValue In = N->getOperand(0);
20004   while (In.getOpcode() == ISD::BITCAST)
20005     In = In.getOperand(0);
20006
20007   if (In.getOpcode() != X86ISD::VZEXT)
20008     return SDValue();
20009
20010   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20011                      In.getOperand(0));
20012 }
20013
20014 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20015                                              DAGCombinerInfo &DCI) const {
20016   SelectionDAG &DAG = DCI.DAG;
20017   switch (N->getOpcode()) {
20018   default: break;
20019   case ISD::EXTRACT_VECTOR_ELT:
20020     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20021   case ISD::VSELECT:
20022   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20023   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20024   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20025   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20026   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20027   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20028   case ISD::SHL:
20029   case ISD::SRA:
20030   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20031   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20032   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20033   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20034   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20035   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20036   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20037   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20038   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20039   case X86ISD::FXOR:
20040   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20041   case X86ISD::FMIN:
20042   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20043   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20044   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20045   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20046   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20047   case ISD::ANY_EXTEND:
20048   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20049   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20050   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20051   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20052   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20053   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20054   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20055   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20056   case X86ISD::SHUFP:       // Handle all target specific shuffles
20057   case X86ISD::PALIGNR:
20058   case X86ISD::UNPCKH:
20059   case X86ISD::UNPCKL:
20060   case X86ISD::MOVHLPS:
20061   case X86ISD::MOVLHPS:
20062   case X86ISD::PSHUFD:
20063   case X86ISD::PSHUFHW:
20064   case X86ISD::PSHUFLW:
20065   case X86ISD::MOVSS:
20066   case X86ISD::MOVSD:
20067   case X86ISD::VPERMILP:
20068   case X86ISD::VPERM2X128:
20069   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20070   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20071   }
20072
20073   return SDValue();
20074 }
20075
20076 /// isTypeDesirableForOp - Return true if the target has native support for
20077 /// the specified value type and it is 'desirable' to use the type for the
20078 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20079 /// instruction encodings are longer and some i16 instructions are slow.
20080 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20081   if (!isTypeLegal(VT))
20082     return false;
20083   if (VT != MVT::i16)
20084     return true;
20085
20086   switch (Opc) {
20087   default:
20088     return true;
20089   case ISD::LOAD:
20090   case ISD::SIGN_EXTEND:
20091   case ISD::ZERO_EXTEND:
20092   case ISD::ANY_EXTEND:
20093   case ISD::SHL:
20094   case ISD::SRL:
20095   case ISD::SUB:
20096   case ISD::ADD:
20097   case ISD::MUL:
20098   case ISD::AND:
20099   case ISD::OR:
20100   case ISD::XOR:
20101     return false;
20102   }
20103 }
20104
20105 /// IsDesirableToPromoteOp - This method query the target whether it is
20106 /// beneficial for dag combiner to promote the specified node. If true, it
20107 /// should return the desired promotion type by reference.
20108 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20109   EVT VT = Op.getValueType();
20110   if (VT != MVT::i16)
20111     return false;
20112
20113   bool Promote = false;
20114   bool Commute = false;
20115   switch (Op.getOpcode()) {
20116   default: break;
20117   case ISD::LOAD: {
20118     LoadSDNode *LD = cast<LoadSDNode>(Op);
20119     // If the non-extending load has a single use and it's not live out, then it
20120     // might be folded.
20121     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20122                                                      Op.hasOneUse()*/) {
20123       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20124              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20125         // The only case where we'd want to promote LOAD (rather then it being
20126         // promoted as an operand is when it's only use is liveout.
20127         if (UI->getOpcode() != ISD::CopyToReg)
20128           return false;
20129       }
20130     }
20131     Promote = true;
20132     break;
20133   }
20134   case ISD::SIGN_EXTEND:
20135   case ISD::ZERO_EXTEND:
20136   case ISD::ANY_EXTEND:
20137     Promote = true;
20138     break;
20139   case ISD::SHL:
20140   case ISD::SRL: {
20141     SDValue N0 = Op.getOperand(0);
20142     // Look out for (store (shl (load), x)).
20143     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20144       return false;
20145     Promote = true;
20146     break;
20147   }
20148   case ISD::ADD:
20149   case ISD::MUL:
20150   case ISD::AND:
20151   case ISD::OR:
20152   case ISD::XOR:
20153     Commute = true;
20154     // fallthrough
20155   case ISD::SUB: {
20156     SDValue N0 = Op.getOperand(0);
20157     SDValue N1 = Op.getOperand(1);
20158     if (!Commute && MayFoldLoad(N1))
20159       return false;
20160     // Avoid disabling potential load folding opportunities.
20161     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20162       return false;
20163     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20164       return false;
20165     Promote = true;
20166   }
20167   }
20168
20169   PVT = MVT::i32;
20170   return Promote;
20171 }
20172
20173 //===----------------------------------------------------------------------===//
20174 //                           X86 Inline Assembly Support
20175 //===----------------------------------------------------------------------===//
20176
20177 namespace {
20178   // Helper to match a string separated by whitespace.
20179   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20180     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20181
20182     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20183       StringRef piece(*args[i]);
20184       if (!s.startswith(piece)) // Check if the piece matches.
20185         return false;
20186
20187       s = s.substr(piece.size());
20188       StringRef::size_type pos = s.find_first_not_of(" \t");
20189       if (pos == 0) // We matched a prefix.
20190         return false;
20191
20192       s = s.substr(pos);
20193     }
20194
20195     return s.empty();
20196   }
20197   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20198 }
20199
20200 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20201
20202   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20203     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20204         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20205         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20206
20207       if (AsmPieces.size() == 3)
20208         return true;
20209       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20210         return true;
20211     }
20212   }
20213   return false;
20214 }
20215
20216 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20217   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20218
20219   std::string AsmStr = IA->getAsmString();
20220
20221   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20222   if (!Ty || Ty->getBitWidth() % 16 != 0)
20223     return false;
20224
20225   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20226   SmallVector<StringRef, 4> AsmPieces;
20227   SplitString(AsmStr, AsmPieces, ";\n");
20228
20229   switch (AsmPieces.size()) {
20230   default: return false;
20231   case 1:
20232     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20233     // we will turn this bswap into something that will be lowered to logical
20234     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20235     // lower so don't worry about this.
20236     // bswap $0
20237     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20238         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20239         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20240         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20241         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20242         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20243       // No need to check constraints, nothing other than the equivalent of
20244       // "=r,0" would be valid here.
20245       return IntrinsicLowering::LowerToByteSwap(CI);
20246     }
20247
20248     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20249     if (CI->getType()->isIntegerTy(16) &&
20250         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20251         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20252          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20253       AsmPieces.clear();
20254       const std::string &ConstraintsStr = IA->getConstraintString();
20255       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20256       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20257       if (clobbersFlagRegisters(AsmPieces))
20258         return IntrinsicLowering::LowerToByteSwap(CI);
20259     }
20260     break;
20261   case 3:
20262     if (CI->getType()->isIntegerTy(32) &&
20263         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20264         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20265         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20266         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20267       AsmPieces.clear();
20268       const std::string &ConstraintsStr = IA->getConstraintString();
20269       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20270       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20271       if (clobbersFlagRegisters(AsmPieces))
20272         return IntrinsicLowering::LowerToByteSwap(CI);
20273     }
20274
20275     if (CI->getType()->isIntegerTy(64)) {
20276       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20277       if (Constraints.size() >= 2 &&
20278           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20279           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20280         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20281         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20282             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20283             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20284           return IntrinsicLowering::LowerToByteSwap(CI);
20285       }
20286     }
20287     break;
20288   }
20289   return false;
20290 }
20291
20292 /// getConstraintType - Given a constraint letter, return the type of
20293 /// constraint it is for this target.
20294 X86TargetLowering::ConstraintType
20295 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20296   if (Constraint.size() == 1) {
20297     switch (Constraint[0]) {
20298     case 'R':
20299     case 'q':
20300     case 'Q':
20301     case 'f':
20302     case 't':
20303     case 'u':
20304     case 'y':
20305     case 'x':
20306     case 'Y':
20307     case 'l':
20308       return C_RegisterClass;
20309     case 'a':
20310     case 'b':
20311     case 'c':
20312     case 'd':
20313     case 'S':
20314     case 'D':
20315     case 'A':
20316       return C_Register;
20317     case 'I':
20318     case 'J':
20319     case 'K':
20320     case 'L':
20321     case 'M':
20322     case 'N':
20323     case 'G':
20324     case 'C':
20325     case 'e':
20326     case 'Z':
20327       return C_Other;
20328     default:
20329       break;
20330     }
20331   }
20332   return TargetLowering::getConstraintType(Constraint);
20333 }
20334
20335 /// Examine constraint type and operand type and determine a weight value.
20336 /// This object must already have been set up with the operand type
20337 /// and the current alternative constraint selected.
20338 TargetLowering::ConstraintWeight
20339   X86TargetLowering::getSingleConstraintMatchWeight(
20340     AsmOperandInfo &info, const char *constraint) const {
20341   ConstraintWeight weight = CW_Invalid;
20342   Value *CallOperandVal = info.CallOperandVal;
20343     // If we don't have a value, we can't do a match,
20344     // but allow it at the lowest weight.
20345   if (!CallOperandVal)
20346     return CW_Default;
20347   Type *type = CallOperandVal->getType();
20348   // Look at the constraint type.
20349   switch (*constraint) {
20350   default:
20351     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20352   case 'R':
20353   case 'q':
20354   case 'Q':
20355   case 'a':
20356   case 'b':
20357   case 'c':
20358   case 'd':
20359   case 'S':
20360   case 'D':
20361   case 'A':
20362     if (CallOperandVal->getType()->isIntegerTy())
20363       weight = CW_SpecificReg;
20364     break;
20365   case 'f':
20366   case 't':
20367   case 'u':
20368     if (type->isFloatingPointTy())
20369       weight = CW_SpecificReg;
20370     break;
20371   case 'y':
20372     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20373       weight = CW_SpecificReg;
20374     break;
20375   case 'x':
20376   case 'Y':
20377     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20378         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20379       weight = CW_Register;
20380     break;
20381   case 'I':
20382     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20383       if (C->getZExtValue() <= 31)
20384         weight = CW_Constant;
20385     }
20386     break;
20387   case 'J':
20388     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20389       if (C->getZExtValue() <= 63)
20390         weight = CW_Constant;
20391     }
20392     break;
20393   case 'K':
20394     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20395       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20396         weight = CW_Constant;
20397     }
20398     break;
20399   case 'L':
20400     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20401       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20402         weight = CW_Constant;
20403     }
20404     break;
20405   case 'M':
20406     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20407       if (C->getZExtValue() <= 3)
20408         weight = CW_Constant;
20409     }
20410     break;
20411   case 'N':
20412     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20413       if (C->getZExtValue() <= 0xff)
20414         weight = CW_Constant;
20415     }
20416     break;
20417   case 'G':
20418   case 'C':
20419     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20420       weight = CW_Constant;
20421     }
20422     break;
20423   case 'e':
20424     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20425       if ((C->getSExtValue() >= -0x80000000LL) &&
20426           (C->getSExtValue() <= 0x7fffffffLL))
20427         weight = CW_Constant;
20428     }
20429     break;
20430   case 'Z':
20431     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20432       if (C->getZExtValue() <= 0xffffffff)
20433         weight = CW_Constant;
20434     }
20435     break;
20436   }
20437   return weight;
20438 }
20439
20440 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20441 /// with another that has more specific requirements based on the type of the
20442 /// corresponding operand.
20443 const char *X86TargetLowering::
20444 LowerXConstraint(EVT ConstraintVT) const {
20445   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20446   // 'f' like normal targets.
20447   if (ConstraintVT.isFloatingPoint()) {
20448     if (Subtarget->hasSSE2())
20449       return "Y";
20450     if (Subtarget->hasSSE1())
20451       return "x";
20452   }
20453
20454   return TargetLowering::LowerXConstraint(ConstraintVT);
20455 }
20456
20457 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20458 /// vector.  If it is invalid, don't add anything to Ops.
20459 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20460                                                      std::string &Constraint,
20461                                                      std::vector<SDValue>&Ops,
20462                                                      SelectionDAG &DAG) const {
20463   SDValue Result;
20464
20465   // Only support length 1 constraints for now.
20466   if (Constraint.length() > 1) return;
20467
20468   char ConstraintLetter = Constraint[0];
20469   switch (ConstraintLetter) {
20470   default: break;
20471   case 'I':
20472     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20473       if (C->getZExtValue() <= 31) {
20474         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20475         break;
20476       }
20477     }
20478     return;
20479   case 'J':
20480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20481       if (C->getZExtValue() <= 63) {
20482         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20483         break;
20484       }
20485     }
20486     return;
20487   case 'K':
20488     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20489       if (isInt<8>(C->getSExtValue())) {
20490         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20491         break;
20492       }
20493     }
20494     return;
20495   case 'N':
20496     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20497       if (C->getZExtValue() <= 255) {
20498         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20499         break;
20500       }
20501     }
20502     return;
20503   case 'e': {
20504     // 32-bit signed value
20505     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20506       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20507                                            C->getSExtValue())) {
20508         // Widen to 64 bits here to get it sign extended.
20509         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20510         break;
20511       }
20512     // FIXME gcc accepts some relocatable values here too, but only in certain
20513     // memory models; it's complicated.
20514     }
20515     return;
20516   }
20517   case 'Z': {
20518     // 32-bit unsigned value
20519     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20520       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20521                                            C->getZExtValue())) {
20522         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20523         break;
20524       }
20525     }
20526     // FIXME gcc accepts some relocatable values here too, but only in certain
20527     // memory models; it's complicated.
20528     return;
20529   }
20530   case 'i': {
20531     // Literal immediates are always ok.
20532     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20533       // Widen to 64 bits here to get it sign extended.
20534       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20535       break;
20536     }
20537
20538     // In any sort of PIC mode addresses need to be computed at runtime by
20539     // adding in a register or some sort of table lookup.  These can't
20540     // be used as immediates.
20541     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20542       return;
20543
20544     // If we are in non-pic codegen mode, we allow the address of a global (with
20545     // an optional displacement) to be used with 'i'.
20546     GlobalAddressSDNode *GA = nullptr;
20547     int64_t Offset = 0;
20548
20549     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20550     while (1) {
20551       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20552         Offset += GA->getOffset();
20553         break;
20554       } else if (Op.getOpcode() == ISD::ADD) {
20555         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20556           Offset += C->getZExtValue();
20557           Op = Op.getOperand(0);
20558           continue;
20559         }
20560       } else if (Op.getOpcode() == ISD::SUB) {
20561         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20562           Offset += -C->getZExtValue();
20563           Op = Op.getOperand(0);
20564           continue;
20565         }
20566       }
20567
20568       // Otherwise, this isn't something we can handle, reject it.
20569       return;
20570     }
20571
20572     const GlobalValue *GV = GA->getGlobal();
20573     // If we require an extra load to get this address, as in PIC mode, we
20574     // can't accept it.
20575     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20576                                                         getTargetMachine())))
20577       return;
20578
20579     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20580                                         GA->getValueType(0), Offset);
20581     break;
20582   }
20583   }
20584
20585   if (Result.getNode()) {
20586     Ops.push_back(Result);
20587     return;
20588   }
20589   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20590 }
20591
20592 std::pair<unsigned, const TargetRegisterClass*>
20593 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20594                                                 MVT VT) const {
20595   // First, see if this is a constraint that directly corresponds to an LLVM
20596   // register class.
20597   if (Constraint.size() == 1) {
20598     // GCC Constraint Letters
20599     switch (Constraint[0]) {
20600     default: break;
20601       // TODO: Slight differences here in allocation order and leaving
20602       // RIP in the class. Do they matter any more here than they do
20603       // in the normal allocation?
20604     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20605       if (Subtarget->is64Bit()) {
20606         if (VT == MVT::i32 || VT == MVT::f32)
20607           return std::make_pair(0U, &X86::GR32RegClass);
20608         if (VT == MVT::i16)
20609           return std::make_pair(0U, &X86::GR16RegClass);
20610         if (VT == MVT::i8 || VT == MVT::i1)
20611           return std::make_pair(0U, &X86::GR8RegClass);
20612         if (VT == MVT::i64 || VT == MVT::f64)
20613           return std::make_pair(0U, &X86::GR64RegClass);
20614         break;
20615       }
20616       // 32-bit fallthrough
20617     case 'Q':   // Q_REGS
20618       if (VT == MVT::i32 || VT == MVT::f32)
20619         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20620       if (VT == MVT::i16)
20621         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20622       if (VT == MVT::i8 || VT == MVT::i1)
20623         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20624       if (VT == MVT::i64)
20625         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20626       break;
20627     case 'r':   // GENERAL_REGS
20628     case 'l':   // INDEX_REGS
20629       if (VT == MVT::i8 || VT == MVT::i1)
20630         return std::make_pair(0U, &X86::GR8RegClass);
20631       if (VT == MVT::i16)
20632         return std::make_pair(0U, &X86::GR16RegClass);
20633       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20634         return std::make_pair(0U, &X86::GR32RegClass);
20635       return std::make_pair(0U, &X86::GR64RegClass);
20636     case 'R':   // LEGACY_REGS
20637       if (VT == MVT::i8 || VT == MVT::i1)
20638         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20639       if (VT == MVT::i16)
20640         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20641       if (VT == MVT::i32 || !Subtarget->is64Bit())
20642         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20643       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20644     case 'f':  // FP Stack registers.
20645       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20646       // value to the correct fpstack register class.
20647       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20648         return std::make_pair(0U, &X86::RFP32RegClass);
20649       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20650         return std::make_pair(0U, &X86::RFP64RegClass);
20651       return std::make_pair(0U, &X86::RFP80RegClass);
20652     case 'y':   // MMX_REGS if MMX allowed.
20653       if (!Subtarget->hasMMX()) break;
20654       return std::make_pair(0U, &X86::VR64RegClass);
20655     case 'Y':   // SSE_REGS if SSE2 allowed
20656       if (!Subtarget->hasSSE2()) break;
20657       // FALL THROUGH.
20658     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20659       if (!Subtarget->hasSSE1()) break;
20660
20661       switch (VT.SimpleTy) {
20662       default: break;
20663       // Scalar SSE types.
20664       case MVT::f32:
20665       case MVT::i32:
20666         return std::make_pair(0U, &X86::FR32RegClass);
20667       case MVT::f64:
20668       case MVT::i64:
20669         return std::make_pair(0U, &X86::FR64RegClass);
20670       // Vector types.
20671       case MVT::v16i8:
20672       case MVT::v8i16:
20673       case MVT::v4i32:
20674       case MVT::v2i64:
20675       case MVT::v4f32:
20676       case MVT::v2f64:
20677         return std::make_pair(0U, &X86::VR128RegClass);
20678       // AVX types.
20679       case MVT::v32i8:
20680       case MVT::v16i16:
20681       case MVT::v8i32:
20682       case MVT::v4i64:
20683       case MVT::v8f32:
20684       case MVT::v4f64:
20685         return std::make_pair(0U, &X86::VR256RegClass);
20686       case MVT::v8f64:
20687       case MVT::v16f32:
20688       case MVT::v16i32:
20689       case MVT::v8i64:
20690         return std::make_pair(0U, &X86::VR512RegClass);
20691       }
20692       break;
20693     }
20694   }
20695
20696   // Use the default implementation in TargetLowering to convert the register
20697   // constraint into a member of a register class.
20698   std::pair<unsigned, const TargetRegisterClass*> Res;
20699   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20700
20701   // Not found as a standard register?
20702   if (!Res.second) {
20703     // Map st(0) -> st(7) -> ST0
20704     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20705         tolower(Constraint[1]) == 's' &&
20706         tolower(Constraint[2]) == 't' &&
20707         Constraint[3] == '(' &&
20708         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20709         Constraint[5] == ')' &&
20710         Constraint[6] == '}') {
20711
20712       Res.first = X86::ST0+Constraint[4]-'0';
20713       Res.second = &X86::RFP80RegClass;
20714       return Res;
20715     }
20716
20717     // GCC allows "st(0)" to be called just plain "st".
20718     if (StringRef("{st}").equals_lower(Constraint)) {
20719       Res.first = X86::ST0;
20720       Res.second = &X86::RFP80RegClass;
20721       return Res;
20722     }
20723
20724     // flags -> EFLAGS
20725     if (StringRef("{flags}").equals_lower(Constraint)) {
20726       Res.first = X86::EFLAGS;
20727       Res.second = &X86::CCRRegClass;
20728       return Res;
20729     }
20730
20731     // 'A' means EAX + EDX.
20732     if (Constraint == "A") {
20733       Res.first = X86::EAX;
20734       Res.second = &X86::GR32_ADRegClass;
20735       return Res;
20736     }
20737     return Res;
20738   }
20739
20740   // Otherwise, check to see if this is a register class of the wrong value
20741   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20742   // turn into {ax},{dx}.
20743   if (Res.second->hasType(VT))
20744     return Res;   // Correct type already, nothing to do.
20745
20746   // All of the single-register GCC register classes map their values onto
20747   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20748   // really want an 8-bit or 32-bit register, map to the appropriate register
20749   // class and return the appropriate register.
20750   if (Res.second == &X86::GR16RegClass) {
20751     if (VT == MVT::i8 || VT == MVT::i1) {
20752       unsigned DestReg = 0;
20753       switch (Res.first) {
20754       default: break;
20755       case X86::AX: DestReg = X86::AL; break;
20756       case X86::DX: DestReg = X86::DL; break;
20757       case X86::CX: DestReg = X86::CL; break;
20758       case X86::BX: DestReg = X86::BL; break;
20759       }
20760       if (DestReg) {
20761         Res.first = DestReg;
20762         Res.second = &X86::GR8RegClass;
20763       }
20764     } else if (VT == MVT::i32 || VT == MVT::f32) {
20765       unsigned DestReg = 0;
20766       switch (Res.first) {
20767       default: break;
20768       case X86::AX: DestReg = X86::EAX; break;
20769       case X86::DX: DestReg = X86::EDX; break;
20770       case X86::CX: DestReg = X86::ECX; break;
20771       case X86::BX: DestReg = X86::EBX; break;
20772       case X86::SI: DestReg = X86::ESI; break;
20773       case X86::DI: DestReg = X86::EDI; break;
20774       case X86::BP: DestReg = X86::EBP; break;
20775       case X86::SP: DestReg = X86::ESP; break;
20776       }
20777       if (DestReg) {
20778         Res.first = DestReg;
20779         Res.second = &X86::GR32RegClass;
20780       }
20781     } else if (VT == MVT::i64 || VT == MVT::f64) {
20782       unsigned DestReg = 0;
20783       switch (Res.first) {
20784       default: break;
20785       case X86::AX: DestReg = X86::RAX; break;
20786       case X86::DX: DestReg = X86::RDX; break;
20787       case X86::CX: DestReg = X86::RCX; break;
20788       case X86::BX: DestReg = X86::RBX; break;
20789       case X86::SI: DestReg = X86::RSI; break;
20790       case X86::DI: DestReg = X86::RDI; break;
20791       case X86::BP: DestReg = X86::RBP; break;
20792       case X86::SP: DestReg = X86::RSP; break;
20793       }
20794       if (DestReg) {
20795         Res.first = DestReg;
20796         Res.second = &X86::GR64RegClass;
20797       }
20798     }
20799   } else if (Res.second == &X86::FR32RegClass ||
20800              Res.second == &X86::FR64RegClass ||
20801              Res.second == &X86::VR128RegClass ||
20802              Res.second == &X86::VR256RegClass ||
20803              Res.second == &X86::FR32XRegClass ||
20804              Res.second == &X86::FR64XRegClass ||
20805              Res.second == &X86::VR128XRegClass ||
20806              Res.second == &X86::VR256XRegClass ||
20807              Res.second == &X86::VR512RegClass) {
20808     // Handle references to XMM physical registers that got mapped into the
20809     // wrong class.  This can happen with constraints like {xmm0} where the
20810     // target independent register mapper will just pick the first match it can
20811     // find, ignoring the required type.
20812
20813     if (VT == MVT::f32 || VT == MVT::i32)
20814       Res.second = &X86::FR32RegClass;
20815     else if (VT == MVT::f64 || VT == MVT::i64)
20816       Res.second = &X86::FR64RegClass;
20817     else if (X86::VR128RegClass.hasType(VT))
20818       Res.second = &X86::VR128RegClass;
20819     else if (X86::VR256RegClass.hasType(VT))
20820       Res.second = &X86::VR256RegClass;
20821     else if (X86::VR512RegClass.hasType(VT))
20822       Res.second = &X86::VR512RegClass;
20823   }
20824
20825   return Res;
20826 }
20827
20828 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20829                                             Type *Ty) const {
20830   // Scaling factors are not free at all.
20831   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20832   // will take 2 allocations instead of 1 for plain addressing mode,
20833   // i.e. inst (reg1).
20834   if (isLegalAddressingMode(AM, Ty))
20835     // Scale represents reg2 * scale, thus account for 1
20836     // as soon as we use a second register.
20837     return AM.Scale != 0;
20838   return -1;
20839 }