df2785c06759ddf24b98ea7cfb7b98c31d0fabc3
[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 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86CallingConv.h"
20 #include "X86InstrBuilder.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.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/IR/LLVMContext.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <cctype>
54 using namespace llvm;
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->isTargetEnvMacho()) {
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->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
194     return new TargetLoweringObjectFileCOFF();
195   llvm_unreachable("unknown subtarget type");
196 }
197
198 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
199   : TargetLowering(TM, createTLOF(TM)) {
200   Subtarget = &TM.getSubtarget<X86Subtarget>();
201   X86ScalarSSEf64 = Subtarget->hasSSE2();
202   X86ScalarSSEf32 = Subtarget->hasSSE1();
203   TD = getDataLayout();
204
205   resetOperationActions();
206 }
207
208 void X86TargetLowering::resetOperationActions() {
209   const TargetMachine &TM = getTargetMachine();
210   static bool FirstTimeThrough = true;
211
212   // If none of the target options have changed, then we don't need to reset the
213   // operation actions.
214   if (!FirstTimeThrough && TO == TM.Options) return;
215
216   if (!FirstTimeThrough) {
217     // Reinitialize the actions.
218     initActions();
219     FirstTimeThrough = false;
220   }
221
222   TO = TM.Options;
223
224   // Set up the TargetLowering object.
225   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
226
227   // X86 is weird, it always uses i8 for shift amounts and setcc results.
228   setBooleanContents(ZeroOrOneBooleanContent);
229   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
230   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231
232   // For 64-bit since we have so many registers use the ILP scheduler, for
233   // 32-bit code use the register pressure specific scheduling.
234   // For Atom, always use ILP scheduling.
235   if (Subtarget->isAtom())
236     setSchedulingPreference(Sched::ILP);
237   else if (Subtarget->is64Bit())
238     setSchedulingPreference(Sched::ILP);
239   else
240     setSchedulingPreference(Sched::RegPressure);
241   const X86RegisterInfo *RegInfo =
242     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
243   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
244
245   // Bypass expensive divides on Atom when compiling with O2
246   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
247     addBypassSlowDiv(32, 8);
248     if (Subtarget->is64Bit())
249       addBypassSlowDiv(64, 16);
250   }
251
252   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
253     // Setup Windows compiler runtime calls.
254     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
255     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
256     setLibcallName(RTLIB::SREM_I64, "_allrem");
257     setLibcallName(RTLIB::UREM_I64, "_aullrem");
258     setLibcallName(RTLIB::MUL_I64, "_allmul");
259     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
264
265     // The _ftol2 runtime function has an unusual calling conv, which
266     // is modeled by a special pseudo-instruction.
267     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
268     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
269     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
270     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
271   }
272
273   if (Subtarget->isTargetDarwin()) {
274     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
275     setUseUnderscoreSetJmp(false);
276     setUseUnderscoreLongJmp(false);
277   } else if (Subtarget->isTargetMingw()) {
278     // MS runtime is weird: it exports _setjmp, but longjmp!
279     setUseUnderscoreSetJmp(true);
280     setUseUnderscoreLongJmp(false);
281   } else {
282     setUseUnderscoreSetJmp(true);
283     setUseUnderscoreLongJmp(true);
284   }
285
286   // Set up the register classes.
287   addRegisterClass(MVT::i8, &X86::GR8RegClass);
288   addRegisterClass(MVT::i16, &X86::GR16RegClass);
289   addRegisterClass(MVT::i32, &X86::GR32RegClass);
290   if (Subtarget->is64Bit())
291     addRegisterClass(MVT::i64, &X86::GR64RegClass);
292
293   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
294
295   // We don't accept any truncstore of integer registers.
296   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
297   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
299   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
302
303   // SETOEQ and SETUNE require checking two conditions.
304   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
305   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
310
311   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
312   // operation.
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
316
317   if (Subtarget->is64Bit()) {
318     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
320   } else if (!TM.Options.UseSoftFloat) {
321     // We have an algorithm for SSE2->double, and we turn this into a
322     // 64-bit FILD followed by conditional FADD for other targets.
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324     // We have an algorithm for SSE2, and we turn this into a 64-bit
325     // FILD for other targets.
326     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
327   }
328
329   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
330   // this operation.
331   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
333
334   if (!TM.Options.UseSoftFloat) {
335     // SSE has no i16 to fp conversion, only i32
336     if (X86ScalarSSEf32) {
337       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
338       // f32 and f64 cases are Legal, f80 case is not
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
340     } else {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
343     }
344   } else {
345     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
347   }
348
349   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
350   // are Legal, f80 is custom lowered.
351   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
352   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
353
354   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
355   // this operation.
356   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
358
359   if (X86ScalarSSEf32) {
360     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
361     // f32 and f64 cases are Legal, f80 case is not
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
363   } else {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
366   }
367
368   // Handle FP_TO_UINT by promoting the destination to a larger signed
369   // conversion.
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
373
374   if (Subtarget->is64Bit()) {
375     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
377   } else if (!TM.Options.UseSoftFloat) {
378     // Since AVX is a superset of SSE3, only check for SSE here.
379     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
380       // Expand FP_TO_UINT into a select.
381       // FIXME: We would like to use a Custom expander here eventually to do
382       // the optimal thing for SSE vs. the default expansion in the legalizer.
383       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
384     else
385       // With SSE3 we can use fisttpll to convert to a signed i64; without
386       // SSE, we're stuck with a fistpll.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
388   }
389
390   if (isTargetFTOL()) {
391     // Use the _ftol2 runtime function, which has a pseudo-instruction
392     // to handle its weird calling convention.
393     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
394   }
395
396   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
397   if (!X86ScalarSSEf64) {
398     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
399     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
400     if (Subtarget->is64Bit()) {
401       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
402       // Without SSE, i64->f64 goes through memory.
403       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
404     }
405   }
406
407   // Scalar integer divide and remainder are lowered to use operations that
408   // produce two results, to match the available instructions. This exposes
409   // the two-result form to trivial CSE, which is able to combine x/y and x%y
410   // into a single instruction.
411   //
412   // Scalar integer multiply-high is also lowered to use two-result
413   // operations, to match the available instructions. However, plain multiply
414   // (low) operations are left as Legal, as there are single-result
415   // instructions for this in x86. Using the two-result multiply instructions
416   // when both high and low results are needed must be arranged by dagcombine.
417   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
418     MVT VT = IntVTs[i];
419     setOperationAction(ISD::MULHS, VT, Expand);
420     setOperationAction(ISD::MULHU, VT, Expand);
421     setOperationAction(ISD::SDIV, VT, Expand);
422     setOperationAction(ISD::UDIV, VT, Expand);
423     setOperationAction(ISD::SREM, VT, Expand);
424     setOperationAction(ISD::UREM, VT, Expand);
425
426     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
427     setOperationAction(ISD::ADDC, VT, Custom);
428     setOperationAction(ISD::ADDE, VT, Custom);
429     setOperationAction(ISD::SUBC, VT, Custom);
430     setOperationAction(ISD::SUBE, VT, Custom);
431   }
432
433   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
434   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
435   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
442   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
443   if (Subtarget->is64Bit())
444     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
448   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
452   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
453
454   // Promote the i8 variants and force them on up to i32 which has a shorter
455   // encoding.
456   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
457   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
458   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
459   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
460   if (Subtarget->hasBMI()) {
461     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
463     if (Subtarget->is64Bit())
464       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
465   } else {
466     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
467     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
468     if (Subtarget->is64Bit())
469       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
470   }
471
472   if (Subtarget->hasLZCNT()) {
473     // When promoting the i8 variants, force them to i32 for a shorter
474     // encoding.
475     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
476     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
477     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
478     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
481     if (Subtarget->is64Bit())
482       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
483   } else {
484     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
485     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
490     if (Subtarget->is64Bit()) {
491       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
492       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
493     }
494   }
495
496   if (Subtarget->hasPOPCNT()) {
497     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
498   } else {
499     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
500     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
502     if (Subtarget->is64Bit())
503       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
504   }
505
506   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
507   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
508
509   // These should be promoted to a larger select which is supported.
510   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
511   // X86 wants to expand cmov itself.
512   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
513   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
524   if (Subtarget->is64Bit()) {
525     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
526     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
527   }
528   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
529   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
530   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
531   // support continuation, user-level threading, and etc.. As a result, no
532   // other SjLj exception interfaces are implemented and please don't build
533   // your own exception handling based on them.
534   // LLVM/Clang supports zero-cost DWARF exception handling.
535   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
536   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
537
538   // Darwin ABI issue.
539   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
540   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
541   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
542   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
543   if (Subtarget->is64Bit())
544     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
545   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
546   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
547   if (Subtarget->is64Bit()) {
548     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
549     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
550     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
551     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
552     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
553   }
554   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
555   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
556   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
557   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
558   if (Subtarget->is64Bit()) {
559     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
560     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
561     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
562   }
563
564   if (Subtarget->hasSSE1())
565     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
566
567   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
568
569   // Expand certain atomics
570   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
571     MVT VT = IntVTs[i];
572     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
573     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
574     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
575   }
576
577   if (!Subtarget->is64Bit()) {
578     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
590   }
591
592   if (Subtarget->hasCmpxchg16b()) {
593     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
594   }
595
596   // FIXME - use subtarget debug flags
597   if (!Subtarget->isTargetDarwin() &&
598       !Subtarget->isTargetELF() &&
599       !Subtarget->isTargetCygMing()) {
600     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
601   }
602
603   if (Subtarget->is64Bit()) {
604     setExceptionPointerRegister(X86::RAX);
605     setExceptionSelectorRegister(X86::RDX);
606   } else {
607     setExceptionPointerRegister(X86::EAX);
608     setExceptionSelectorRegister(X86::EDX);
609   }
610   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
611   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
612
613   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
614   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
615
616   setOperationAction(ISD::TRAP, MVT::Other, Legal);
617   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
618
619   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
620   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
621   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
622   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
623     // TargetInfo::X86_64ABIBuiltinVaList
624     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
625     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
626   } else {
627     // TargetInfo::CharPtrBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
630   }
631
632   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
633   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
634
635   if (Subtarget->isOSWindows() && !Subtarget->isTargetEnvMacho())
636     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
637                        MVT::i64 : MVT::i32, Custom);
638   else if (TM.Options.EnableSegmentedStacks)
639     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                        MVT::i64 : MVT::i32, Custom);
641   else
642     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643                        MVT::i64 : MVT::i32, Expand);
644
645   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
646     // f32 and f64 use SSE.
647     // Set up the FP register classes.
648     addRegisterClass(MVT::f32, &X86::FR32RegClass);
649     addRegisterClass(MVT::f64, &X86::FR64RegClass);
650
651     // Use ANDPD to simulate FABS.
652     setOperationAction(ISD::FABS , MVT::f64, Custom);
653     setOperationAction(ISD::FABS , MVT::f32, Custom);
654
655     // Use XORP to simulate FNEG.
656     setOperationAction(ISD::FNEG , MVT::f64, Custom);
657     setOperationAction(ISD::FNEG , MVT::f32, Custom);
658
659     // Use ANDPD and ORPD to simulate FCOPYSIGN.
660     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
661     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662
663     // Lower this to FGETSIGNx86 plus an AND.
664     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
665     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
666
667     // We don't support sin/cos/fmod
668     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
669     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
670     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
671     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
672     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
673     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674
675     // Expand FP immediates into loads from the stack, except for the special
676     // cases we handle.
677     addLegalFPImmediate(APFloat(+0.0)); // xorpd
678     addLegalFPImmediate(APFloat(+0.0f)); // xorps
679   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
680     // Use SSE for f32, x87 for f64.
681     // Set up the FP register classes.
682     addRegisterClass(MVT::f32, &X86::FR32RegClass);
683     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
684
685     // Use ANDPS to simulate FABS.
686     setOperationAction(ISD::FABS , MVT::f32, Custom);
687
688     // Use XORP to simulate FNEG.
689     setOperationAction(ISD::FNEG , MVT::f32, Custom);
690
691     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
692
693     // Use ANDPS and ORPS to simulate FCOPYSIGN.
694     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
695     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
696
697     // We don't support sin/cos/fmod
698     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
699     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
700     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701
702     // Special cases we handle for FP constants.
703     addLegalFPImmediate(APFloat(+0.0f)); // xorps
704     addLegalFPImmediate(APFloat(+0.0)); // FLD0
705     addLegalFPImmediate(APFloat(+1.0)); // FLD1
706     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
707     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708
709     if (!TM.Options.UnsafeFPMath) {
710       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
711       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
712       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
713     }
714   } else if (!TM.Options.UseSoftFloat) {
715     // f32 and f64 in x87.
716     // Set up the FP register classes.
717     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
718     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
719
720     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
721     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
723     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
724
725     if (!TM.Options.UnsafeFPMath) {
726       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
727       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
729       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
732     }
733     addLegalFPImmediate(APFloat(+0.0)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
737     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
738     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
739     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
740     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
741   }
742
743   // We don't support FMA.
744   setOperationAction(ISD::FMA, MVT::f64, Expand);
745   setOperationAction(ISD::FMA, MVT::f32, Expand);
746
747   // Long double always uses X87.
748   if (!TM.Options.UseSoftFloat) {
749     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
750     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
751     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
752     {
753       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
754       addLegalFPImmediate(TmpFlt);  // FLD0
755       TmpFlt.changeSign();
756       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
757
758       bool ignored;
759       APFloat TmpFlt2(+1.0);
760       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
761                       &ignored);
762       addLegalFPImmediate(TmpFlt2);  // FLD1
763       TmpFlt2.changeSign();
764       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
765     }
766
767     if (!TM.Options.UnsafeFPMath) {
768       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
769       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
770       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
771     }
772
773     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
774     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
775     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
776     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
777     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
778     setOperationAction(ISD::FMA, MVT::f80, Expand);
779   }
780
781   // Always use a library call for pow.
782   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
784   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
785
786   setOperationAction(ISD::FLOG, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
788   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP, MVT::f80, Expand);
790   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
791
792   // First set operation action for all vector types to either promote
793   // (for widening) or expand (for scalarization). Then we will selectively
794   // turn on ones that can be effectively codegen'd.
795   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
796            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
797     MVT VT = (MVT::SimpleValueType)i;
798     setOperationAction(ISD::ADD , VT, Expand);
799     setOperationAction(ISD::SUB , VT, Expand);
800     setOperationAction(ISD::FADD, VT, Expand);
801     setOperationAction(ISD::FNEG, VT, Expand);
802     setOperationAction(ISD::FSUB, VT, Expand);
803     setOperationAction(ISD::MUL , VT, Expand);
804     setOperationAction(ISD::FMUL, VT, Expand);
805     setOperationAction(ISD::SDIV, VT, Expand);
806     setOperationAction(ISD::UDIV, VT, Expand);
807     setOperationAction(ISD::FDIV, VT, Expand);
808     setOperationAction(ISD::SREM, VT, Expand);
809     setOperationAction(ISD::UREM, VT, Expand);
810     setOperationAction(ISD::LOAD, VT, Expand);
811     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
812     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
813     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
814     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
816     setOperationAction(ISD::FABS, VT, Expand);
817     setOperationAction(ISD::FSIN, VT, Expand);
818     setOperationAction(ISD::FSINCOS, VT, Expand);
819     setOperationAction(ISD::FCOS, VT, Expand);
820     setOperationAction(ISD::FSINCOS, VT, Expand);
821     setOperationAction(ISD::FREM, VT, Expand);
822     setOperationAction(ISD::FMA,  VT, Expand);
823     setOperationAction(ISD::FPOWI, VT, Expand);
824     setOperationAction(ISD::FSQRT, VT, Expand);
825     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
826     setOperationAction(ISD::FFLOOR, VT, Expand);
827     setOperationAction(ISD::FCEIL, VT, Expand);
828     setOperationAction(ISD::FTRUNC, VT, Expand);
829     setOperationAction(ISD::FRINT, VT, Expand);
830     setOperationAction(ISD::FNEARBYINT, VT, Expand);
831     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::SDIVREM, VT, Expand);
834     setOperationAction(ISD::UDIVREM, VT, Expand);
835     setOperationAction(ISD::FPOW, VT, Expand);
836     setOperationAction(ISD::CTPOP, VT, Expand);
837     setOperationAction(ISD::CTTZ, VT, Expand);
838     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::CTLZ, VT, Expand);
840     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
841     setOperationAction(ISD::SHL, VT, Expand);
842     setOperationAction(ISD::SRA, VT, Expand);
843     setOperationAction(ISD::SRL, VT, Expand);
844     setOperationAction(ISD::ROTL, VT, Expand);
845     setOperationAction(ISD::ROTR, VT, Expand);
846     setOperationAction(ISD::BSWAP, VT, Expand);
847     setOperationAction(ISD::SETCC, VT, Expand);
848     setOperationAction(ISD::FLOG, VT, Expand);
849     setOperationAction(ISD::FLOG2, VT, Expand);
850     setOperationAction(ISD::FLOG10, VT, Expand);
851     setOperationAction(ISD::FEXP, VT, Expand);
852     setOperationAction(ISD::FEXP2, VT, Expand);
853     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
854     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
855     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
858     setOperationAction(ISD::TRUNCATE, VT, Expand);
859     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
860     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
861     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
862     setOperationAction(ISD::VSELECT, VT, Expand);
863     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
864              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
865       setTruncStoreAction(VT,
866                           (MVT::SimpleValueType)InnerVT, Expand);
867     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
870   }
871
872   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
873   // with -msoft-float, disable use of MMX as well.
874   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
875     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
876     // No operations on x86mmx supported, everything uses intrinsics.
877   }
878
879   // MMX-sized vectors (other than x86mmx) are expected to be expanded
880   // into smaller operations.
881   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
882   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
885   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
886   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
887   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
888   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
889   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
890   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
891   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
892   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
893   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
894   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
895   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
896   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
901   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
903   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
910
911   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
912     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913
914     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
919     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
920     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
921     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
922     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
923     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
924     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
925     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
926   }
927
928   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
929     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930
931     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
932     // registers cannot be used even for integer operations.
933     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
934     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
935     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
936     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937
938     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
939     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
940     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
941     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
942     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
943     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
944     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
945     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
947     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
948     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
949     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
954     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
955     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
956
957     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
961
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
963     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
967
968     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
969     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
970       MVT VT = (MVT::SimpleValueType)i;
971       // Do not attempt to custom lower non-power-of-2 vectors
972       if (!isPowerOf2_32(VT.getVectorNumElements()))
973         continue;
974       // Do not attempt to custom lower non-128-bit vectors
975       if (!VT.is128BitVector())
976         continue;
977       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
978       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
979       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
980     }
981
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
983     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
985     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
988
989     if (Subtarget->is64Bit()) {
990       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
991       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
992     }
993
994     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
995     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996       MVT VT = (MVT::SimpleValueType)i;
997
998       // Do not attempt to promote non-128-bit vectors
999       if (!VT.is128BitVector())
1000         continue;
1001
1002       setOperationAction(ISD::AND,    VT, Promote);
1003       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1004       setOperationAction(ISD::OR,     VT, Promote);
1005       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1006       setOperationAction(ISD::XOR,    VT, Promote);
1007       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1008       setOperationAction(ISD::LOAD,   VT, Promote);
1009       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1010       setOperationAction(ISD::SELECT, VT, Promote);
1011       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1012     }
1013
1014     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1015
1016     // Custom lower v2i64 and v2f64 selects.
1017     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1019     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1020     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1021
1022     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1023     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1024
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1026     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1027     // As there is no 64-bit GPR available, we need build a special custom
1028     // sequence to convert from v2i32 to v2f32.
1029     if (!Subtarget->is64Bit())
1030       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1031
1032     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1033     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1034
1035     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1036   }
1037
1038   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1039     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1040     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1041     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1042     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1043     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1047     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1049
1050     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1051     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1052     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1053     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1054     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1055     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1056     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1057     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1058     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1059     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1060
1061     // FIXME: Do we need to handle scalar-to-vector here?
1062     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1063
1064     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1069
1070     // i8 and i16 vectors are custom , because the source register and source
1071     // source memory operand types are not the same width.  f32 vectors are
1072     // custom since the immediate controlling the insert encodes additional
1073     // information.
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1078
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1083
1084     // FIXME: these should be Legal but thats only for the case where
1085     // the index is constant.  For now custom expand to deal with that.
1086     if (Subtarget->is64Bit()) {
1087       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1088       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089     }
1090   }
1091
1092   if (Subtarget->hasSSE2()) {
1093     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1101
1102     // In the customized shift lowering, the legal cases in AVX2 will be
1103     // recognized.
1104     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1105     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1106
1107     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1111
1112     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1113     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1114   }
1115
1116   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1123
1124     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1126     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1127
1128     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1133     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1134     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1135     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1136     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1138     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1139     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1140
1141     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1146     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1147     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1148     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1149     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1151     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1152     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1153
1154     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1155
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1157     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1160
1161     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1162     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1163
1164     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1165
1166     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1167     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1168
1169     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1176
1177     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1181
1182     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1183     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1185
1186     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1190
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1203
1204     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1209       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1211     }
1212
1213     if (Subtarget->hasInt256()) {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1227       // Don't lower v32i8 because there is no 128-bit byte mul
1228
1229       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1232     } else {
1233       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1236       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1237
1238       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1241       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1242
1243       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1244       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1245       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1246       // Don't lower v32i8 because there is no 128-bit byte mul
1247     }
1248
1249     // In the customized shift lowering, the legal cases in AVX2 will be
1250     // recognized.
1251     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1255     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1256
1257     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1258
1259     // Custom lower several nodes for 256-bit types.
1260     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262       MVT VT = (MVT::SimpleValueType)i;
1263
1264       // Extract subvector is special because the value type
1265       // (result) is 128-bit but the source is 256-bit wide.
1266       if (VT.is128BitVector())
1267         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1268
1269       // Do not attempt to custom lower other non-256-bit vectors
1270       if (!VT.is256BitVector())
1271         continue;
1272
1273       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1274       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1275       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1276       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1278       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1279       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1280     }
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1310     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1311
1312     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1315     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1316     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1317     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1318
1319     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1321     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1322     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1323     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1324     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1325
1326     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1328     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1329     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1330     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1331     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1332     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1333     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1334     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1335
1336     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1340     if (Subtarget->is64Bit()) {
1341       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1342       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1343       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1344       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1345     }
1346     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1347     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1349     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1350     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1352     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1353     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1354
1355     setOperationAction(ISD::TRUNCATE,           MVT::i1, Legal);
1356     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1357     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1358     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1359     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1360     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1361     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1362     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1363     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1364     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1365     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1367
1368     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1369     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1370     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1371     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1372     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1373
1374     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1375     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1376
1377     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1378
1379     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1380     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1381     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1382     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1383     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1384
1385     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1386     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1387
1388     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1389     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1390
1391     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1392
1393     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1394     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1395
1396     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1397     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1398
1399     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1400     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1401
1402     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1403     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1404     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1405     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1406     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1407     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1408
1409     // Custom lower several nodes.
1410     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1411              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1412       MVT VT = (MVT::SimpleValueType)i;
1413
1414       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1415       // Extract subvector is special because the value type
1416       // (result) is 256/128-bit but the source is 512-bit wide.
1417       if (VT.is128BitVector() || VT.is256BitVector())
1418         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1419
1420       if (VT.getVectorElementType() == MVT::i1)
1421         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1422
1423       // Do not attempt to custom lower other non-512-bit vectors
1424       if (!VT.is512BitVector())
1425         continue;
1426
1427       if ( EltSize >= 32) {
1428         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1429         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1430         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1431         setOperationAction(ISD::VSELECT,             VT, Legal);
1432         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1433         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1434         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1435       }
1436     }
1437     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1438       MVT VT = (MVT::SimpleValueType)i;
1439
1440       // Do not attempt to promote non-256-bit vectors
1441       if (!VT.is512BitVector())
1442         continue;
1443
1444       setOperationAction(ISD::SELECT, VT, Promote);
1445       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1446     }
1447   }// has  AVX-512
1448
1449   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1450   // of this type with custom code.
1451   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1452            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1453     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1454                        Custom);
1455   }
1456
1457   // We want to custom lower some of our intrinsics.
1458   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1459   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1460   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1461
1462   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1463   // handle type legalization for these operations here.
1464   //
1465   // FIXME: We really should do custom legalization for addition and
1466   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1467   // than generic legalization for 64-bit multiplication-with-overflow, though.
1468   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1469     // Add/Sub/Mul with overflow operations are custom lowered.
1470     MVT VT = IntVTs[i];
1471     setOperationAction(ISD::SADDO, VT, Custom);
1472     setOperationAction(ISD::UADDO, VT, Custom);
1473     setOperationAction(ISD::SSUBO, VT, Custom);
1474     setOperationAction(ISD::USUBO, VT, Custom);
1475     setOperationAction(ISD::SMULO, VT, Custom);
1476     setOperationAction(ISD::UMULO, VT, Custom);
1477   }
1478
1479   // There are no 8-bit 3-address imul/mul instructions
1480   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1481   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1482
1483   if (!Subtarget->is64Bit()) {
1484     // These libcalls are not available in 32-bit.
1485     setLibcallName(RTLIB::SHL_I128, 0);
1486     setLibcallName(RTLIB::SRL_I128, 0);
1487     setLibcallName(RTLIB::SRA_I128, 0);
1488   }
1489
1490   // Combine sin / cos into one node or libcall if possible.
1491   if (Subtarget->hasSinCos()) {
1492     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1493     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1494     if (Subtarget->isTargetDarwin()) {
1495       // For MacOSX, we don't want to the normal expansion of a libcall to
1496       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1497       // traffic.
1498       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1499       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1500     }
1501   }
1502
1503   // We have target-specific dag combine patterns for the following nodes:
1504   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1505   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1506   setTargetDAGCombine(ISD::VSELECT);
1507   setTargetDAGCombine(ISD::SELECT);
1508   setTargetDAGCombine(ISD::SHL);
1509   setTargetDAGCombine(ISD::SRA);
1510   setTargetDAGCombine(ISD::SRL);
1511   setTargetDAGCombine(ISD::OR);
1512   setTargetDAGCombine(ISD::AND);
1513   setTargetDAGCombine(ISD::ADD);
1514   setTargetDAGCombine(ISD::FADD);
1515   setTargetDAGCombine(ISD::FSUB);
1516   setTargetDAGCombine(ISD::FMA);
1517   setTargetDAGCombine(ISD::SUB);
1518   setTargetDAGCombine(ISD::LOAD);
1519   setTargetDAGCombine(ISD::STORE);
1520   setTargetDAGCombine(ISD::ZERO_EXTEND);
1521   setTargetDAGCombine(ISD::ANY_EXTEND);
1522   setTargetDAGCombine(ISD::SIGN_EXTEND);
1523   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1524   setTargetDAGCombine(ISD::TRUNCATE);
1525   setTargetDAGCombine(ISD::SINT_TO_FP);
1526   setTargetDAGCombine(ISD::SETCC);
1527   if (Subtarget->is64Bit())
1528     setTargetDAGCombine(ISD::MUL);
1529   setTargetDAGCombine(ISD::XOR);
1530
1531   computeRegisterProperties();
1532
1533   // On Darwin, -Os means optimize for size without hurting performance,
1534   // do not reduce the limit.
1535   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1536   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1537   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1538   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1539   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1540   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1541   setPrefLoopAlignment(4); // 2^4 bytes.
1542
1543   // Predictable cmov don't hurt on atom because it's in-order.
1544   PredictableSelectIsExpensive = !Subtarget->isAtom();
1545
1546   setPrefFunctionAlignment(4); // 2^4 bytes.
1547 }
1548
1549 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1550   if (!VT.isVector())
1551     return MVT::i8;
1552
1553   const TargetMachine &TM = getTargetMachine();
1554   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512())
1555     switch(VT.getVectorNumElements()) {
1556     case  8: return MVT::v8i1;
1557     case 16: return MVT::v16i1;
1558     }
1559
1560   return VT.changeVectorElementTypeToInteger();
1561 }
1562
1563 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1564 /// the desired ByVal argument alignment.
1565 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1566   if (MaxAlign == 16)
1567     return;
1568   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1569     if (VTy->getBitWidth() == 128)
1570       MaxAlign = 16;
1571   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1572     unsigned EltAlign = 0;
1573     getMaxByValAlign(ATy->getElementType(), EltAlign);
1574     if (EltAlign > MaxAlign)
1575       MaxAlign = EltAlign;
1576   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1577     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1578       unsigned EltAlign = 0;
1579       getMaxByValAlign(STy->getElementType(i), EltAlign);
1580       if (EltAlign > MaxAlign)
1581         MaxAlign = EltAlign;
1582       if (MaxAlign == 16)
1583         break;
1584     }
1585   }
1586 }
1587
1588 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1589 /// function arguments in the caller parameter area. For X86, aggregates
1590 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1591 /// are at 4-byte boundaries.
1592 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1593   if (Subtarget->is64Bit()) {
1594     // Max of 8 and alignment of type.
1595     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1596     if (TyAlign > 8)
1597       return TyAlign;
1598     return 8;
1599   }
1600
1601   unsigned Align = 4;
1602   if (Subtarget->hasSSE1())
1603     getMaxByValAlign(Ty, Align);
1604   return Align;
1605 }
1606
1607 /// getOptimalMemOpType - Returns the target specific optimal type for load
1608 /// and store operations as a result of memset, memcpy, and memmove
1609 /// lowering. If DstAlign is zero that means it's safe to destination
1610 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1611 /// means there isn't a need to check it against alignment requirement,
1612 /// probably because the source does not need to be loaded. If 'IsMemset' is
1613 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1614 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1615 /// source is constant so it does not need to be loaded.
1616 /// It returns EVT::Other if the type should be determined using generic
1617 /// target-independent logic.
1618 EVT
1619 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1620                                        unsigned DstAlign, unsigned SrcAlign,
1621                                        bool IsMemset, bool ZeroMemset,
1622                                        bool MemcpyStrSrc,
1623                                        MachineFunction &MF) const {
1624   const Function *F = MF.getFunction();
1625   if ((!IsMemset || ZeroMemset) &&
1626       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1627                                        Attribute::NoImplicitFloat)) {
1628     if (Size >= 16 &&
1629         (Subtarget->isUnalignedMemAccessFast() ||
1630          ((DstAlign == 0 || DstAlign >= 16) &&
1631           (SrcAlign == 0 || SrcAlign >= 16)))) {
1632       if (Size >= 32) {
1633         if (Subtarget->hasInt256())
1634           return MVT::v8i32;
1635         if (Subtarget->hasFp256())
1636           return MVT::v8f32;
1637       }
1638       if (Subtarget->hasSSE2())
1639         return MVT::v4i32;
1640       if (Subtarget->hasSSE1())
1641         return MVT::v4f32;
1642     } else if (!MemcpyStrSrc && Size >= 8 &&
1643                !Subtarget->is64Bit() &&
1644                Subtarget->hasSSE2()) {
1645       // Do not use f64 to lower memcpy if source is string constant. It's
1646       // better to use i32 to avoid the loads.
1647       return MVT::f64;
1648     }
1649   }
1650   if (Subtarget->is64Bit() && Size >= 8)
1651     return MVT::i64;
1652   return MVT::i32;
1653 }
1654
1655 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1656   if (VT == MVT::f32)
1657     return X86ScalarSSEf32;
1658   else if (VT == MVT::f64)
1659     return X86ScalarSSEf64;
1660   return true;
1661 }
1662
1663 bool
1664 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1665   if (Fast)
1666     *Fast = Subtarget->isUnalignedMemAccessFast();
1667   return true;
1668 }
1669
1670 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1671 /// current function.  The returned value is a member of the
1672 /// MachineJumpTableInfo::JTEntryKind enum.
1673 unsigned X86TargetLowering::getJumpTableEncoding() const {
1674   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1675   // symbol.
1676   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1677       Subtarget->isPICStyleGOT())
1678     return MachineJumpTableInfo::EK_Custom32;
1679
1680   // Otherwise, use the normal jump table encoding heuristics.
1681   return TargetLowering::getJumpTableEncoding();
1682 }
1683
1684 const MCExpr *
1685 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1686                                              const MachineBasicBlock *MBB,
1687                                              unsigned uid,MCContext &Ctx) const{
1688   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1689          Subtarget->isPICStyleGOT());
1690   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1691   // entries.
1692   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1693                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1694 }
1695
1696 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1697 /// jumptable.
1698 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1699                                                     SelectionDAG &DAG) const {
1700   if (!Subtarget->is64Bit())
1701     // This doesn't have SDLoc associated with it, but is not really the
1702     // same as a Register.
1703     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1704   return Table;
1705 }
1706
1707 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1708 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1709 /// MCExpr.
1710 const MCExpr *X86TargetLowering::
1711 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1712                              MCContext &Ctx) const {
1713   // X86-64 uses RIP relative addressing based on the jump table label.
1714   if (Subtarget->isPICStyleRIPRel())
1715     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1716
1717   // Otherwise, the reference is relative to the PIC base.
1718   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1719 }
1720
1721 // FIXME: Why this routine is here? Move to RegInfo!
1722 std::pair<const TargetRegisterClass*, uint8_t>
1723 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1724   const TargetRegisterClass *RRC = 0;
1725   uint8_t Cost = 1;
1726   switch (VT.SimpleTy) {
1727   default:
1728     return TargetLowering::findRepresentativeClass(VT);
1729   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1730     RRC = Subtarget->is64Bit() ?
1731       (const TargetRegisterClass*)&X86::GR64RegClass :
1732       (const TargetRegisterClass*)&X86::GR32RegClass;
1733     break;
1734   case MVT::x86mmx:
1735     RRC = &X86::VR64RegClass;
1736     break;
1737   case MVT::f32: case MVT::f64:
1738   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1739   case MVT::v4f32: case MVT::v2f64:
1740   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1741   case MVT::v4f64:
1742     RRC = &X86::VR128RegClass;
1743     break;
1744   }
1745   return std::make_pair(RRC, Cost);
1746 }
1747
1748 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1749                                                unsigned &Offset) const {
1750   if (!Subtarget->isTargetLinux())
1751     return false;
1752
1753   if (Subtarget->is64Bit()) {
1754     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1755     Offset = 0x28;
1756     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1757       AddressSpace = 256;
1758     else
1759       AddressSpace = 257;
1760   } else {
1761     // %gs:0x14 on i386
1762     Offset = 0x14;
1763     AddressSpace = 256;
1764   }
1765   return true;
1766 }
1767
1768 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1769                                             unsigned DestAS) const {
1770   assert(SrcAS != DestAS && "Expected different address spaces!");
1771
1772   return SrcAS < 256 && DestAS < 256;
1773 }
1774
1775 //===----------------------------------------------------------------------===//
1776 //               Return Value Calling Convention Implementation
1777 //===----------------------------------------------------------------------===//
1778
1779 #include "X86GenCallingConv.inc"
1780
1781 bool
1782 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1783                                   MachineFunction &MF, bool isVarArg,
1784                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1785                         LLVMContext &Context) const {
1786   SmallVector<CCValAssign, 16> RVLocs;
1787   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1788                  RVLocs, Context);
1789   return CCInfo.CheckReturn(Outs, RetCC_X86);
1790 }
1791
1792 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1793   static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1794   return ScratchRegs;
1795 }
1796
1797 SDValue
1798 X86TargetLowering::LowerReturn(SDValue Chain,
1799                                CallingConv::ID CallConv, bool isVarArg,
1800                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1801                                const SmallVectorImpl<SDValue> &OutVals,
1802                                SDLoc dl, SelectionDAG &DAG) const {
1803   MachineFunction &MF = DAG.getMachineFunction();
1804   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1805
1806   SmallVector<CCValAssign, 16> RVLocs;
1807   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1808                  RVLocs, *DAG.getContext());
1809   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1810
1811   SDValue Flag;
1812   SmallVector<SDValue, 6> RetOps;
1813   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1814   // Operand #1 = Bytes To Pop
1815   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1816                    MVT::i16));
1817
1818   // Copy the result values into the output registers.
1819   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1820     CCValAssign &VA = RVLocs[i];
1821     assert(VA.isRegLoc() && "Can only return in registers!");
1822     SDValue ValToCopy = OutVals[i];
1823     EVT ValVT = ValToCopy.getValueType();
1824
1825     // Promote values to the appropriate types
1826     if (VA.getLocInfo() == CCValAssign::SExt)
1827       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1828     else if (VA.getLocInfo() == CCValAssign::ZExt)
1829       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1830     else if (VA.getLocInfo() == CCValAssign::AExt)
1831       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1832     else if (VA.getLocInfo() == CCValAssign::BCvt)
1833       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1834
1835     // If this is x86-64, and we disabled SSE, we can't return FP values,
1836     // or SSE or MMX vectors.
1837     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1838          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1839           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1840       report_fatal_error("SSE register return with SSE disabled");
1841     }
1842     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1843     // llvm-gcc has never done it right and no one has noticed, so this
1844     // should be OK for now.
1845     if (ValVT == MVT::f64 &&
1846         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1847       report_fatal_error("SSE2 register return with SSE2 disabled");
1848
1849     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1850     // the RET instruction and handled by the FP Stackifier.
1851     if (VA.getLocReg() == X86::ST0 ||
1852         VA.getLocReg() == X86::ST1) {
1853       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1854       // change the value to the FP stack register class.
1855       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1856         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1857       RetOps.push_back(ValToCopy);
1858       // Don't emit a copytoreg.
1859       continue;
1860     }
1861
1862     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1863     // which is returned in RAX / RDX.
1864     if (Subtarget->is64Bit()) {
1865       if (ValVT == MVT::x86mmx) {
1866         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1867           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1868           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1869                                   ValToCopy);
1870           // If we don't have SSE2 available, convert to v4f32 so the generated
1871           // register is legal.
1872           if (!Subtarget->hasSSE2())
1873             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1874         }
1875       }
1876     }
1877
1878     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1879     Flag = Chain.getValue(1);
1880     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1881   }
1882
1883   // The x86-64 ABIs require that for returning structs by value we copy
1884   // the sret argument into %rax/%eax (depending on ABI) for the return.
1885   // Win32 requires us to put the sret argument to %eax as well.
1886   // We saved the argument into a virtual register in the entry block,
1887   // so now we copy the value out and into %rax/%eax.
1888   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1889       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1890     MachineFunction &MF = DAG.getMachineFunction();
1891     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1892     unsigned Reg = FuncInfo->getSRetReturnReg();
1893     assert(Reg &&
1894            "SRetReturnReg should have been set in LowerFormalArguments().");
1895     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1896
1897     unsigned RetValReg
1898         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1899           X86::RAX : X86::EAX;
1900     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1901     Flag = Chain.getValue(1);
1902
1903     // RAX/EAX now acts like a return value.
1904     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1905   }
1906
1907   RetOps[0] = Chain;  // Update chain.
1908
1909   // Add the flag if we have it.
1910   if (Flag.getNode())
1911     RetOps.push_back(Flag);
1912
1913   return DAG.getNode(X86ISD::RET_FLAG, dl,
1914                      MVT::Other, &RetOps[0], RetOps.size());
1915 }
1916
1917 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1918   if (N->getNumValues() != 1)
1919     return false;
1920   if (!N->hasNUsesOfValue(1, 0))
1921     return false;
1922
1923   SDValue TCChain = Chain;
1924   SDNode *Copy = *N->use_begin();
1925   if (Copy->getOpcode() == ISD::CopyToReg) {
1926     // If the copy has a glue operand, we conservatively assume it isn't safe to
1927     // perform a tail call.
1928     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1929       return false;
1930     TCChain = Copy->getOperand(0);
1931   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1932     return false;
1933
1934   bool HasRet = false;
1935   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1936        UI != UE; ++UI) {
1937     if (UI->getOpcode() != X86ISD::RET_FLAG)
1938       return false;
1939     HasRet = true;
1940   }
1941
1942   if (!HasRet)
1943     return false;
1944
1945   Chain = TCChain;
1946   return true;
1947 }
1948
1949 MVT
1950 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1951                                             ISD::NodeType ExtendKind) const {
1952   MVT ReturnMVT;
1953   // TODO: Is this also valid on 32-bit?
1954   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1955     ReturnMVT = MVT::i8;
1956   else
1957     ReturnMVT = MVT::i32;
1958
1959   MVT MinVT = getRegisterType(ReturnMVT);
1960   return VT.bitsLT(MinVT) ? MinVT : VT;
1961 }
1962
1963 /// LowerCallResult - Lower the result values of a call into the
1964 /// appropriate copies out of appropriate physical registers.
1965 ///
1966 SDValue
1967 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1968                                    CallingConv::ID CallConv, bool isVarArg,
1969                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1970                                    SDLoc dl, SelectionDAG &DAG,
1971                                    SmallVectorImpl<SDValue> &InVals) const {
1972
1973   // Assign locations to each value returned by this call.
1974   SmallVector<CCValAssign, 16> RVLocs;
1975   bool Is64Bit = Subtarget->is64Bit();
1976   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1977                  getTargetMachine(), RVLocs, *DAG.getContext());
1978   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1979
1980   // Copy all of the result registers out of their specified physreg.
1981   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1982     CCValAssign &VA = RVLocs[i];
1983     EVT CopyVT = VA.getValVT();
1984
1985     // If this is x86-64, and we disabled SSE, we can't return FP values
1986     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1987         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1988       report_fatal_error("SSE register return with SSE disabled");
1989     }
1990
1991     SDValue Val;
1992
1993     // If this is a call to a function that returns an fp value on the floating
1994     // point stack, we must guarantee the value is popped from the stack, so
1995     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1996     // if the return value is not used. We use the FpPOP_RETVAL instruction
1997     // instead.
1998     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1999       // If we prefer to use the value in xmm registers, copy it out as f80 and
2000       // use a truncate to move it from fp stack reg to xmm reg.
2001       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2002       SDValue Ops[] = { Chain, InFlag };
2003       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2004                                          MVT::Other, MVT::Glue, Ops), 1);
2005       Val = Chain.getValue(0);
2006
2007       // Round the f80 to the right size, which also moves it to the appropriate
2008       // xmm register.
2009       if (CopyVT != VA.getValVT())
2010         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2011                           // This truncation won't change the value.
2012                           DAG.getIntPtrConstant(1));
2013     } else {
2014       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2015                                  CopyVT, InFlag).getValue(1);
2016       Val = Chain.getValue(0);
2017     }
2018     InFlag = Chain.getValue(2);
2019     InVals.push_back(Val);
2020   }
2021
2022   return Chain;
2023 }
2024
2025 //===----------------------------------------------------------------------===//
2026 //                C & StdCall & Fast Calling Convention implementation
2027 //===----------------------------------------------------------------------===//
2028 //  StdCall calling convention seems to be standard for many Windows' API
2029 //  routines and around. It differs from C calling convention just a little:
2030 //  callee should clean up the stack, not caller. Symbols should be also
2031 //  decorated in some fancy way :) It doesn't support any vector arguments.
2032 //  For info on fast calling convention see Fast Calling Convention (tail call)
2033 //  implementation LowerX86_32FastCCCallTo.
2034
2035 /// CallIsStructReturn - Determines whether a call uses struct return
2036 /// semantics.
2037 enum StructReturnType {
2038   NotStructReturn,
2039   RegStructReturn,
2040   StackStructReturn
2041 };
2042 static StructReturnType
2043 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2044   if (Outs.empty())
2045     return NotStructReturn;
2046
2047   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2048   if (!Flags.isSRet())
2049     return NotStructReturn;
2050   if (Flags.isInReg())
2051     return RegStructReturn;
2052   return StackStructReturn;
2053 }
2054
2055 /// ArgsAreStructReturn - Determines whether a function uses struct
2056 /// return semantics.
2057 static StructReturnType
2058 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2059   if (Ins.empty())
2060     return NotStructReturn;
2061
2062   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2063   if (!Flags.isSRet())
2064     return NotStructReturn;
2065   if (Flags.isInReg())
2066     return RegStructReturn;
2067   return StackStructReturn;
2068 }
2069
2070 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2071 /// by "Src" to address "Dst" with size and alignment information specified by
2072 /// the specific parameter attribute. The copy will be passed as a byval
2073 /// function parameter.
2074 static SDValue
2075 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2076                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2077                           SDLoc dl) {
2078   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2079
2080   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2081                        /*isVolatile*/false, /*AlwaysInline=*/true,
2082                        MachinePointerInfo(), MachinePointerInfo());
2083 }
2084
2085 /// IsTailCallConvention - Return true if the calling convention is one that
2086 /// supports tail call optimization.
2087 static bool IsTailCallConvention(CallingConv::ID CC) {
2088   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2089           CC == CallingConv::HiPE);
2090 }
2091
2092 /// \brief Return true if the calling convention is a C calling convention.
2093 static bool IsCCallConvention(CallingConv::ID CC) {
2094   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2095           CC == CallingConv::X86_64_SysV);
2096 }
2097
2098 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2099   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2100     return false;
2101
2102   CallSite CS(CI);
2103   CallingConv::ID CalleeCC = CS.getCallingConv();
2104   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2105     return false;
2106
2107   return true;
2108 }
2109
2110 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2111 /// a tailcall target by changing its ABI.
2112 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2113                                    bool GuaranteedTailCallOpt) {
2114   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2115 }
2116
2117 SDValue
2118 X86TargetLowering::LowerMemArgument(SDValue Chain,
2119                                     CallingConv::ID CallConv,
2120                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2121                                     SDLoc dl, SelectionDAG &DAG,
2122                                     const CCValAssign &VA,
2123                                     MachineFrameInfo *MFI,
2124                                     unsigned i) const {
2125   // Create the nodes corresponding to a load from this parameter slot.
2126   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2127   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2128                               getTargetMachine().Options.GuaranteedTailCallOpt);
2129   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2130   EVT ValVT;
2131
2132   // If value is passed by pointer we have address passed instead of the value
2133   // itself.
2134   if (VA.getLocInfo() == CCValAssign::Indirect)
2135     ValVT = VA.getLocVT();
2136   else
2137     ValVT = VA.getValVT();
2138
2139   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2140   // changed with more analysis.
2141   // In case of tail call optimization mark all arguments mutable. Since they
2142   // could be overwritten by lowering of arguments in case of a tail call.
2143   if (Flags.isByVal()) {
2144     unsigned Bytes = Flags.getByValSize();
2145     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2146     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2147     return DAG.getFrameIndex(FI, getPointerTy());
2148   } else {
2149     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2150                                     VA.getLocMemOffset(), isImmutable);
2151     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2152     return DAG.getLoad(ValVT, dl, Chain, FIN,
2153                        MachinePointerInfo::getFixedStack(FI),
2154                        false, false, false, 0);
2155   }
2156 }
2157
2158 SDValue
2159 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2160                                         CallingConv::ID CallConv,
2161                                         bool isVarArg,
2162                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2163                                         SDLoc dl,
2164                                         SelectionDAG &DAG,
2165                                         SmallVectorImpl<SDValue> &InVals)
2166                                           const {
2167   MachineFunction &MF = DAG.getMachineFunction();
2168   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2169
2170   const Function* Fn = MF.getFunction();
2171   if (Fn->hasExternalLinkage() &&
2172       Subtarget->isTargetCygMing() &&
2173       Fn->getName() == "main")
2174     FuncInfo->setForceFramePointer(true);
2175
2176   MachineFrameInfo *MFI = MF.getFrameInfo();
2177   bool Is64Bit = Subtarget->is64Bit();
2178   bool IsWindows = Subtarget->isTargetWindows();
2179   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2180
2181   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2182          "Var args not supported with calling convention fastcc, ghc or hipe");
2183
2184   // Assign locations to all of the incoming arguments.
2185   SmallVector<CCValAssign, 16> ArgLocs;
2186   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2187                  ArgLocs, *DAG.getContext());
2188
2189   // Allocate shadow area for Win64
2190   if (IsWin64)
2191     CCInfo.AllocateStack(32, 8);
2192
2193   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2194
2195   unsigned LastVal = ~0U;
2196   SDValue ArgValue;
2197   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2198     CCValAssign &VA = ArgLocs[i];
2199     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2200     // places.
2201     assert(VA.getValNo() != LastVal &&
2202            "Don't support value assigned to multiple locs yet");
2203     (void)LastVal;
2204     LastVal = VA.getValNo();
2205
2206     if (VA.isRegLoc()) {
2207       EVT RegVT = VA.getLocVT();
2208       const TargetRegisterClass *RC;
2209       if (RegVT == MVT::i32)
2210         RC = &X86::GR32RegClass;
2211       else if (Is64Bit && RegVT == MVT::i64)
2212         RC = &X86::GR64RegClass;
2213       else if (RegVT == MVT::f32)
2214         RC = &X86::FR32RegClass;
2215       else if (RegVT == MVT::f64)
2216         RC = &X86::FR64RegClass;
2217       else if (RegVT.is512BitVector())
2218         RC = &X86::VR512RegClass;
2219       else if (RegVT.is256BitVector())
2220         RC = &X86::VR256RegClass;
2221       else if (RegVT.is128BitVector())
2222         RC = &X86::VR128RegClass;
2223       else if (RegVT == MVT::x86mmx)
2224         RC = &X86::VR64RegClass;
2225       else if (RegVT == MVT::v8i1)
2226         RC = &X86::VK8RegClass;
2227       else if (RegVT == MVT::v16i1)
2228         RC = &X86::VK16RegClass;
2229       else
2230         llvm_unreachable("Unknown argument type!");
2231
2232       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2233       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2234
2235       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2236       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2237       // right size.
2238       if (VA.getLocInfo() == CCValAssign::SExt)
2239         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2240                                DAG.getValueType(VA.getValVT()));
2241       else if (VA.getLocInfo() == CCValAssign::ZExt)
2242         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2243                                DAG.getValueType(VA.getValVT()));
2244       else if (VA.getLocInfo() == CCValAssign::BCvt)
2245         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2246
2247       if (VA.isExtInLoc()) {
2248         // Handle MMX values passed in XMM regs.
2249         if (RegVT.isVector())
2250           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2251         else
2252           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2253       }
2254     } else {
2255       assert(VA.isMemLoc());
2256       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2257     }
2258
2259     // If value is passed via pointer - do a load.
2260     if (VA.getLocInfo() == CCValAssign::Indirect)
2261       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2262                              MachinePointerInfo(), false, false, false, 0);
2263
2264     InVals.push_back(ArgValue);
2265   }
2266
2267   // The x86-64 ABIs require that for returning structs by value we copy
2268   // the sret argument into %rax/%eax (depending on ABI) for the return.
2269   // Win32 requires us to put the sret argument to %eax as well.
2270   // Save the argument into a virtual register so that we can access it
2271   // from the return points.
2272   if (MF.getFunction()->hasStructRetAttr() &&
2273       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2274     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2275     unsigned Reg = FuncInfo->getSRetReturnReg();
2276     if (!Reg) {
2277       MVT PtrTy = getPointerTy();
2278       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2279       FuncInfo->setSRetReturnReg(Reg);
2280     }
2281     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2282     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2283   }
2284
2285   unsigned StackSize = CCInfo.getNextStackOffset();
2286   // Align stack specially for tail calls.
2287   if (FuncIsMadeTailCallSafe(CallConv,
2288                              MF.getTarget().Options.GuaranteedTailCallOpt))
2289     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2290
2291   // If the function takes variable number of arguments, make a frame index for
2292   // the start of the first vararg value... for expansion of llvm.va_start.
2293   if (isVarArg) {
2294     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2295                     CallConv != CallingConv::X86_ThisCall)) {
2296       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2297     }
2298     if (Is64Bit) {
2299       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2300
2301       // FIXME: We should really autogenerate these arrays
2302       static const uint16_t GPR64ArgRegsWin64[] = {
2303         X86::RCX, X86::RDX, X86::R8,  X86::R9
2304       };
2305       static const uint16_t GPR64ArgRegs64Bit[] = {
2306         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2307       };
2308       static const uint16_t XMMArgRegs64Bit[] = {
2309         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2310         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2311       };
2312       const uint16_t *GPR64ArgRegs;
2313       unsigned NumXMMRegs = 0;
2314
2315       if (IsWin64) {
2316         // The XMM registers which might contain var arg parameters are shadowed
2317         // in their paired GPR.  So we only need to save the GPR to their home
2318         // slots.
2319         TotalNumIntRegs = 4;
2320         GPR64ArgRegs = GPR64ArgRegsWin64;
2321       } else {
2322         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2323         GPR64ArgRegs = GPR64ArgRegs64Bit;
2324
2325         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2326                                                 TotalNumXMMRegs);
2327       }
2328       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2329                                                        TotalNumIntRegs);
2330
2331       bool NoImplicitFloatOps = Fn->getAttributes().
2332         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2333       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2334              "SSE register cannot be used when SSE is disabled!");
2335       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2336                NoImplicitFloatOps) &&
2337              "SSE register cannot be used when SSE is disabled!");
2338       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2339           !Subtarget->hasSSE1())
2340         // Kernel mode asks for SSE to be disabled, so don't push them
2341         // on the stack.
2342         TotalNumXMMRegs = 0;
2343
2344       if (IsWin64) {
2345         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2346         // Get to the caller-allocated home save location.  Add 8 to account
2347         // for the return address.
2348         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2349         FuncInfo->setRegSaveFrameIndex(
2350           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2351         // Fixup to set vararg frame on shadow area (4 x i64).
2352         if (NumIntRegs < 4)
2353           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2354       } else {
2355         // For X86-64, if there are vararg parameters that are passed via
2356         // registers, then we must store them to their spots on the stack so
2357         // they may be loaded by deferencing the result of va_next.
2358         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2359         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2360         FuncInfo->setRegSaveFrameIndex(
2361           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2362                                false));
2363       }
2364
2365       // Store the integer parameter registers.
2366       SmallVector<SDValue, 8> MemOps;
2367       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2368                                         getPointerTy());
2369       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2370       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2371         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2372                                   DAG.getIntPtrConstant(Offset));
2373         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2374                                      &X86::GR64RegClass);
2375         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2376         SDValue Store =
2377           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2378                        MachinePointerInfo::getFixedStack(
2379                          FuncInfo->getRegSaveFrameIndex(), Offset),
2380                        false, false, 0);
2381         MemOps.push_back(Store);
2382         Offset += 8;
2383       }
2384
2385       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2386         // Now store the XMM (fp + vector) parameter registers.
2387         SmallVector<SDValue, 11> SaveXMMOps;
2388         SaveXMMOps.push_back(Chain);
2389
2390         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2391         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2392         SaveXMMOps.push_back(ALVal);
2393
2394         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2395                                FuncInfo->getRegSaveFrameIndex()));
2396         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2397                                FuncInfo->getVarArgsFPOffset()));
2398
2399         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2400           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2401                                        &X86::VR128RegClass);
2402           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2403           SaveXMMOps.push_back(Val);
2404         }
2405         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2406                                      MVT::Other,
2407                                      &SaveXMMOps[0], SaveXMMOps.size()));
2408       }
2409
2410       if (!MemOps.empty())
2411         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2412                             &MemOps[0], MemOps.size());
2413     }
2414   }
2415
2416   // Some CCs need callee pop.
2417   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2418                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2419     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2420   } else {
2421     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2422     // If this is an sret function, the return should pop the hidden pointer.
2423     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2424         argsAreStructReturn(Ins) == StackStructReturn)
2425       FuncInfo->setBytesToPopOnReturn(4);
2426   }
2427
2428   if (!Is64Bit) {
2429     // RegSaveFrameIndex is X86-64 only.
2430     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2431     if (CallConv == CallingConv::X86_FastCall ||
2432         CallConv == CallingConv::X86_ThisCall)
2433       // fastcc functions can't have varargs.
2434       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2435   }
2436
2437   FuncInfo->setArgumentStackSize(StackSize);
2438
2439   return Chain;
2440 }
2441
2442 SDValue
2443 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2444                                     SDValue StackPtr, SDValue Arg,
2445                                     SDLoc dl, SelectionDAG &DAG,
2446                                     const CCValAssign &VA,
2447                                     ISD::ArgFlagsTy Flags) const {
2448   unsigned LocMemOffset = VA.getLocMemOffset();
2449   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2450   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2451   if (Flags.isByVal())
2452     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2453
2454   return DAG.getStore(Chain, dl, Arg, PtrOff,
2455                       MachinePointerInfo::getStack(LocMemOffset),
2456                       false, false, 0);
2457 }
2458
2459 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2460 /// optimization is performed and it is required.
2461 SDValue
2462 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2463                                            SDValue &OutRetAddr, SDValue Chain,
2464                                            bool IsTailCall, bool Is64Bit,
2465                                            int FPDiff, SDLoc dl) const {
2466   // Adjust the Return address stack slot.
2467   EVT VT = getPointerTy();
2468   OutRetAddr = getReturnAddressFrameIndex(DAG);
2469
2470   // Load the "old" Return address.
2471   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2472                            false, false, false, 0);
2473   return SDValue(OutRetAddr.getNode(), 1);
2474 }
2475
2476 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2477 /// optimization is performed and it is required (FPDiff!=0).
2478 static SDValue
2479 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2480                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2481                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2482   // Store the return address to the appropriate stack slot.
2483   if (!FPDiff) return Chain;
2484   // Calculate the new stack slot for the return address.
2485   int NewReturnAddrFI =
2486     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2487                                          false);
2488   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2489   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2490                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2491                        false, false, 0);
2492   return Chain;
2493 }
2494
2495 SDValue
2496 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2497                              SmallVectorImpl<SDValue> &InVals) const {
2498   SelectionDAG &DAG                     = CLI.DAG;
2499   SDLoc &dl                             = CLI.DL;
2500   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2501   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2502   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2503   SDValue Chain                         = CLI.Chain;
2504   SDValue Callee                        = CLI.Callee;
2505   CallingConv::ID CallConv              = CLI.CallConv;
2506   bool &isTailCall                      = CLI.IsTailCall;
2507   bool isVarArg                         = CLI.IsVarArg;
2508
2509   MachineFunction &MF = DAG.getMachineFunction();
2510   bool Is64Bit        = Subtarget->is64Bit();
2511   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2512   bool IsWindows      = Subtarget->isTargetWindows();
2513   StructReturnType SR = callIsStructReturn(Outs);
2514   bool IsSibcall      = false;
2515
2516   if (MF.getTarget().Options.DisableTailCalls)
2517     isTailCall = false;
2518
2519   if (isTailCall) {
2520     // Check if it's really possible to do a tail call.
2521     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2522                     isVarArg, SR != NotStructReturn,
2523                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2524                     Outs, OutVals, Ins, DAG);
2525
2526     // Sibcalls are automatically detected tailcalls which do not require
2527     // ABI changes.
2528     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2529       IsSibcall = true;
2530
2531     if (isTailCall)
2532       ++NumTailCalls;
2533   }
2534
2535   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2536          "Var args not supported with calling convention fastcc, ghc or hipe");
2537
2538   // Analyze operands of the call, assigning locations to each operand.
2539   SmallVector<CCValAssign, 16> ArgLocs;
2540   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2541                  ArgLocs, *DAG.getContext());
2542
2543   // Allocate shadow area for Win64
2544   if (IsWin64)
2545     CCInfo.AllocateStack(32, 8);
2546
2547   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2548
2549   // Get a count of how many bytes are to be pushed on the stack.
2550   unsigned NumBytes = CCInfo.getNextStackOffset();
2551   if (IsSibcall)
2552     // This is a sibcall. The memory operands are available in caller's
2553     // own caller's stack.
2554     NumBytes = 0;
2555   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2556            IsTailCallConvention(CallConv))
2557     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2558
2559   int FPDiff = 0;
2560   if (isTailCall && !IsSibcall) {
2561     // Lower arguments at fp - stackoffset + fpdiff.
2562     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2563     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2564
2565     FPDiff = NumBytesCallerPushed - NumBytes;
2566
2567     // Set the delta of movement of the returnaddr stackslot.
2568     // But only set if delta is greater than previous delta.
2569     if (FPDiff < X86Info->getTCReturnAddrDelta())
2570       X86Info->setTCReturnAddrDelta(FPDiff);
2571   }
2572
2573   if (!IsSibcall)
2574     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2575                                  dl);
2576
2577   SDValue RetAddrFrIdx;
2578   // Load return address for tail calls.
2579   if (isTailCall && FPDiff)
2580     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2581                                     Is64Bit, FPDiff, dl);
2582
2583   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2584   SmallVector<SDValue, 8> MemOpChains;
2585   SDValue StackPtr;
2586
2587   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2588   // of tail call optimization arguments are handle later.
2589   const X86RegisterInfo *RegInfo =
2590     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2591   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2592     CCValAssign &VA = ArgLocs[i];
2593     EVT RegVT = VA.getLocVT();
2594     SDValue Arg = OutVals[i];
2595     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2596     bool isByVal = Flags.isByVal();
2597
2598     // Promote the value if needed.
2599     switch (VA.getLocInfo()) {
2600     default: llvm_unreachable("Unknown loc info!");
2601     case CCValAssign::Full: break;
2602     case CCValAssign::SExt:
2603       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2604       break;
2605     case CCValAssign::ZExt:
2606       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2607       break;
2608     case CCValAssign::AExt:
2609       if (RegVT.is128BitVector()) {
2610         // Special case: passing MMX values in XMM registers.
2611         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2612         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2613         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2614       } else
2615         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2616       break;
2617     case CCValAssign::BCvt:
2618       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2619       break;
2620     case CCValAssign::Indirect: {
2621       // Store the argument.
2622       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2623       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2624       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2625                            MachinePointerInfo::getFixedStack(FI),
2626                            false, false, 0);
2627       Arg = SpillSlot;
2628       break;
2629     }
2630     }
2631
2632     if (VA.isRegLoc()) {
2633       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2634       if (isVarArg && IsWin64) {
2635         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2636         // shadow reg if callee is a varargs function.
2637         unsigned ShadowReg = 0;
2638         switch (VA.getLocReg()) {
2639         case X86::XMM0: ShadowReg = X86::RCX; break;
2640         case X86::XMM1: ShadowReg = X86::RDX; break;
2641         case X86::XMM2: ShadowReg = X86::R8; break;
2642         case X86::XMM3: ShadowReg = X86::R9; break;
2643         }
2644         if (ShadowReg)
2645           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2646       }
2647     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2648       assert(VA.isMemLoc());
2649       if (StackPtr.getNode() == 0)
2650         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2651                                       getPointerTy());
2652       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2653                                              dl, DAG, VA, Flags));
2654     }
2655   }
2656
2657   if (!MemOpChains.empty())
2658     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2659                         &MemOpChains[0], MemOpChains.size());
2660
2661   if (Subtarget->isPICStyleGOT()) {
2662     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2663     // GOT pointer.
2664     if (!isTailCall) {
2665       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2666                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2667     } else {
2668       // If we are tail calling and generating PIC/GOT style code load the
2669       // address of the callee into ECX. The value in ecx is used as target of
2670       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2671       // for tail calls on PIC/GOT architectures. Normally we would just put the
2672       // address of GOT into ebx and then call target@PLT. But for tail calls
2673       // ebx would be restored (since ebx is callee saved) before jumping to the
2674       // target@PLT.
2675
2676       // Note: The actual moving to ECX is done further down.
2677       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2678       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2679           !G->getGlobal()->hasProtectedVisibility())
2680         Callee = LowerGlobalAddress(Callee, DAG);
2681       else if (isa<ExternalSymbolSDNode>(Callee))
2682         Callee = LowerExternalSymbol(Callee, DAG);
2683     }
2684   }
2685
2686   if (Is64Bit && isVarArg && !IsWin64) {
2687     // From AMD64 ABI document:
2688     // For calls that may call functions that use varargs or stdargs
2689     // (prototype-less calls or calls to functions containing ellipsis (...) in
2690     // the declaration) %al is used as hidden argument to specify the number
2691     // of SSE registers used. The contents of %al do not need to match exactly
2692     // the number of registers, but must be an ubound on the number of SSE
2693     // registers used and is in the range 0 - 8 inclusive.
2694
2695     // Count the number of XMM registers allocated.
2696     static const uint16_t XMMArgRegs[] = {
2697       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2698       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2699     };
2700     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2701     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2702            && "SSE registers cannot be used when SSE is disabled");
2703
2704     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2705                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2706   }
2707
2708   // For tail calls lower the arguments to the 'real' stack slot.
2709   if (isTailCall) {
2710     // Force all the incoming stack arguments to be loaded from the stack
2711     // before any new outgoing arguments are stored to the stack, because the
2712     // outgoing stack slots may alias the incoming argument stack slots, and
2713     // the alias isn't otherwise explicit. This is slightly more conservative
2714     // than necessary, because it means that each store effectively depends
2715     // on every argument instead of just those arguments it would clobber.
2716     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2717
2718     SmallVector<SDValue, 8> MemOpChains2;
2719     SDValue FIN;
2720     int FI = 0;
2721     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2722       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2723         CCValAssign &VA = ArgLocs[i];
2724         if (VA.isRegLoc())
2725           continue;
2726         assert(VA.isMemLoc());
2727         SDValue Arg = OutVals[i];
2728         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2729         // Create frame index.
2730         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2731         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2732         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2733         FIN = DAG.getFrameIndex(FI, getPointerTy());
2734
2735         if (Flags.isByVal()) {
2736           // Copy relative to framepointer.
2737           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2738           if (StackPtr.getNode() == 0)
2739             StackPtr = DAG.getCopyFromReg(Chain, dl,
2740                                           RegInfo->getStackRegister(),
2741                                           getPointerTy());
2742           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2743
2744           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2745                                                            ArgChain,
2746                                                            Flags, DAG, dl));
2747         } else {
2748           // Store relative to framepointer.
2749           MemOpChains2.push_back(
2750             DAG.getStore(ArgChain, dl, Arg, FIN,
2751                          MachinePointerInfo::getFixedStack(FI),
2752                          false, false, 0));
2753         }
2754       }
2755     }
2756
2757     if (!MemOpChains2.empty())
2758       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2759                           &MemOpChains2[0], MemOpChains2.size());
2760
2761     // Store the return address to the appropriate stack slot.
2762     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2763                                      getPointerTy(), RegInfo->getSlotSize(),
2764                                      FPDiff, dl);
2765   }
2766
2767   // Build a sequence of copy-to-reg nodes chained together with token chain
2768   // and flag operands which copy the outgoing args into registers.
2769   SDValue InFlag;
2770   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2771     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2772                              RegsToPass[i].second, InFlag);
2773     InFlag = Chain.getValue(1);
2774   }
2775
2776   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2777     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2778     // In the 64-bit large code model, we have to make all calls
2779     // through a register, since the call instruction's 32-bit
2780     // pc-relative offset may not be large enough to hold the whole
2781     // address.
2782   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2783     // If the callee is a GlobalAddress node (quite common, every direct call
2784     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2785     // it.
2786
2787     // We should use extra load for direct calls to dllimported functions in
2788     // non-JIT mode.
2789     const GlobalValue *GV = G->getGlobal();
2790     if (!GV->hasDLLImportLinkage()) {
2791       unsigned char OpFlags = 0;
2792       bool ExtraLoad = false;
2793       unsigned WrapperKind = ISD::DELETED_NODE;
2794
2795       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2796       // external symbols most go through the PLT in PIC mode.  If the symbol
2797       // has hidden or protected visibility, or if it is static or local, then
2798       // we don't need to use the PLT - we can directly call it.
2799       if (Subtarget->isTargetELF() &&
2800           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2801           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2802         OpFlags = X86II::MO_PLT;
2803       } else if (Subtarget->isPICStyleStubAny() &&
2804                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2805                  (!Subtarget->getTargetTriple().isMacOSX() ||
2806                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2807         // PC-relative references to external symbols should go through $stub,
2808         // unless we're building with the leopard linker or later, which
2809         // automatically synthesizes these stubs.
2810         OpFlags = X86II::MO_DARWIN_STUB;
2811       } else if (Subtarget->isPICStyleRIPRel() &&
2812                  isa<Function>(GV) &&
2813                  cast<Function>(GV)->getAttributes().
2814                    hasAttribute(AttributeSet::FunctionIndex,
2815                                 Attribute::NonLazyBind)) {
2816         // If the function is marked as non-lazy, generate an indirect call
2817         // which loads from the GOT directly. This avoids runtime overhead
2818         // at the cost of eager binding (and one extra byte of encoding).
2819         OpFlags = X86II::MO_GOTPCREL;
2820         WrapperKind = X86ISD::WrapperRIP;
2821         ExtraLoad = true;
2822       }
2823
2824       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2825                                           G->getOffset(), OpFlags);
2826
2827       // Add a wrapper if needed.
2828       if (WrapperKind != ISD::DELETED_NODE)
2829         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2830       // Add extra indirection if needed.
2831       if (ExtraLoad)
2832         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2833                              MachinePointerInfo::getGOT(),
2834                              false, false, false, 0);
2835     }
2836   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2837     unsigned char OpFlags = 0;
2838
2839     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2840     // external symbols should go through the PLT.
2841     if (Subtarget->isTargetELF() &&
2842         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2843       OpFlags = X86II::MO_PLT;
2844     } else if (Subtarget->isPICStyleStubAny() &&
2845                (!Subtarget->getTargetTriple().isMacOSX() ||
2846                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2847       // PC-relative references to external symbols should go through $stub,
2848       // unless we're building with the leopard linker or later, which
2849       // automatically synthesizes these stubs.
2850       OpFlags = X86II::MO_DARWIN_STUB;
2851     }
2852
2853     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2854                                          OpFlags);
2855   }
2856
2857   // Returns a chain & a flag for retval copy to use.
2858   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2859   SmallVector<SDValue, 8> Ops;
2860
2861   if (!IsSibcall && isTailCall) {
2862     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2863                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2864     InFlag = Chain.getValue(1);
2865   }
2866
2867   Ops.push_back(Chain);
2868   Ops.push_back(Callee);
2869
2870   if (isTailCall)
2871     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2872
2873   // Add argument registers to the end of the list so that they are known live
2874   // into the call.
2875   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2876     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2877                                   RegsToPass[i].second.getValueType()));
2878
2879   // Add a register mask operand representing the call-preserved registers.
2880   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2881   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2882   assert(Mask && "Missing call preserved mask for calling convention");
2883   Ops.push_back(DAG.getRegisterMask(Mask));
2884
2885   if (InFlag.getNode())
2886     Ops.push_back(InFlag);
2887
2888   if (isTailCall) {
2889     // We used to do:
2890     //// If this is the first return lowered for this function, add the regs
2891     //// to the liveout set for the function.
2892     // This isn't right, although it's probably harmless on x86; liveouts
2893     // should be computed from returns not tail calls.  Consider a void
2894     // function making a tail call to a function returning int.
2895     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2896   }
2897
2898   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2899   InFlag = Chain.getValue(1);
2900
2901   // Create the CALLSEQ_END node.
2902   unsigned NumBytesForCalleeToPush;
2903   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2904                        getTargetMachine().Options.GuaranteedTailCallOpt))
2905     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2906   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2907            SR == StackStructReturn)
2908     // If this is a call to a struct-return function, the callee
2909     // pops the hidden struct pointer, so we have to push it back.
2910     // This is common for Darwin/X86, Linux & Mingw32 targets.
2911     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2912     NumBytesForCalleeToPush = 4;
2913   else
2914     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2915
2916   // Returns a flag for retval copy to use.
2917   if (!IsSibcall) {
2918     Chain = DAG.getCALLSEQ_END(Chain,
2919                                DAG.getIntPtrConstant(NumBytes, true),
2920                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2921                                                      true),
2922                                InFlag, dl);
2923     InFlag = Chain.getValue(1);
2924   }
2925
2926   // Handle result values, copying them out of physregs into vregs that we
2927   // return.
2928   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2929                          Ins, dl, DAG, InVals);
2930 }
2931
2932 //===----------------------------------------------------------------------===//
2933 //                Fast Calling Convention (tail call) implementation
2934 //===----------------------------------------------------------------------===//
2935
2936 //  Like std call, callee cleans arguments, convention except that ECX is
2937 //  reserved for storing the tail called function address. Only 2 registers are
2938 //  free for argument passing (inreg). Tail call optimization is performed
2939 //  provided:
2940 //                * tailcallopt is enabled
2941 //                * caller/callee are fastcc
2942 //  On X86_64 architecture with GOT-style position independent code only local
2943 //  (within module) calls are supported at the moment.
2944 //  To keep the stack aligned according to platform abi the function
2945 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2946 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2947 //  If a tail called function callee has more arguments than the caller the
2948 //  caller needs to make sure that there is room to move the RETADDR to. This is
2949 //  achieved by reserving an area the size of the argument delta right after the
2950 //  original REtADDR, but before the saved framepointer or the spilled registers
2951 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2952 //  stack layout:
2953 //    arg1
2954 //    arg2
2955 //    RETADDR
2956 //    [ new RETADDR
2957 //      move area ]
2958 //    (possible EBP)
2959 //    ESI
2960 //    EDI
2961 //    local1 ..
2962
2963 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2964 /// for a 16 byte align requirement.
2965 unsigned
2966 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2967                                                SelectionDAG& DAG) const {
2968   MachineFunction &MF = DAG.getMachineFunction();
2969   const TargetMachine &TM = MF.getTarget();
2970   const X86RegisterInfo *RegInfo =
2971     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2972   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2973   unsigned StackAlignment = TFI.getStackAlignment();
2974   uint64_t AlignMask = StackAlignment - 1;
2975   int64_t Offset = StackSize;
2976   unsigned SlotSize = RegInfo->getSlotSize();
2977   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2978     // Number smaller than 12 so just add the difference.
2979     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2980   } else {
2981     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2982     Offset = ((~AlignMask) & Offset) + StackAlignment +
2983       (StackAlignment-SlotSize);
2984   }
2985   return Offset;
2986 }
2987
2988 /// MatchingStackOffset - Return true if the given stack call argument is
2989 /// already available in the same position (relatively) of the caller's
2990 /// incoming argument stack.
2991 static
2992 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2993                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2994                          const X86InstrInfo *TII) {
2995   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2996   int FI = INT_MAX;
2997   if (Arg.getOpcode() == ISD::CopyFromReg) {
2998     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2999     if (!TargetRegisterInfo::isVirtualRegister(VR))
3000       return false;
3001     MachineInstr *Def = MRI->getVRegDef(VR);
3002     if (!Def)
3003       return false;
3004     if (!Flags.isByVal()) {
3005       if (!TII->isLoadFromStackSlot(Def, FI))
3006         return false;
3007     } else {
3008       unsigned Opcode = Def->getOpcode();
3009       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3010           Def->getOperand(1).isFI()) {
3011         FI = Def->getOperand(1).getIndex();
3012         Bytes = Flags.getByValSize();
3013       } else
3014         return false;
3015     }
3016   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3017     if (Flags.isByVal())
3018       // ByVal argument is passed in as a pointer but it's now being
3019       // dereferenced. e.g.
3020       // define @foo(%struct.X* %A) {
3021       //   tail call @bar(%struct.X* byval %A)
3022       // }
3023       return false;
3024     SDValue Ptr = Ld->getBasePtr();
3025     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3026     if (!FINode)
3027       return false;
3028     FI = FINode->getIndex();
3029   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3030     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3031     FI = FINode->getIndex();
3032     Bytes = Flags.getByValSize();
3033   } else
3034     return false;
3035
3036   assert(FI != INT_MAX);
3037   if (!MFI->isFixedObjectIndex(FI))
3038     return false;
3039   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3040 }
3041
3042 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3043 /// for tail call optimization. Targets which want to do tail call
3044 /// optimization should implement this function.
3045 bool
3046 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3047                                                      CallingConv::ID CalleeCC,
3048                                                      bool isVarArg,
3049                                                      bool isCalleeStructRet,
3050                                                      bool isCallerStructRet,
3051                                                      Type *RetTy,
3052                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3053                                     const SmallVectorImpl<SDValue> &OutVals,
3054                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3055                                                      SelectionDAG &DAG) const {
3056   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3057     return false;
3058
3059   // If -tailcallopt is specified, make fastcc functions tail-callable.
3060   const MachineFunction &MF = DAG.getMachineFunction();
3061   const Function *CallerF = MF.getFunction();
3062
3063   // If the function return type is x86_fp80 and the callee return type is not,
3064   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3065   // perform a tailcall optimization here.
3066   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3067     return false;
3068
3069   CallingConv::ID CallerCC = CallerF->getCallingConv();
3070   bool CCMatch = CallerCC == CalleeCC;
3071   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3072   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3073
3074   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3075     if (IsTailCallConvention(CalleeCC) && CCMatch)
3076       return true;
3077     return false;
3078   }
3079
3080   // Look for obvious safe cases to perform tail call optimization that do not
3081   // require ABI changes. This is what gcc calls sibcall.
3082
3083   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3084   // emit a special epilogue.
3085   const X86RegisterInfo *RegInfo =
3086     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3087   if (RegInfo->needsStackRealignment(MF))
3088     return false;
3089
3090   // Also avoid sibcall optimization if either caller or callee uses struct
3091   // return semantics.
3092   if (isCalleeStructRet || isCallerStructRet)
3093     return false;
3094
3095   // An stdcall/thiscall caller is expected to clean up its arguments; the
3096   // callee isn't going to do that.
3097   // FIXME: this is more restrictive than needed. We could produce a tailcall
3098   // when the stack adjustment matches. For example, with a thiscall that takes
3099   // only one argument.
3100   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3101                    CallerCC == CallingConv::X86_ThisCall))
3102     return false;
3103
3104   // Do not sibcall optimize vararg calls unless all arguments are passed via
3105   // registers.
3106   if (isVarArg && !Outs.empty()) {
3107
3108     // Optimizing for varargs on Win64 is unlikely to be safe without
3109     // additional testing.
3110     if (IsCalleeWin64 || IsCallerWin64)
3111       return false;
3112
3113     SmallVector<CCValAssign, 16> ArgLocs;
3114     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3115                    getTargetMachine(), ArgLocs, *DAG.getContext());
3116
3117     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3118     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3119       if (!ArgLocs[i].isRegLoc())
3120         return false;
3121   }
3122
3123   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3124   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3125   // this into a sibcall.
3126   bool Unused = false;
3127   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3128     if (!Ins[i].Used) {
3129       Unused = true;
3130       break;
3131     }
3132   }
3133   if (Unused) {
3134     SmallVector<CCValAssign, 16> RVLocs;
3135     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3136                    getTargetMachine(), RVLocs, *DAG.getContext());
3137     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3138     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3139       CCValAssign &VA = RVLocs[i];
3140       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3141         return false;
3142     }
3143   }
3144
3145   // If the calling conventions do not match, then we'd better make sure the
3146   // results are returned in the same way as what the caller expects.
3147   if (!CCMatch) {
3148     SmallVector<CCValAssign, 16> RVLocs1;
3149     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3150                     getTargetMachine(), RVLocs1, *DAG.getContext());
3151     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3152
3153     SmallVector<CCValAssign, 16> RVLocs2;
3154     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3155                     getTargetMachine(), RVLocs2, *DAG.getContext());
3156     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3157
3158     if (RVLocs1.size() != RVLocs2.size())
3159       return false;
3160     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3161       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3162         return false;
3163       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3164         return false;
3165       if (RVLocs1[i].isRegLoc()) {
3166         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3167           return false;
3168       } else {
3169         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3170           return false;
3171       }
3172     }
3173   }
3174
3175   // If the callee takes no arguments then go on to check the results of the
3176   // call.
3177   if (!Outs.empty()) {
3178     // Check if stack adjustment is needed. For now, do not do this if any
3179     // argument is passed on the stack.
3180     SmallVector<CCValAssign, 16> ArgLocs;
3181     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3182                    getTargetMachine(), ArgLocs, *DAG.getContext());
3183
3184     // Allocate shadow area for Win64
3185     if (IsCalleeWin64)
3186       CCInfo.AllocateStack(32, 8);
3187
3188     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3189     if (CCInfo.getNextStackOffset()) {
3190       MachineFunction &MF = DAG.getMachineFunction();
3191       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3192         return false;
3193
3194       // Check if the arguments are already laid out in the right way as
3195       // the caller's fixed stack objects.
3196       MachineFrameInfo *MFI = MF.getFrameInfo();
3197       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3198       const X86InstrInfo *TII =
3199         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3200       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3201         CCValAssign &VA = ArgLocs[i];
3202         SDValue Arg = OutVals[i];
3203         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3204         if (VA.getLocInfo() == CCValAssign::Indirect)
3205           return false;
3206         if (!VA.isRegLoc()) {
3207           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3208                                    MFI, MRI, TII))
3209             return false;
3210         }
3211       }
3212     }
3213
3214     // If the tailcall address may be in a register, then make sure it's
3215     // possible to register allocate for it. In 32-bit, the call address can
3216     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3217     // callee-saved registers are restored. These happen to be the same
3218     // registers used to pass 'inreg' arguments so watch out for those.
3219     if (!Subtarget->is64Bit() &&
3220         ((!isa<GlobalAddressSDNode>(Callee) &&
3221           !isa<ExternalSymbolSDNode>(Callee)) ||
3222          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3223       unsigned NumInRegs = 0;
3224       // In PIC we need an extra register to formulate the address computation
3225       // for the callee.
3226       unsigned MaxInRegs =
3227           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3228
3229       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3230         CCValAssign &VA = ArgLocs[i];
3231         if (!VA.isRegLoc())
3232           continue;
3233         unsigned Reg = VA.getLocReg();
3234         switch (Reg) {
3235         default: break;
3236         case X86::EAX: case X86::EDX: case X86::ECX:
3237           if (++NumInRegs == MaxInRegs)
3238             return false;
3239           break;
3240         }
3241       }
3242     }
3243   }
3244
3245   return true;
3246 }
3247
3248 FastISel *
3249 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3250                                   const TargetLibraryInfo *libInfo) const {
3251   return X86::createFastISel(funcInfo, libInfo);
3252 }
3253
3254 //===----------------------------------------------------------------------===//
3255 //                           Other Lowering Hooks
3256 //===----------------------------------------------------------------------===//
3257
3258 static bool MayFoldLoad(SDValue Op) {
3259   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3260 }
3261
3262 static bool MayFoldIntoStore(SDValue Op) {
3263   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3264 }
3265
3266 static bool isTargetShuffle(unsigned Opcode) {
3267   switch(Opcode) {
3268   default: return false;
3269   case X86ISD::PSHUFD:
3270   case X86ISD::PSHUFHW:
3271   case X86ISD::PSHUFLW:
3272   case X86ISD::SHUFP:
3273   case X86ISD::PALIGNR:
3274   case X86ISD::MOVLHPS:
3275   case X86ISD::MOVLHPD:
3276   case X86ISD::MOVHLPS:
3277   case X86ISD::MOVLPS:
3278   case X86ISD::MOVLPD:
3279   case X86ISD::MOVSHDUP:
3280   case X86ISD::MOVSLDUP:
3281   case X86ISD::MOVDDUP:
3282   case X86ISD::MOVSS:
3283   case X86ISD::MOVSD:
3284   case X86ISD::UNPCKL:
3285   case X86ISD::UNPCKH:
3286   case X86ISD::VPERMILP:
3287   case X86ISD::VPERM2X128:
3288   case X86ISD::VPERMI:
3289     return true;
3290   }
3291 }
3292
3293 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3294                                     SDValue V1, SelectionDAG &DAG) {
3295   switch(Opc) {
3296   default: llvm_unreachable("Unknown x86 shuffle node");
3297   case X86ISD::MOVSHDUP:
3298   case X86ISD::MOVSLDUP:
3299   case X86ISD::MOVDDUP:
3300     return DAG.getNode(Opc, dl, VT, V1);
3301   }
3302 }
3303
3304 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3305                                     SDValue V1, unsigned TargetMask,
3306                                     SelectionDAG &DAG) {
3307   switch(Opc) {
3308   default: llvm_unreachable("Unknown x86 shuffle node");
3309   case X86ISD::PSHUFD:
3310   case X86ISD::PSHUFHW:
3311   case X86ISD::PSHUFLW:
3312   case X86ISD::VPERMILP:
3313   case X86ISD::VPERMI:
3314     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3315   }
3316 }
3317
3318 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3319                                     SDValue V1, SDValue V2, unsigned TargetMask,
3320                                     SelectionDAG &DAG) {
3321   switch(Opc) {
3322   default: llvm_unreachable("Unknown x86 shuffle node");
3323   case X86ISD::PALIGNR:
3324   case X86ISD::SHUFP:
3325   case X86ISD::VPERM2X128:
3326     return DAG.getNode(Opc, dl, VT, V1, V2,
3327                        DAG.getConstant(TargetMask, MVT::i8));
3328   }
3329 }
3330
3331 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3332                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3333   switch(Opc) {
3334   default: llvm_unreachable("Unknown x86 shuffle node");
3335   case X86ISD::MOVLHPS:
3336   case X86ISD::MOVLHPD:
3337   case X86ISD::MOVHLPS:
3338   case X86ISD::MOVLPS:
3339   case X86ISD::MOVLPD:
3340   case X86ISD::MOVSS:
3341   case X86ISD::MOVSD:
3342   case X86ISD::UNPCKL:
3343   case X86ISD::UNPCKH:
3344     return DAG.getNode(Opc, dl, VT, V1, V2);
3345   }
3346 }
3347
3348 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3349   MachineFunction &MF = DAG.getMachineFunction();
3350   const X86RegisterInfo *RegInfo =
3351     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3352   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3353   int ReturnAddrIndex = FuncInfo->getRAIndex();
3354
3355   if (ReturnAddrIndex == 0) {
3356     // Set up a frame object for the return address.
3357     unsigned SlotSize = RegInfo->getSlotSize();
3358     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3359                                                            -(int64_t)SlotSize,
3360                                                            false);
3361     FuncInfo->setRAIndex(ReturnAddrIndex);
3362   }
3363
3364   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3365 }
3366
3367 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3368                                        bool hasSymbolicDisplacement) {
3369   // Offset should fit into 32 bit immediate field.
3370   if (!isInt<32>(Offset))
3371     return false;
3372
3373   // If we don't have a symbolic displacement - we don't have any extra
3374   // restrictions.
3375   if (!hasSymbolicDisplacement)
3376     return true;
3377
3378   // FIXME: Some tweaks might be needed for medium code model.
3379   if (M != CodeModel::Small && M != CodeModel::Kernel)
3380     return false;
3381
3382   // For small code model we assume that latest object is 16MB before end of 31
3383   // bits boundary. We may also accept pretty large negative constants knowing
3384   // that all objects are in the positive half of address space.
3385   if (M == CodeModel::Small && Offset < 16*1024*1024)
3386     return true;
3387
3388   // For kernel code model we know that all object resist in the negative half
3389   // of 32bits address space. We may not accept negative offsets, since they may
3390   // be just off and we may accept pretty large positive ones.
3391   if (M == CodeModel::Kernel && Offset > 0)
3392     return true;
3393
3394   return false;
3395 }
3396
3397 /// isCalleePop - Determines whether the callee is required to pop its
3398 /// own arguments. Callee pop is necessary to support tail calls.
3399 bool X86::isCalleePop(CallingConv::ID CallingConv,
3400                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3401   if (IsVarArg)
3402     return false;
3403
3404   switch (CallingConv) {
3405   default:
3406     return false;
3407   case CallingConv::X86_StdCall:
3408     return !is64Bit;
3409   case CallingConv::X86_FastCall:
3410     return !is64Bit;
3411   case CallingConv::X86_ThisCall:
3412     return !is64Bit;
3413   case CallingConv::Fast:
3414     return TailCallOpt;
3415   case CallingConv::GHC:
3416     return TailCallOpt;
3417   case CallingConv::HiPE:
3418     return TailCallOpt;
3419   }
3420 }
3421
3422 /// \brief Return true if the condition is an unsigned comparison operation.
3423 static bool isX86CCUnsigned(unsigned X86CC) {
3424   switch (X86CC) {
3425   default: llvm_unreachable("Invalid integer condition!");
3426   case X86::COND_E:     return true;
3427   case X86::COND_G:     return false;
3428   case X86::COND_GE:    return false;
3429   case X86::COND_L:     return false;
3430   case X86::COND_LE:    return false;
3431   case X86::COND_NE:    return true;
3432   case X86::COND_B:     return true;
3433   case X86::COND_A:     return true;
3434   case X86::COND_BE:    return true;
3435   case X86::COND_AE:    return true;
3436   }
3437   llvm_unreachable("covered switch fell through?!");
3438 }
3439
3440 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3441 /// specific condition code, returning the condition code and the LHS/RHS of the
3442 /// comparison to make.
3443 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3444                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3445   if (!isFP) {
3446     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3447       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3448         // X > -1   -> X == 0, jump !sign.
3449         RHS = DAG.getConstant(0, RHS.getValueType());
3450         return X86::COND_NS;
3451       }
3452       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3453         // X < 0   -> X == 0, jump on sign.
3454         return X86::COND_S;
3455       }
3456       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3457         // X < 1   -> X <= 0
3458         RHS = DAG.getConstant(0, RHS.getValueType());
3459         return X86::COND_LE;
3460       }
3461     }
3462
3463     switch (SetCCOpcode) {
3464     default: llvm_unreachable("Invalid integer condition!");
3465     case ISD::SETEQ:  return X86::COND_E;
3466     case ISD::SETGT:  return X86::COND_G;
3467     case ISD::SETGE:  return X86::COND_GE;
3468     case ISD::SETLT:  return X86::COND_L;
3469     case ISD::SETLE:  return X86::COND_LE;
3470     case ISD::SETNE:  return X86::COND_NE;
3471     case ISD::SETULT: return X86::COND_B;
3472     case ISD::SETUGT: return X86::COND_A;
3473     case ISD::SETULE: return X86::COND_BE;
3474     case ISD::SETUGE: return X86::COND_AE;
3475     }
3476   }
3477
3478   // First determine if it is required or is profitable to flip the operands.
3479
3480   // If LHS is a foldable load, but RHS is not, flip the condition.
3481   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3482       !ISD::isNON_EXTLoad(RHS.getNode())) {
3483     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3484     std::swap(LHS, RHS);
3485   }
3486
3487   switch (SetCCOpcode) {
3488   default: break;
3489   case ISD::SETOLT:
3490   case ISD::SETOLE:
3491   case ISD::SETUGT:
3492   case ISD::SETUGE:
3493     std::swap(LHS, RHS);
3494     break;
3495   }
3496
3497   // On a floating point condition, the flags are set as follows:
3498   // ZF  PF  CF   op
3499   //  0 | 0 | 0 | X > Y
3500   //  0 | 0 | 1 | X < Y
3501   //  1 | 0 | 0 | X == Y
3502   //  1 | 1 | 1 | unordered
3503   switch (SetCCOpcode) {
3504   default: llvm_unreachable("Condcode should be pre-legalized away");
3505   case ISD::SETUEQ:
3506   case ISD::SETEQ:   return X86::COND_E;
3507   case ISD::SETOLT:              // flipped
3508   case ISD::SETOGT:
3509   case ISD::SETGT:   return X86::COND_A;
3510   case ISD::SETOLE:              // flipped
3511   case ISD::SETOGE:
3512   case ISD::SETGE:   return X86::COND_AE;
3513   case ISD::SETUGT:              // flipped
3514   case ISD::SETULT:
3515   case ISD::SETLT:   return X86::COND_B;
3516   case ISD::SETUGE:              // flipped
3517   case ISD::SETULE:
3518   case ISD::SETLE:   return X86::COND_BE;
3519   case ISD::SETONE:
3520   case ISD::SETNE:   return X86::COND_NE;
3521   case ISD::SETUO:   return X86::COND_P;
3522   case ISD::SETO:    return X86::COND_NP;
3523   case ISD::SETOEQ:
3524   case ISD::SETUNE:  return X86::COND_INVALID;
3525   }
3526 }
3527
3528 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3529 /// code. Current x86 isa includes the following FP cmov instructions:
3530 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3531 static bool hasFPCMov(unsigned X86CC) {
3532   switch (X86CC) {
3533   default:
3534     return false;
3535   case X86::COND_B:
3536   case X86::COND_BE:
3537   case X86::COND_E:
3538   case X86::COND_P:
3539   case X86::COND_A:
3540   case X86::COND_AE:
3541   case X86::COND_NE:
3542   case X86::COND_NP:
3543     return true;
3544   }
3545 }
3546
3547 /// isFPImmLegal - Returns true if the target can instruction select the
3548 /// specified FP immediate natively. If false, the legalizer will
3549 /// materialize the FP immediate as a load from a constant pool.
3550 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3551   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3552     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3553       return true;
3554   }
3555   return false;
3556 }
3557
3558 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3559 /// the specified range (L, H].
3560 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3561   return (Val < 0) || (Val >= Low && Val < Hi);
3562 }
3563
3564 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3565 /// specified value.
3566 static bool isUndefOrEqual(int Val, int CmpVal) {
3567   return (Val < 0 || Val == CmpVal);
3568 }
3569
3570 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3571 /// from position Pos and ending in Pos+Size, falls within the specified
3572 /// sequential range (L, L+Pos]. or is undef.
3573 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3574                                        unsigned Pos, unsigned Size, int Low) {
3575   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3576     if (!isUndefOrEqual(Mask[i], Low))
3577       return false;
3578   return true;
3579 }
3580
3581 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3582 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3583 /// the second operand.
3584 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3585   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3586     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3587   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3588     return (Mask[0] < 2 && Mask[1] < 2);
3589   return false;
3590 }
3591
3592 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3593 /// is suitable for input to PSHUFHW.
3594 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3595   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3596     return false;
3597
3598   // Lower quadword copied in order or undef.
3599   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3600     return false;
3601
3602   // Upper quadword shuffled.
3603   for (unsigned i = 4; i != 8; ++i)
3604     if (!isUndefOrInRange(Mask[i], 4, 8))
3605       return false;
3606
3607   if (VT == MVT::v16i16) {
3608     // Lower quadword copied in order or undef.
3609     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3610       return false;
3611
3612     // Upper quadword shuffled.
3613     for (unsigned i = 12; i != 16; ++i)
3614       if (!isUndefOrInRange(Mask[i], 12, 16))
3615         return false;
3616   }
3617
3618   return true;
3619 }
3620
3621 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3622 /// is suitable for input to PSHUFLW.
3623 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3624   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3625     return false;
3626
3627   // Upper quadword copied in order.
3628   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3629     return false;
3630
3631   // Lower quadword shuffled.
3632   for (unsigned i = 0; i != 4; ++i)
3633     if (!isUndefOrInRange(Mask[i], 0, 4))
3634       return false;
3635
3636   if (VT == MVT::v16i16) {
3637     // Upper quadword copied in order.
3638     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3639       return false;
3640
3641     // Lower quadword shuffled.
3642     for (unsigned i = 8; i != 12; ++i)
3643       if (!isUndefOrInRange(Mask[i], 8, 12))
3644         return false;
3645   }
3646
3647   return true;
3648 }
3649
3650 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3651 /// is suitable for input to PALIGNR.
3652 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3653                           const X86Subtarget *Subtarget) {
3654   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3655       (VT.is256BitVector() && !Subtarget->hasInt256()))
3656     return false;
3657
3658   unsigned NumElts = VT.getVectorNumElements();
3659   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3660   unsigned NumLaneElts = NumElts/NumLanes;
3661
3662   // Do not handle 64-bit element shuffles with palignr.
3663   if (NumLaneElts == 2)
3664     return false;
3665
3666   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3667     unsigned i;
3668     for (i = 0; i != NumLaneElts; ++i) {
3669       if (Mask[i+l] >= 0)
3670         break;
3671     }
3672
3673     // Lane is all undef, go to next lane
3674     if (i == NumLaneElts)
3675       continue;
3676
3677     int Start = Mask[i+l];
3678
3679     // Make sure its in this lane in one of the sources
3680     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3681         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3682       return false;
3683
3684     // If not lane 0, then we must match lane 0
3685     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3686       return false;
3687
3688     // Correct second source to be contiguous with first source
3689     if (Start >= (int)NumElts)
3690       Start -= NumElts - NumLaneElts;
3691
3692     // Make sure we're shifting in the right direction.
3693     if (Start <= (int)(i+l))
3694       return false;
3695
3696     Start -= i;
3697
3698     // Check the rest of the elements to see if they are consecutive.
3699     for (++i; i != NumLaneElts; ++i) {
3700       int Idx = Mask[i+l];
3701
3702       // Make sure its in this lane
3703       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3704           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3705         return false;
3706
3707       // If not lane 0, then we must match lane 0
3708       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3709         return false;
3710
3711       if (Idx >= (int)NumElts)
3712         Idx -= NumElts - NumLaneElts;
3713
3714       if (!isUndefOrEqual(Idx, Start+i))
3715         return false;
3716
3717     }
3718   }
3719
3720   return true;
3721 }
3722
3723 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3724 /// the two vector operands have swapped position.
3725 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3726                                      unsigned NumElems) {
3727   for (unsigned i = 0; i != NumElems; ++i) {
3728     int idx = Mask[i];
3729     if (idx < 0)
3730       continue;
3731     else if (idx < (int)NumElems)
3732       Mask[i] = idx + NumElems;
3733     else
3734       Mask[i] = idx - NumElems;
3735   }
3736 }
3737
3738 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3739 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3740 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3741 /// reverse of what x86 shuffles want.
3742 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3743
3744   unsigned NumElems = VT.getVectorNumElements();
3745   unsigned NumLanes = VT.getSizeInBits()/128;
3746   unsigned NumLaneElems = NumElems/NumLanes;
3747
3748   if (NumLaneElems != 2 && NumLaneElems != 4)
3749     return false;
3750
3751   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3752   bool symetricMaskRequired =
3753     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3754
3755   // VSHUFPSY divides the resulting vector into 4 chunks.
3756   // The sources are also splitted into 4 chunks, and each destination
3757   // chunk must come from a different source chunk.
3758   //
3759   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3760   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3761   //
3762   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3763   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3764   //
3765   // VSHUFPDY divides the resulting vector into 4 chunks.
3766   // The sources are also splitted into 4 chunks, and each destination
3767   // chunk must come from a different source chunk.
3768   //
3769   //  SRC1 =>      X3       X2       X1       X0
3770   //  SRC2 =>      Y3       Y2       Y1       Y0
3771   //
3772   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3773   //
3774   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3775   unsigned HalfLaneElems = NumLaneElems/2;
3776   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3777     for (unsigned i = 0; i != NumLaneElems; ++i) {
3778       int Idx = Mask[i+l];
3779       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3780       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3781         return false;
3782       // For VSHUFPSY, the mask of the second half must be the same as the
3783       // first but with the appropriate offsets. This works in the same way as
3784       // VPERMILPS works with masks.
3785       if (!symetricMaskRequired || Idx < 0)
3786         continue;
3787       if (MaskVal[i] < 0) {
3788         MaskVal[i] = Idx - l;
3789         continue;
3790       }
3791       if ((signed)(Idx - l) != MaskVal[i])
3792         return false;
3793     }
3794   }
3795
3796   return true;
3797 }
3798
3799 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3800 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3801 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3802   if (!VT.is128BitVector())
3803     return false;
3804
3805   unsigned NumElems = VT.getVectorNumElements();
3806
3807   if (NumElems != 4)
3808     return false;
3809
3810   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3811   return isUndefOrEqual(Mask[0], 6) &&
3812          isUndefOrEqual(Mask[1], 7) &&
3813          isUndefOrEqual(Mask[2], 2) &&
3814          isUndefOrEqual(Mask[3], 3);
3815 }
3816
3817 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3818 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3819 /// <2, 3, 2, 3>
3820 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3821   if (!VT.is128BitVector())
3822     return false;
3823
3824   unsigned NumElems = VT.getVectorNumElements();
3825
3826   if (NumElems != 4)
3827     return false;
3828
3829   return isUndefOrEqual(Mask[0], 2) &&
3830          isUndefOrEqual(Mask[1], 3) &&
3831          isUndefOrEqual(Mask[2], 2) &&
3832          isUndefOrEqual(Mask[3], 3);
3833 }
3834
3835 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3836 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3837 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3838   if (!VT.is128BitVector())
3839     return false;
3840
3841   unsigned NumElems = VT.getVectorNumElements();
3842
3843   if (NumElems != 2 && NumElems != 4)
3844     return false;
3845
3846   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3847     if (!isUndefOrEqual(Mask[i], i + NumElems))
3848       return false;
3849
3850   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3851     if (!isUndefOrEqual(Mask[i], i))
3852       return false;
3853
3854   return true;
3855 }
3856
3857 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3858 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3859 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3860   if (!VT.is128BitVector())
3861     return false;
3862
3863   unsigned NumElems = VT.getVectorNumElements();
3864
3865   if (NumElems != 2 && NumElems != 4)
3866     return false;
3867
3868   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3869     if (!isUndefOrEqual(Mask[i], i))
3870       return false;
3871
3872   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3873     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3874       return false;
3875
3876   return true;
3877 }
3878
3879 //
3880 // Some special combinations that can be optimized.
3881 //
3882 static
3883 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3884                                SelectionDAG &DAG) {
3885   MVT VT = SVOp->getSimpleValueType(0);
3886   SDLoc dl(SVOp);
3887
3888   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3889     return SDValue();
3890
3891   ArrayRef<int> Mask = SVOp->getMask();
3892
3893   // These are the special masks that may be optimized.
3894   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3895   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3896   bool MatchEvenMask = true;
3897   bool MatchOddMask  = true;
3898   for (int i=0; i<8; ++i) {
3899     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3900       MatchEvenMask = false;
3901     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3902       MatchOddMask = false;
3903   }
3904
3905   if (!MatchEvenMask && !MatchOddMask)
3906     return SDValue();
3907
3908   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3909
3910   SDValue Op0 = SVOp->getOperand(0);
3911   SDValue Op1 = SVOp->getOperand(1);
3912
3913   if (MatchEvenMask) {
3914     // Shift the second operand right to 32 bits.
3915     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3916     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3917   } else {
3918     // Shift the first operand left to 32 bits.
3919     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3920     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3921   }
3922   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3923   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3924 }
3925
3926 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3927 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3928 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3929                          bool HasInt256, bool V2IsSplat = false) {
3930
3931   assert(VT.getSizeInBits() >= 128 &&
3932          "Unsupported vector type for unpckl");
3933
3934   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3935   unsigned NumLanes;
3936   unsigned NumOf256BitLanes;
3937   unsigned NumElts = VT.getVectorNumElements();
3938   if (VT.is256BitVector()) {
3939     if (NumElts != 4 && NumElts != 8 &&
3940         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3941     return false;
3942     NumLanes = 2;
3943     NumOf256BitLanes = 1;
3944   } else if (VT.is512BitVector()) {
3945     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3946            "Unsupported vector type for unpckh");
3947     NumLanes = 2;
3948     NumOf256BitLanes = 2;
3949   } else {
3950     NumLanes = 1;
3951     NumOf256BitLanes = 1;
3952   }
3953
3954   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3955   unsigned NumLaneElts = NumEltsInStride/NumLanes;
3956
3957   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
3958     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
3959       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3960         int BitI  = Mask[l256*NumEltsInStride+l+i];
3961         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
3962         if (!isUndefOrEqual(BitI, j+l256*NumElts))
3963           return false;
3964         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
3965           return false;
3966         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
3967           return false;
3968       }
3969     }
3970   }
3971   return true;
3972 }
3973
3974 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3975 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3976 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3977                          bool HasInt256, bool V2IsSplat = false) {
3978   assert(VT.getSizeInBits() >= 128 &&
3979          "Unsupported vector type for unpckh");
3980
3981   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3982   unsigned NumLanes;
3983   unsigned NumOf256BitLanes;
3984   unsigned NumElts = VT.getVectorNumElements();
3985   if (VT.is256BitVector()) {
3986     if (NumElts != 4 && NumElts != 8 &&
3987         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3988     return false;
3989     NumLanes = 2;
3990     NumOf256BitLanes = 1;
3991   } else if (VT.is512BitVector()) {
3992     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3993            "Unsupported vector type for unpckh");
3994     NumLanes = 2;
3995     NumOf256BitLanes = 2;
3996   } else {
3997     NumLanes = 1;
3998     NumOf256BitLanes = 1;
3999   }
4000
4001   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4002   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4003
4004   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4005     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4006       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4007         int BitI  = Mask[l256*NumEltsInStride+l+i];
4008         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4009         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4010           return false;
4011         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4012           return false;
4013         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4014           return false;
4015       }
4016     }
4017   }
4018   return true;
4019 }
4020
4021 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4022 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4023 /// <0, 0, 1, 1>
4024 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4025   unsigned NumElts = VT.getVectorNumElements();
4026   bool Is256BitVec = VT.is256BitVector();
4027
4028   if (VT.is512BitVector())
4029     return false;
4030   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4031          "Unsupported vector type for unpckh");
4032
4033   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4034       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4035     return false;
4036
4037   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4038   // FIXME: Need a better way to get rid of this, there's no latency difference
4039   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4040   // the former later. We should also remove the "_undef" special mask.
4041   if (NumElts == 4 && Is256BitVec)
4042     return false;
4043
4044   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4045   // independently on 128-bit lanes.
4046   unsigned NumLanes = VT.getSizeInBits()/128;
4047   unsigned NumLaneElts = NumElts/NumLanes;
4048
4049   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4050     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4051       int BitI  = Mask[l+i];
4052       int BitI1 = Mask[l+i+1];
4053
4054       if (!isUndefOrEqual(BitI, j))
4055         return false;
4056       if (!isUndefOrEqual(BitI1, j))
4057         return false;
4058     }
4059   }
4060
4061   return true;
4062 }
4063
4064 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4065 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4066 /// <2, 2, 3, 3>
4067 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4068   unsigned NumElts = VT.getVectorNumElements();
4069
4070   if (VT.is512BitVector())
4071     return false;
4072
4073   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4074          "Unsupported vector type for unpckh");
4075
4076   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4077       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4078     return false;
4079
4080   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4081   // independently on 128-bit lanes.
4082   unsigned NumLanes = VT.getSizeInBits()/128;
4083   unsigned NumLaneElts = NumElts/NumLanes;
4084
4085   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4086     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4087       int BitI  = Mask[l+i];
4088       int BitI1 = Mask[l+i+1];
4089       if (!isUndefOrEqual(BitI, j))
4090         return false;
4091       if (!isUndefOrEqual(BitI1, j))
4092         return false;
4093     }
4094   }
4095   return true;
4096 }
4097
4098 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4099 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4100 /// MOVSD, and MOVD, i.e. setting the lowest element.
4101 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4102   if (VT.getVectorElementType().getSizeInBits() < 32)
4103     return false;
4104   if (!VT.is128BitVector())
4105     return false;
4106
4107   unsigned NumElts = VT.getVectorNumElements();
4108
4109   if (!isUndefOrEqual(Mask[0], NumElts))
4110     return false;
4111
4112   for (unsigned i = 1; i != NumElts; ++i)
4113     if (!isUndefOrEqual(Mask[i], i))
4114       return false;
4115
4116   return true;
4117 }
4118
4119 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4120 /// as permutations between 128-bit chunks or halves. As an example: this
4121 /// shuffle bellow:
4122 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4123 /// The first half comes from the second half of V1 and the second half from the
4124 /// the second half of V2.
4125 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4126   if (!HasFp256 || !VT.is256BitVector())
4127     return false;
4128
4129   // The shuffle result is divided into half A and half B. In total the two
4130   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4131   // B must come from C, D, E or F.
4132   unsigned HalfSize = VT.getVectorNumElements()/2;
4133   bool MatchA = false, MatchB = false;
4134
4135   // Check if A comes from one of C, D, E, F.
4136   for (unsigned Half = 0; Half != 4; ++Half) {
4137     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4138       MatchA = true;
4139       break;
4140     }
4141   }
4142
4143   // Check if B comes from one of C, D, E, F.
4144   for (unsigned Half = 0; Half != 4; ++Half) {
4145     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4146       MatchB = true;
4147       break;
4148     }
4149   }
4150
4151   return MatchA && MatchB;
4152 }
4153
4154 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4155 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4156 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4157   MVT VT = SVOp->getSimpleValueType(0);
4158
4159   unsigned HalfSize = VT.getVectorNumElements()/2;
4160
4161   unsigned FstHalf = 0, SndHalf = 0;
4162   for (unsigned i = 0; i < HalfSize; ++i) {
4163     if (SVOp->getMaskElt(i) > 0) {
4164       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4165       break;
4166     }
4167   }
4168   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4169     if (SVOp->getMaskElt(i) > 0) {
4170       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4171       break;
4172     }
4173   }
4174
4175   return (FstHalf | (SndHalf << 4));
4176 }
4177
4178 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4179 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4180   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4181   if (EltSize < 32)
4182     return false;
4183
4184   unsigned NumElts = VT.getVectorNumElements();
4185   Imm8 = 0;
4186   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4187     for (unsigned i = 0; i != NumElts; ++i) {
4188       if (Mask[i] < 0)
4189         continue;
4190       Imm8 |= Mask[i] << (i*2);
4191     }
4192     return true;
4193   }
4194
4195   unsigned LaneSize = 4;
4196   SmallVector<int, 4> MaskVal(LaneSize, -1);
4197
4198   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4199     for (unsigned i = 0; i != LaneSize; ++i) {
4200       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4201         return false;
4202       if (Mask[i+l] < 0)
4203         continue;
4204       if (MaskVal[i] < 0) {
4205         MaskVal[i] = Mask[i+l] - l;
4206         Imm8 |= MaskVal[i] << (i*2);
4207         continue;
4208       }
4209       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4210         return false;
4211     }
4212   }
4213   return true;
4214 }
4215
4216 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4217 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4218 /// Note that VPERMIL mask matching is different depending whether theunderlying
4219 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4220 /// to the same elements of the low, but to the higher half of the source.
4221 /// In VPERMILPD the two lanes could be shuffled independently of each other
4222 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4223 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4224   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4225   if (VT.getSizeInBits() < 256 || EltSize < 32)
4226     return false;
4227   bool symetricMaskRequired = (EltSize == 32);
4228   unsigned NumElts = VT.getVectorNumElements();
4229
4230   unsigned NumLanes = VT.getSizeInBits()/128;
4231   unsigned LaneSize = NumElts/NumLanes;
4232   // 2 or 4 elements in one lane
4233
4234   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4235   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4236     for (unsigned i = 0; i != LaneSize; ++i) {
4237       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4238         return false;
4239       if (symetricMaskRequired) {
4240         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4241           ExpectedMaskVal[i] = Mask[i+l] - l;
4242           continue;
4243         }
4244         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4245           return false;
4246       }
4247     }
4248   }
4249   return true;
4250 }
4251
4252 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4253 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4254 /// element of vector 2 and the other elements to come from vector 1 in order.
4255 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4256                                bool V2IsSplat = false, bool V2IsUndef = false) {
4257   if (!VT.is128BitVector())
4258     return false;
4259
4260   unsigned NumOps = VT.getVectorNumElements();
4261   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4262     return false;
4263
4264   if (!isUndefOrEqual(Mask[0], 0))
4265     return false;
4266
4267   for (unsigned i = 1; i != NumOps; ++i)
4268     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4269           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4270           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4271       return false;
4272
4273   return true;
4274 }
4275
4276 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4277 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4278 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4279 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4280                            const X86Subtarget *Subtarget) {
4281   if (!Subtarget->hasSSE3())
4282     return false;
4283
4284   unsigned NumElems = VT.getVectorNumElements();
4285
4286   if ((VT.is128BitVector() && NumElems != 4) ||
4287       (VT.is256BitVector() && NumElems != 8) ||
4288       (VT.is512BitVector() && NumElems != 16))
4289     return false;
4290
4291   // "i+1" is the value the indexed mask element must have
4292   for (unsigned i = 0; i != NumElems; i += 2)
4293     if (!isUndefOrEqual(Mask[i], i+1) ||
4294         !isUndefOrEqual(Mask[i+1], i+1))
4295       return false;
4296
4297   return true;
4298 }
4299
4300 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4301 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4302 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4303 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4304                            const X86Subtarget *Subtarget) {
4305   if (!Subtarget->hasSSE3())
4306     return false;
4307
4308   unsigned NumElems = VT.getVectorNumElements();
4309
4310   if ((VT.is128BitVector() && NumElems != 4) ||
4311       (VT.is256BitVector() && NumElems != 8) ||
4312       (VT.is512BitVector() && NumElems != 16))
4313     return false;
4314
4315   // "i" is the value the indexed mask element must have
4316   for (unsigned i = 0; i != NumElems; i += 2)
4317     if (!isUndefOrEqual(Mask[i], i) ||
4318         !isUndefOrEqual(Mask[i+1], i))
4319       return false;
4320
4321   return true;
4322 }
4323
4324 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4325 /// specifies a shuffle of elements that is suitable for input to 256-bit
4326 /// version of MOVDDUP.
4327 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4328   if (!HasFp256 || !VT.is256BitVector())
4329     return false;
4330
4331   unsigned NumElts = VT.getVectorNumElements();
4332   if (NumElts != 4)
4333     return false;
4334
4335   for (unsigned i = 0; i != NumElts/2; ++i)
4336     if (!isUndefOrEqual(Mask[i], 0))
4337       return false;
4338   for (unsigned i = NumElts/2; i != NumElts; ++i)
4339     if (!isUndefOrEqual(Mask[i], NumElts/2))
4340       return false;
4341   return true;
4342 }
4343
4344 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4345 /// specifies a shuffle of elements that is suitable for input to 128-bit
4346 /// version of MOVDDUP.
4347 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4348   if (!VT.is128BitVector())
4349     return false;
4350
4351   unsigned e = VT.getVectorNumElements() / 2;
4352   for (unsigned i = 0; i != e; ++i)
4353     if (!isUndefOrEqual(Mask[i], i))
4354       return false;
4355   for (unsigned i = 0; i != e; ++i)
4356     if (!isUndefOrEqual(Mask[e+i], i))
4357       return false;
4358   return true;
4359 }
4360
4361 /// isVEXTRACTIndex - Return true if the specified
4362 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4363 /// suitable for instruction that extract 128 or 256 bit vectors
4364 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4365   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4366   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4367     return false;
4368
4369   // The index should be aligned on a vecWidth-bit boundary.
4370   uint64_t Index =
4371     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4372
4373   MVT VT = N->getSimpleValueType(0);
4374   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4375   bool Result = (Index * ElSize) % vecWidth == 0;
4376
4377   return Result;
4378 }
4379
4380 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4381 /// operand specifies a subvector insert that is suitable for input to
4382 /// insertion of 128 or 256-bit subvectors
4383 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4384   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4385   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4386     return false;
4387   // The index should be aligned on a vecWidth-bit boundary.
4388   uint64_t Index =
4389     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4390
4391   MVT VT = N->getSimpleValueType(0);
4392   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4393   bool Result = (Index * ElSize) % vecWidth == 0;
4394
4395   return Result;
4396 }
4397
4398 bool X86::isVINSERT128Index(SDNode *N) {
4399   return isVINSERTIndex(N, 128);
4400 }
4401
4402 bool X86::isVINSERT256Index(SDNode *N) {
4403   return isVINSERTIndex(N, 256);
4404 }
4405
4406 bool X86::isVEXTRACT128Index(SDNode *N) {
4407   return isVEXTRACTIndex(N, 128);
4408 }
4409
4410 bool X86::isVEXTRACT256Index(SDNode *N) {
4411   return isVEXTRACTIndex(N, 256);
4412 }
4413
4414 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4415 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4416 /// Handles 128-bit and 256-bit.
4417 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4418   MVT VT = N->getSimpleValueType(0);
4419
4420   assert((VT.getSizeInBits() >= 128) &&
4421          "Unsupported vector type for PSHUF/SHUFP");
4422
4423   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4424   // independently on 128-bit lanes.
4425   unsigned NumElts = VT.getVectorNumElements();
4426   unsigned NumLanes = VT.getSizeInBits()/128;
4427   unsigned NumLaneElts = NumElts/NumLanes;
4428
4429   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4430          "Only supports 2, 4 or 8 elements per lane");
4431
4432   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4433   unsigned Mask = 0;
4434   for (unsigned i = 0; i != NumElts; ++i) {
4435     int Elt = N->getMaskElt(i);
4436     if (Elt < 0) continue;
4437     Elt &= NumLaneElts - 1;
4438     unsigned ShAmt = (i << Shift) % 8;
4439     Mask |= Elt << ShAmt;
4440   }
4441
4442   return Mask;
4443 }
4444
4445 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4446 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4447 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4448   MVT VT = N->getSimpleValueType(0);
4449
4450   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4451          "Unsupported vector type for PSHUFHW");
4452
4453   unsigned NumElts = VT.getVectorNumElements();
4454
4455   unsigned Mask = 0;
4456   for (unsigned l = 0; l != NumElts; l += 8) {
4457     // 8 nodes per lane, but we only care about the last 4.
4458     for (unsigned i = 0; i < 4; ++i) {
4459       int Elt = N->getMaskElt(l+i+4);
4460       if (Elt < 0) continue;
4461       Elt &= 0x3; // only 2-bits.
4462       Mask |= Elt << (i * 2);
4463     }
4464   }
4465
4466   return Mask;
4467 }
4468
4469 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4470 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4471 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4472   MVT VT = N->getSimpleValueType(0);
4473
4474   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4475          "Unsupported vector type for PSHUFHW");
4476
4477   unsigned NumElts = VT.getVectorNumElements();
4478
4479   unsigned Mask = 0;
4480   for (unsigned l = 0; l != NumElts; l += 8) {
4481     // 8 nodes per lane, but we only care about the first 4.
4482     for (unsigned i = 0; i < 4; ++i) {
4483       int Elt = N->getMaskElt(l+i);
4484       if (Elt < 0) continue;
4485       Elt &= 0x3; // only 2-bits
4486       Mask |= Elt << (i * 2);
4487     }
4488   }
4489
4490   return Mask;
4491 }
4492
4493 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4494 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4495 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4496   MVT VT = SVOp->getSimpleValueType(0);
4497   unsigned EltSize = VT.is512BitVector() ? 1 :
4498     VT.getVectorElementType().getSizeInBits() >> 3;
4499
4500   unsigned NumElts = VT.getVectorNumElements();
4501   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4502   unsigned NumLaneElts = NumElts/NumLanes;
4503
4504   int Val = 0;
4505   unsigned i;
4506   for (i = 0; i != NumElts; ++i) {
4507     Val = SVOp->getMaskElt(i);
4508     if (Val >= 0)
4509       break;
4510   }
4511   if (Val >= (int)NumElts)
4512     Val -= NumElts - NumLaneElts;
4513
4514   assert(Val - i > 0 && "PALIGNR imm should be positive");
4515   return (Val - i) * EltSize;
4516 }
4517
4518 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4519   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4520   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4521     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4522
4523   uint64_t Index =
4524     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4525
4526   MVT VecVT = N->getOperand(0).getSimpleValueType();
4527   MVT ElVT = VecVT.getVectorElementType();
4528
4529   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4530   return Index / NumElemsPerChunk;
4531 }
4532
4533 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4534   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4535   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4536     llvm_unreachable("Illegal insert subvector for VINSERT");
4537
4538   uint64_t Index =
4539     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4540
4541   MVT VecVT = N->getSimpleValueType(0);
4542   MVT ElVT = VecVT.getVectorElementType();
4543
4544   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4545   return Index / NumElemsPerChunk;
4546 }
4547
4548 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4549 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4550 /// and VINSERTI128 instructions.
4551 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4552   return getExtractVEXTRACTImmediate(N, 128);
4553 }
4554
4555 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4556 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4557 /// and VINSERTI64x4 instructions.
4558 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4559   return getExtractVEXTRACTImmediate(N, 256);
4560 }
4561
4562 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4563 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4564 /// and VINSERTI128 instructions.
4565 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4566   return getInsertVINSERTImmediate(N, 128);
4567 }
4568
4569 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4570 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4571 /// and VINSERTI64x4 instructions.
4572 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4573   return getInsertVINSERTImmediate(N, 256);
4574 }
4575
4576 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4577 /// constant +0.0.
4578 bool X86::isZeroNode(SDValue Elt) {
4579   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4580     return CN->isNullValue();
4581   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4582     return CFP->getValueAPF().isPosZero();
4583   return false;
4584 }
4585
4586 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4587 /// their permute mask.
4588 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4589                                     SelectionDAG &DAG) {
4590   MVT VT = SVOp->getSimpleValueType(0);
4591   unsigned NumElems = VT.getVectorNumElements();
4592   SmallVector<int, 8> MaskVec;
4593
4594   for (unsigned i = 0; i != NumElems; ++i) {
4595     int Idx = SVOp->getMaskElt(i);
4596     if (Idx >= 0) {
4597       if (Idx < (int)NumElems)
4598         Idx += NumElems;
4599       else
4600         Idx -= NumElems;
4601     }
4602     MaskVec.push_back(Idx);
4603   }
4604   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4605                               SVOp->getOperand(0), &MaskVec[0]);
4606 }
4607
4608 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4609 /// match movhlps. The lower half elements should come from upper half of
4610 /// V1 (and in order), and the upper half elements should come from the upper
4611 /// half of V2 (and in order).
4612 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4613   if (!VT.is128BitVector())
4614     return false;
4615   if (VT.getVectorNumElements() != 4)
4616     return false;
4617   for (unsigned i = 0, e = 2; i != e; ++i)
4618     if (!isUndefOrEqual(Mask[i], i+2))
4619       return false;
4620   for (unsigned i = 2; i != 4; ++i)
4621     if (!isUndefOrEqual(Mask[i], i+4))
4622       return false;
4623   return true;
4624 }
4625
4626 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4627 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4628 /// required.
4629 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4630   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4631     return false;
4632   N = N->getOperand(0).getNode();
4633   if (!ISD::isNON_EXTLoad(N))
4634     return false;
4635   if (LD)
4636     *LD = cast<LoadSDNode>(N);
4637   return true;
4638 }
4639
4640 // Test whether the given value is a vector value which will be legalized
4641 // into a load.
4642 static bool WillBeConstantPoolLoad(SDNode *N) {
4643   if (N->getOpcode() != ISD::BUILD_VECTOR)
4644     return false;
4645
4646   // Check for any non-constant elements.
4647   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4648     switch (N->getOperand(i).getNode()->getOpcode()) {
4649     case ISD::UNDEF:
4650     case ISD::ConstantFP:
4651     case ISD::Constant:
4652       break;
4653     default:
4654       return false;
4655     }
4656
4657   // Vectors of all-zeros and all-ones are materialized with special
4658   // instructions rather than being loaded.
4659   return !ISD::isBuildVectorAllZeros(N) &&
4660          !ISD::isBuildVectorAllOnes(N);
4661 }
4662
4663 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4664 /// match movlp{s|d}. The lower half elements should come from lower half of
4665 /// V1 (and in order), and the upper half elements should come from the upper
4666 /// half of V2 (and in order). And since V1 will become the source of the
4667 /// MOVLP, it must be either a vector load or a scalar load to vector.
4668 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4669                                ArrayRef<int> Mask, MVT VT) {
4670   if (!VT.is128BitVector())
4671     return false;
4672
4673   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4674     return false;
4675   // Is V2 is a vector load, don't do this transformation. We will try to use
4676   // load folding shufps op.
4677   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4678     return false;
4679
4680   unsigned NumElems = VT.getVectorNumElements();
4681
4682   if (NumElems != 2 && NumElems != 4)
4683     return false;
4684   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4685     if (!isUndefOrEqual(Mask[i], i))
4686       return false;
4687   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4688     if (!isUndefOrEqual(Mask[i], i+NumElems))
4689       return false;
4690   return true;
4691 }
4692
4693 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4694 /// all the same.
4695 static bool isSplatVector(SDNode *N) {
4696   if (N->getOpcode() != ISD::BUILD_VECTOR)
4697     return false;
4698
4699   SDValue SplatValue = N->getOperand(0);
4700   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4701     if (N->getOperand(i) != SplatValue)
4702       return false;
4703   return true;
4704 }
4705
4706 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4707 /// to an zero vector.
4708 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4709 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4710   SDValue V1 = N->getOperand(0);
4711   SDValue V2 = N->getOperand(1);
4712   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4713   for (unsigned i = 0; i != NumElems; ++i) {
4714     int Idx = N->getMaskElt(i);
4715     if (Idx >= (int)NumElems) {
4716       unsigned Opc = V2.getOpcode();
4717       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4718         continue;
4719       if (Opc != ISD::BUILD_VECTOR ||
4720           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4721         return false;
4722     } else if (Idx >= 0) {
4723       unsigned Opc = V1.getOpcode();
4724       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4725         continue;
4726       if (Opc != ISD::BUILD_VECTOR ||
4727           !X86::isZeroNode(V1.getOperand(Idx)))
4728         return false;
4729     }
4730   }
4731   return true;
4732 }
4733
4734 /// getZeroVector - Returns a vector of specified type with all zero elements.
4735 ///
4736 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4737                              SelectionDAG &DAG, SDLoc dl) {
4738   assert(VT.isVector() && "Expected a vector type");
4739
4740   // Always build SSE zero vectors as <4 x i32> bitcasted
4741   // to their dest type. This ensures they get CSE'd.
4742   SDValue Vec;
4743   if (VT.is128BitVector()) {  // SSE
4744     if (Subtarget->hasSSE2()) {  // SSE2
4745       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4746       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4747     } else { // SSE1
4748       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4749       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4750     }
4751   } else if (VT.is256BitVector()) { // AVX
4752     if (Subtarget->hasInt256()) { // AVX2
4753       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4754       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4755       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4756                         array_lengthof(Ops));
4757     } else {
4758       // 256-bit logic and arithmetic instructions in AVX are all
4759       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4760       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4761       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4762       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4763                         array_lengthof(Ops));
4764     }
4765   } else if (VT.is512BitVector()) { // AVX-512
4766       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4767       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4768                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4769       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4770   } else
4771     llvm_unreachable("Unexpected vector type");
4772
4773   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4774 }
4775
4776 /// getOnesVector - Returns a vector of specified type with all bits set.
4777 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4778 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4779 /// Then bitcast to their original type, ensuring they get CSE'd.
4780 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4781                              SDLoc dl) {
4782   assert(VT.isVector() && "Expected a vector type");
4783
4784   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4785   SDValue Vec;
4786   if (VT.is256BitVector()) {
4787     if (HasInt256) { // AVX2
4788       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4789       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4790                         array_lengthof(Ops));
4791     } else { // AVX
4792       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4793       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4794     }
4795   } else if (VT.is128BitVector()) {
4796     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4797   } else
4798     llvm_unreachable("Unexpected vector type");
4799
4800   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4801 }
4802
4803 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4804 /// that point to V2 points to its first element.
4805 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4806   for (unsigned i = 0; i != NumElems; ++i) {
4807     if (Mask[i] > (int)NumElems) {
4808       Mask[i] = NumElems;
4809     }
4810   }
4811 }
4812
4813 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4814 /// operation of specified width.
4815 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4816                        SDValue V2) {
4817   unsigned NumElems = VT.getVectorNumElements();
4818   SmallVector<int, 8> Mask;
4819   Mask.push_back(NumElems);
4820   for (unsigned i = 1; i != NumElems; ++i)
4821     Mask.push_back(i);
4822   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4823 }
4824
4825 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4826 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4827                           SDValue V2) {
4828   unsigned NumElems = VT.getVectorNumElements();
4829   SmallVector<int, 8> Mask;
4830   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4831     Mask.push_back(i);
4832     Mask.push_back(i + NumElems);
4833   }
4834   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4835 }
4836
4837 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4838 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4839                           SDValue V2) {
4840   unsigned NumElems = VT.getVectorNumElements();
4841   SmallVector<int, 8> Mask;
4842   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4843     Mask.push_back(i + Half);
4844     Mask.push_back(i + NumElems + Half);
4845   }
4846   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4847 }
4848
4849 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4850 // a generic shuffle instruction because the target has no such instructions.
4851 // Generate shuffles which repeat i16 and i8 several times until they can be
4852 // represented by v4f32 and then be manipulated by target suported shuffles.
4853 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4854   MVT VT = V.getSimpleValueType();
4855   int NumElems = VT.getVectorNumElements();
4856   SDLoc dl(V);
4857
4858   while (NumElems > 4) {
4859     if (EltNo < NumElems/2) {
4860       V = getUnpackl(DAG, dl, VT, V, V);
4861     } else {
4862       V = getUnpackh(DAG, dl, VT, V, V);
4863       EltNo -= NumElems/2;
4864     }
4865     NumElems >>= 1;
4866   }
4867   return V;
4868 }
4869
4870 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4871 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4872   MVT VT = V.getSimpleValueType();
4873   SDLoc dl(V);
4874
4875   if (VT.is128BitVector()) {
4876     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4877     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4878     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4879                              &SplatMask[0]);
4880   } else if (VT.is256BitVector()) {
4881     // To use VPERMILPS to splat scalars, the second half of indicies must
4882     // refer to the higher part, which is a duplication of the lower one,
4883     // because VPERMILPS can only handle in-lane permutations.
4884     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4885                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4886
4887     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4888     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4889                              &SplatMask[0]);
4890   } else
4891     llvm_unreachable("Vector size not supported");
4892
4893   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4894 }
4895
4896 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4897 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4898   MVT SrcVT = SV->getSimpleValueType(0);
4899   SDValue V1 = SV->getOperand(0);
4900   SDLoc dl(SV);
4901
4902   int EltNo = SV->getSplatIndex();
4903   int NumElems = SrcVT.getVectorNumElements();
4904   bool Is256BitVec = SrcVT.is256BitVector();
4905
4906   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4907          "Unknown how to promote splat for type");
4908
4909   // Extract the 128-bit part containing the splat element and update
4910   // the splat element index when it refers to the higher register.
4911   if (Is256BitVec) {
4912     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4913     if (EltNo >= NumElems/2)
4914       EltNo -= NumElems/2;
4915   }
4916
4917   // All i16 and i8 vector types can't be used directly by a generic shuffle
4918   // instruction because the target has no such instruction. Generate shuffles
4919   // which repeat i16 and i8 several times until they fit in i32, and then can
4920   // be manipulated by target suported shuffles.
4921   MVT EltVT = SrcVT.getVectorElementType();
4922   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4923     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4924
4925   // Recreate the 256-bit vector and place the same 128-bit vector
4926   // into the low and high part. This is necessary because we want
4927   // to use VPERM* to shuffle the vectors
4928   if (Is256BitVec) {
4929     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4930   }
4931
4932   return getLegalSplat(DAG, V1, EltNo);
4933 }
4934
4935 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4936 /// vector of zero or undef vector.  This produces a shuffle where the low
4937 /// element of V2 is swizzled into the zero/undef vector, landing at element
4938 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4939 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4940                                            bool IsZero,
4941                                            const X86Subtarget *Subtarget,
4942                                            SelectionDAG &DAG) {
4943   MVT VT = V2.getSimpleValueType();
4944   SDValue V1 = IsZero
4945     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4946   unsigned NumElems = VT.getVectorNumElements();
4947   SmallVector<int, 16> MaskVec;
4948   for (unsigned i = 0; i != NumElems; ++i)
4949     // If this is the insertion idx, put the low elt of V2 here.
4950     MaskVec.push_back(i == Idx ? NumElems : i);
4951   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4952 }
4953
4954 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4955 /// target specific opcode. Returns true if the Mask could be calculated.
4956 /// Sets IsUnary to true if only uses one source.
4957 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4958                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4959   unsigned NumElems = VT.getVectorNumElements();
4960   SDValue ImmN;
4961
4962   IsUnary = false;
4963   switch(N->getOpcode()) {
4964   case X86ISD::SHUFP:
4965     ImmN = N->getOperand(N->getNumOperands()-1);
4966     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4967     break;
4968   case X86ISD::UNPCKH:
4969     DecodeUNPCKHMask(VT, Mask);
4970     break;
4971   case X86ISD::UNPCKL:
4972     DecodeUNPCKLMask(VT, Mask);
4973     break;
4974   case X86ISD::MOVHLPS:
4975     DecodeMOVHLPSMask(NumElems, Mask);
4976     break;
4977   case X86ISD::MOVLHPS:
4978     DecodeMOVLHPSMask(NumElems, Mask);
4979     break;
4980   case X86ISD::PALIGNR:
4981     ImmN = N->getOperand(N->getNumOperands()-1);
4982     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4983     break;
4984   case X86ISD::PSHUFD:
4985   case X86ISD::VPERMILP:
4986     ImmN = N->getOperand(N->getNumOperands()-1);
4987     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4988     IsUnary = true;
4989     break;
4990   case X86ISD::PSHUFHW:
4991     ImmN = N->getOperand(N->getNumOperands()-1);
4992     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4993     IsUnary = true;
4994     break;
4995   case X86ISD::PSHUFLW:
4996     ImmN = N->getOperand(N->getNumOperands()-1);
4997     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4998     IsUnary = true;
4999     break;
5000   case X86ISD::VPERMI:
5001     ImmN = N->getOperand(N->getNumOperands()-1);
5002     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5003     IsUnary = true;
5004     break;
5005   case X86ISD::MOVSS:
5006   case X86ISD::MOVSD: {
5007     // The index 0 always comes from the first element of the second source,
5008     // this is why MOVSS and MOVSD are used in the first place. The other
5009     // elements come from the other positions of the first source vector
5010     Mask.push_back(NumElems);
5011     for (unsigned i = 1; i != NumElems; ++i) {
5012       Mask.push_back(i);
5013     }
5014     break;
5015   }
5016   case X86ISD::VPERM2X128:
5017     ImmN = N->getOperand(N->getNumOperands()-1);
5018     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5019     if (Mask.empty()) return false;
5020     break;
5021   case X86ISD::MOVDDUP:
5022   case X86ISD::MOVLHPD:
5023   case X86ISD::MOVLPD:
5024   case X86ISD::MOVLPS:
5025   case X86ISD::MOVSHDUP:
5026   case X86ISD::MOVSLDUP:
5027     // Not yet implemented
5028     return false;
5029   default: llvm_unreachable("unknown target shuffle node");
5030   }
5031
5032   return true;
5033 }
5034
5035 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5036 /// element of the result of the vector shuffle.
5037 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5038                                    unsigned Depth) {
5039   if (Depth == 6)
5040     return SDValue();  // Limit search depth.
5041
5042   SDValue V = SDValue(N, 0);
5043   EVT VT = V.getValueType();
5044   unsigned Opcode = V.getOpcode();
5045
5046   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5047   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5048     int Elt = SV->getMaskElt(Index);
5049
5050     if (Elt < 0)
5051       return DAG.getUNDEF(VT.getVectorElementType());
5052
5053     unsigned NumElems = VT.getVectorNumElements();
5054     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5055                                          : SV->getOperand(1);
5056     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5057   }
5058
5059   // Recurse into target specific vector shuffles to find scalars.
5060   if (isTargetShuffle(Opcode)) {
5061     MVT ShufVT = V.getSimpleValueType();
5062     unsigned NumElems = ShufVT.getVectorNumElements();
5063     SmallVector<int, 16> ShuffleMask;
5064     bool IsUnary;
5065
5066     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5067       return SDValue();
5068
5069     int Elt = ShuffleMask[Index];
5070     if (Elt < 0)
5071       return DAG.getUNDEF(ShufVT.getVectorElementType());
5072
5073     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5074                                          : N->getOperand(1);
5075     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5076                                Depth+1);
5077   }
5078
5079   // Actual nodes that may contain scalar elements
5080   if (Opcode == ISD::BITCAST) {
5081     V = V.getOperand(0);
5082     EVT SrcVT = V.getValueType();
5083     unsigned NumElems = VT.getVectorNumElements();
5084
5085     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5086       return SDValue();
5087   }
5088
5089   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5090     return (Index == 0) ? V.getOperand(0)
5091                         : DAG.getUNDEF(VT.getVectorElementType());
5092
5093   if (V.getOpcode() == ISD::BUILD_VECTOR)
5094     return V.getOperand(Index);
5095
5096   return SDValue();
5097 }
5098
5099 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5100 /// shuffle operation which come from a consecutively from a zero. The
5101 /// search can start in two different directions, from left or right.
5102 /// We count undefs as zeros until PreferredNum is reached.
5103 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5104                                          unsigned NumElems, bool ZerosFromLeft,
5105                                          SelectionDAG &DAG,
5106                                          unsigned PreferredNum = -1U) {
5107   unsigned NumZeros = 0;
5108   for (unsigned i = 0; i != NumElems; ++i) {
5109     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5110     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5111     if (!Elt.getNode())
5112       break;
5113
5114     if (X86::isZeroNode(Elt))
5115       ++NumZeros;
5116     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5117       NumZeros = std::min(NumZeros + 1, PreferredNum);
5118     else
5119       break;
5120   }
5121
5122   return NumZeros;
5123 }
5124
5125 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5126 /// correspond consecutively to elements from one of the vector operands,
5127 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5128 static
5129 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5130                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5131                               unsigned NumElems, unsigned &OpNum) {
5132   bool SeenV1 = false;
5133   bool SeenV2 = false;
5134
5135   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5136     int Idx = SVOp->getMaskElt(i);
5137     // Ignore undef indicies
5138     if (Idx < 0)
5139       continue;
5140
5141     if (Idx < (int)NumElems)
5142       SeenV1 = true;
5143     else
5144       SeenV2 = true;
5145
5146     // Only accept consecutive elements from the same vector
5147     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5148       return false;
5149   }
5150
5151   OpNum = SeenV1 ? 0 : 1;
5152   return true;
5153 }
5154
5155 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5156 /// logical left shift of a vector.
5157 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5158                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5159   unsigned NumElems =
5160     SVOp->getSimpleValueType(0).getVectorNumElements();
5161   unsigned NumZeros = getNumOfConsecutiveZeros(
5162       SVOp, NumElems, false /* check zeros from right */, DAG,
5163       SVOp->getMaskElt(0));
5164   unsigned OpSrc;
5165
5166   if (!NumZeros)
5167     return false;
5168
5169   // Considering the elements in the mask that are not consecutive zeros,
5170   // check if they consecutively come from only one of the source vectors.
5171   //
5172   //               V1 = {X, A, B, C}     0
5173   //                         \  \  \    /
5174   //   vector_shuffle V1, V2 <1, 2, 3, X>
5175   //
5176   if (!isShuffleMaskConsecutive(SVOp,
5177             0,                   // Mask Start Index
5178             NumElems-NumZeros,   // Mask End Index(exclusive)
5179             NumZeros,            // Where to start looking in the src vector
5180             NumElems,            // Number of elements in vector
5181             OpSrc))              // Which source operand ?
5182     return false;
5183
5184   isLeft = false;
5185   ShAmt = NumZeros;
5186   ShVal = SVOp->getOperand(OpSrc);
5187   return true;
5188 }
5189
5190 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5191 /// logical left shift of a vector.
5192 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5193                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5194   unsigned NumElems =
5195     SVOp->getSimpleValueType(0).getVectorNumElements();
5196   unsigned NumZeros = getNumOfConsecutiveZeros(
5197       SVOp, NumElems, true /* check zeros from left */, DAG,
5198       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5199   unsigned OpSrc;
5200
5201   if (!NumZeros)
5202     return false;
5203
5204   // Considering the elements in the mask that are not consecutive zeros,
5205   // check if they consecutively come from only one of the source vectors.
5206   //
5207   //                           0    { A, B, X, X } = V2
5208   //                          / \    /  /
5209   //   vector_shuffle V1, V2 <X, X, 4, 5>
5210   //
5211   if (!isShuffleMaskConsecutive(SVOp,
5212             NumZeros,     // Mask Start Index
5213             NumElems,     // Mask End Index(exclusive)
5214             0,            // Where to start looking in the src vector
5215             NumElems,     // Number of elements in vector
5216             OpSrc))       // Which source operand ?
5217     return false;
5218
5219   isLeft = true;
5220   ShAmt = NumZeros;
5221   ShVal = SVOp->getOperand(OpSrc);
5222   return true;
5223 }
5224
5225 /// isVectorShift - Returns true if the shuffle can be implemented as a
5226 /// logical left or right shift of a vector.
5227 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5228                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5229   // Although the logic below support any bitwidth size, there are no
5230   // shift instructions which handle more than 128-bit vectors.
5231   if (!SVOp->getSimpleValueType(0).is128BitVector())
5232     return false;
5233
5234   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5235       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5236     return true;
5237
5238   return false;
5239 }
5240
5241 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5242 ///
5243 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5244                                        unsigned NumNonZero, unsigned NumZero,
5245                                        SelectionDAG &DAG,
5246                                        const X86Subtarget* Subtarget,
5247                                        const TargetLowering &TLI) {
5248   if (NumNonZero > 8)
5249     return SDValue();
5250
5251   SDLoc dl(Op);
5252   SDValue V(0, 0);
5253   bool First = true;
5254   for (unsigned i = 0; i < 16; ++i) {
5255     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5256     if (ThisIsNonZero && First) {
5257       if (NumZero)
5258         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5259       else
5260         V = DAG.getUNDEF(MVT::v8i16);
5261       First = false;
5262     }
5263
5264     if ((i & 1) != 0) {
5265       SDValue ThisElt(0, 0), LastElt(0, 0);
5266       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5267       if (LastIsNonZero) {
5268         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5269                               MVT::i16, Op.getOperand(i-1));
5270       }
5271       if (ThisIsNonZero) {
5272         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5273         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5274                               ThisElt, DAG.getConstant(8, MVT::i8));
5275         if (LastIsNonZero)
5276           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5277       } else
5278         ThisElt = LastElt;
5279
5280       if (ThisElt.getNode())
5281         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5282                         DAG.getIntPtrConstant(i/2));
5283     }
5284   }
5285
5286   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5287 }
5288
5289 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5290 ///
5291 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5292                                      unsigned NumNonZero, unsigned NumZero,
5293                                      SelectionDAG &DAG,
5294                                      const X86Subtarget* Subtarget,
5295                                      const TargetLowering &TLI) {
5296   if (NumNonZero > 4)
5297     return SDValue();
5298
5299   SDLoc dl(Op);
5300   SDValue V(0, 0);
5301   bool First = true;
5302   for (unsigned i = 0; i < 8; ++i) {
5303     bool isNonZero = (NonZeros & (1 << i)) != 0;
5304     if (isNonZero) {
5305       if (First) {
5306         if (NumZero)
5307           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5308         else
5309           V = DAG.getUNDEF(MVT::v8i16);
5310         First = false;
5311       }
5312       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5313                       MVT::v8i16, V, Op.getOperand(i),
5314                       DAG.getIntPtrConstant(i));
5315     }
5316   }
5317
5318   return V;
5319 }
5320
5321 /// getVShift - Return a vector logical shift node.
5322 ///
5323 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5324                          unsigned NumBits, SelectionDAG &DAG,
5325                          const TargetLowering &TLI, SDLoc dl) {
5326   assert(VT.is128BitVector() && "Unknown type for VShift");
5327   EVT ShVT = MVT::v2i64;
5328   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5329   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5330   return DAG.getNode(ISD::BITCAST, dl, VT,
5331                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5332                              DAG.getConstant(NumBits,
5333                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5334 }
5335
5336 static SDValue
5337 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5338
5339   // Check if the scalar load can be widened into a vector load. And if
5340   // the address is "base + cst" see if the cst can be "absorbed" into
5341   // the shuffle mask.
5342   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5343     SDValue Ptr = LD->getBasePtr();
5344     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5345       return SDValue();
5346     EVT PVT = LD->getValueType(0);
5347     if (PVT != MVT::i32 && PVT != MVT::f32)
5348       return SDValue();
5349
5350     int FI = -1;
5351     int64_t Offset = 0;
5352     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5353       FI = FINode->getIndex();
5354       Offset = 0;
5355     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5356                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5357       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5358       Offset = Ptr.getConstantOperandVal(1);
5359       Ptr = Ptr.getOperand(0);
5360     } else {
5361       return SDValue();
5362     }
5363
5364     // FIXME: 256-bit vector instructions don't require a strict alignment,
5365     // improve this code to support it better.
5366     unsigned RequiredAlign = VT.getSizeInBits()/8;
5367     SDValue Chain = LD->getChain();
5368     // Make sure the stack object alignment is at least 16 or 32.
5369     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5370     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5371       if (MFI->isFixedObjectIndex(FI)) {
5372         // Can't change the alignment. FIXME: It's possible to compute
5373         // the exact stack offset and reference FI + adjust offset instead.
5374         // If someone *really* cares about this. That's the way to implement it.
5375         return SDValue();
5376       } else {
5377         MFI->setObjectAlignment(FI, RequiredAlign);
5378       }
5379     }
5380
5381     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5382     // Ptr + (Offset & ~15).
5383     if (Offset < 0)
5384       return SDValue();
5385     if ((Offset % RequiredAlign) & 3)
5386       return SDValue();
5387     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5388     if (StartOffset)
5389       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5390                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5391
5392     int EltNo = (Offset - StartOffset) >> 2;
5393     unsigned NumElems = VT.getVectorNumElements();
5394
5395     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5396     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5397                              LD->getPointerInfo().getWithOffset(StartOffset),
5398                              false, false, false, 0);
5399
5400     SmallVector<int, 8> Mask;
5401     for (unsigned i = 0; i != NumElems; ++i)
5402       Mask.push_back(EltNo);
5403
5404     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5405   }
5406
5407   return SDValue();
5408 }
5409
5410 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5411 /// vector of type 'VT', see if the elements can be replaced by a single large
5412 /// load which has the same value as a build_vector whose operands are 'elts'.
5413 ///
5414 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5415 ///
5416 /// FIXME: we'd also like to handle the case where the last elements are zero
5417 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5418 /// There's even a handy isZeroNode for that purpose.
5419 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5420                                         SDLoc &DL, SelectionDAG &DAG) {
5421   EVT EltVT = VT.getVectorElementType();
5422   unsigned NumElems = Elts.size();
5423
5424   LoadSDNode *LDBase = NULL;
5425   unsigned LastLoadedElt = -1U;
5426
5427   // For each element in the initializer, see if we've found a load or an undef.
5428   // If we don't find an initial load element, or later load elements are
5429   // non-consecutive, bail out.
5430   for (unsigned i = 0; i < NumElems; ++i) {
5431     SDValue Elt = Elts[i];
5432
5433     if (!Elt.getNode() ||
5434         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5435       return SDValue();
5436     if (!LDBase) {
5437       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5438         return SDValue();
5439       LDBase = cast<LoadSDNode>(Elt.getNode());
5440       LastLoadedElt = i;
5441       continue;
5442     }
5443     if (Elt.getOpcode() == ISD::UNDEF)
5444       continue;
5445
5446     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5447     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5448       return SDValue();
5449     LastLoadedElt = i;
5450   }
5451
5452   // If we have found an entire vector of loads and undefs, then return a large
5453   // load of the entire vector width starting at the base pointer.  If we found
5454   // consecutive loads for the low half, generate a vzext_load node.
5455   if (LastLoadedElt == NumElems - 1) {
5456     SDValue NewLd = SDValue();
5457     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5458       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5459                           LDBase->getPointerInfo(),
5460                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5461                           LDBase->isInvariant(), 0);
5462     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5463                         LDBase->getPointerInfo(),
5464                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5465                         LDBase->isInvariant(), LDBase->getAlignment());
5466
5467     if (LDBase->hasAnyUseOfValue(1)) {
5468       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5469                                      SDValue(LDBase, 1),
5470                                      SDValue(NewLd.getNode(), 1));
5471       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5472       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5473                              SDValue(NewLd.getNode(), 1));
5474     }
5475
5476     return NewLd;
5477   }
5478   if (NumElems == 4 && LastLoadedElt == 1 &&
5479       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5480     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5481     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5482     SDValue ResNode =
5483         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5484                                 array_lengthof(Ops), MVT::i64,
5485                                 LDBase->getPointerInfo(),
5486                                 LDBase->getAlignment(),
5487                                 false/*isVolatile*/, true/*ReadMem*/,
5488                                 false/*WriteMem*/);
5489
5490     // Make sure the newly-created LOAD is in the same position as LDBase in
5491     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5492     // update uses of LDBase's output chain to use the TokenFactor.
5493     if (LDBase->hasAnyUseOfValue(1)) {
5494       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5495                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5496       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5497       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5498                              SDValue(ResNode.getNode(), 1));
5499     }
5500
5501     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5502   }
5503   return SDValue();
5504 }
5505
5506 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5507 /// to generate a splat value for the following cases:
5508 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5509 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5510 /// a scalar load, or a constant.
5511 /// The VBROADCAST node is returned when a pattern is found,
5512 /// or SDValue() otherwise.
5513 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5514                                     SelectionDAG &DAG) {
5515   if (!Subtarget->hasFp256())
5516     return SDValue();
5517
5518   MVT VT = Op.getSimpleValueType();
5519   SDLoc dl(Op);
5520
5521   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5522          "Unsupported vector type for broadcast.");
5523
5524   SDValue Ld;
5525   bool ConstSplatVal;
5526
5527   switch (Op.getOpcode()) {
5528     default:
5529       // Unknown pattern found.
5530       return SDValue();
5531
5532     case ISD::BUILD_VECTOR: {
5533       // The BUILD_VECTOR node must be a splat.
5534       if (!isSplatVector(Op.getNode()))
5535         return SDValue();
5536
5537       Ld = Op.getOperand(0);
5538       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5539                      Ld.getOpcode() == ISD::ConstantFP);
5540
5541       // The suspected load node has several users. Make sure that all
5542       // of its users are from the BUILD_VECTOR node.
5543       // Constants may have multiple users.
5544       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5545         return SDValue();
5546       break;
5547     }
5548
5549     case ISD::VECTOR_SHUFFLE: {
5550       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5551
5552       // Shuffles must have a splat mask where the first element is
5553       // broadcasted.
5554       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5555         return SDValue();
5556
5557       SDValue Sc = Op.getOperand(0);
5558       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5559           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5560
5561         if (!Subtarget->hasInt256())
5562           return SDValue();
5563
5564         // Use the register form of the broadcast instruction available on AVX2.
5565         if (VT.getSizeInBits() >= 256)
5566           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5567         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5568       }
5569
5570       Ld = Sc.getOperand(0);
5571       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5572                        Ld.getOpcode() == ISD::ConstantFP);
5573
5574       // The scalar_to_vector node and the suspected
5575       // load node must have exactly one user.
5576       // Constants may have multiple users.
5577
5578       // AVX-512 has register version of the broadcast
5579       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5580         Ld.getValueType().getSizeInBits() >= 32;
5581       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5582           !hasRegVer))
5583         return SDValue();
5584       break;
5585     }
5586   }
5587
5588   bool IsGE256 = (VT.getSizeInBits() >= 256);
5589
5590   // Handle the broadcasting a single constant scalar from the constant pool
5591   // into a vector. On Sandybridge it is still better to load a constant vector
5592   // from the constant pool and not to broadcast it from a scalar.
5593   if (ConstSplatVal && Subtarget->hasInt256()) {
5594     EVT CVT = Ld.getValueType();
5595     assert(!CVT.isVector() && "Must not broadcast a vector type");
5596     unsigned ScalarSize = CVT.getSizeInBits();
5597
5598     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5599       const Constant *C = 0;
5600       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5601         C = CI->getConstantIntValue();
5602       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5603         C = CF->getConstantFPValue();
5604
5605       assert(C && "Invalid constant type");
5606
5607       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5608       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5609       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5610       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5611                        MachinePointerInfo::getConstantPool(),
5612                        false, false, false, Alignment);
5613
5614       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5615     }
5616   }
5617
5618   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5619   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5620
5621   // Handle AVX2 in-register broadcasts.
5622   if (!IsLoad && Subtarget->hasInt256() &&
5623       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5624     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5625
5626   // The scalar source must be a normal load.
5627   if (!IsLoad)
5628     return SDValue();
5629
5630   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5631     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5632
5633   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5634   // double since there is no vbroadcastsd xmm
5635   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5636     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5637       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5638   }
5639
5640   // Unsupported broadcast.
5641   return SDValue();
5642 }
5643
5644 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5645   MVT VT = Op.getSimpleValueType();
5646
5647   // Skip if insert_vec_elt is not supported.
5648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5649   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5650     return SDValue();
5651
5652   SDLoc DL(Op);
5653   unsigned NumElems = Op.getNumOperands();
5654
5655   SDValue VecIn1;
5656   SDValue VecIn2;
5657   SmallVector<unsigned, 4> InsertIndices;
5658   SmallVector<int, 8> Mask(NumElems, -1);
5659
5660   for (unsigned i = 0; i != NumElems; ++i) {
5661     unsigned Opc = Op.getOperand(i).getOpcode();
5662
5663     if (Opc == ISD::UNDEF)
5664       continue;
5665
5666     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5667       // Quit if more than 1 elements need inserting.
5668       if (InsertIndices.size() > 1)
5669         return SDValue();
5670
5671       InsertIndices.push_back(i);
5672       continue;
5673     }
5674
5675     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5676     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5677
5678     // Quit if extracted from vector of different type.
5679     if (ExtractedFromVec.getValueType() != VT)
5680       return SDValue();
5681
5682     // Quit if non-constant index.
5683     if (!isa<ConstantSDNode>(ExtIdx))
5684       return SDValue();
5685
5686     if (VecIn1.getNode() == 0)
5687       VecIn1 = ExtractedFromVec;
5688     else if (VecIn1 != ExtractedFromVec) {
5689       if (VecIn2.getNode() == 0)
5690         VecIn2 = ExtractedFromVec;
5691       else if (VecIn2 != ExtractedFromVec)
5692         // Quit if more than 2 vectors to shuffle
5693         return SDValue();
5694     }
5695
5696     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5697
5698     if (ExtractedFromVec == VecIn1)
5699       Mask[i] = Idx;
5700     else if (ExtractedFromVec == VecIn2)
5701       Mask[i] = Idx + NumElems;
5702   }
5703
5704   if (VecIn1.getNode() == 0)
5705     return SDValue();
5706
5707   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5708   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5709   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5710     unsigned Idx = InsertIndices[i];
5711     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5712                      DAG.getIntPtrConstant(Idx));
5713   }
5714
5715   return NV;
5716 }
5717
5718 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5719 SDValue
5720 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5721
5722   MVT VT = Op.getSimpleValueType();
5723   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5724          "Unexpected type in LowerBUILD_VECTORvXi1!");
5725
5726   SDLoc dl(Op);
5727   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5728     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5729     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5730                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5731     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5732                        Ops, VT.getVectorNumElements());
5733   }
5734
5735   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5736     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5737     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5738                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5739     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5740                        Ops, VT.getVectorNumElements());
5741   }
5742
5743   bool AllContants = true;
5744   uint64_t Immediate = 0;
5745   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5746     SDValue In = Op.getOperand(idx);
5747     if (In.getOpcode() == ISD::UNDEF)
5748       continue;
5749     if (!isa<ConstantSDNode>(In)) {
5750       AllContants = false;
5751       break;
5752     }
5753     if (cast<ConstantSDNode>(In)->getZExtValue())
5754       Immediate |= (1ULL << idx);
5755   }
5756
5757   if (AllContants) {
5758     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5759       DAG.getConstant(Immediate, MVT::i16));
5760     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5761                        DAG.getIntPtrConstant(0));
5762   }
5763
5764   // Splat vector (with undefs)
5765   SDValue In = Op.getOperand(0);
5766   for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5767     if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5768       llvm_unreachable("Unsupported predicate operation");
5769   }
5770
5771   SDValue EFLAGS, X86CC;
5772   if (In.getOpcode() == ISD::SETCC) {
5773     SDValue Op0 = In.getOperand(0);
5774     SDValue Op1 = In.getOperand(1);
5775     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5776     bool isFP = Op1.getValueType().isFloatingPoint();
5777     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5778
5779     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5780
5781     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5782     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5783     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5784   } else if (In.getOpcode() == X86ISD::SETCC) {
5785     X86CC = In.getOperand(0);
5786     EFLAGS = In.getOperand(1);
5787   } else {
5788     // The algorithm:
5789     //   Bit1 = In & 0x1
5790     //   if (Bit1 != 0)
5791     //     ZF = 0
5792     //   else
5793     //     ZF = 1
5794     //   if (ZF == 0)
5795     //     res = allOnes ### CMOVNE -1, %res
5796     //   else
5797     //     res = allZero
5798     MVT InVT = In.getSimpleValueType();
5799     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5800     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5801     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5802   }
5803
5804   if (VT == MVT::v16i1) {
5805     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5806     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5807     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5808           Cst0, Cst1, X86CC, EFLAGS);
5809     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5810   }
5811
5812   if (VT == MVT::v8i1) {
5813     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5814     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5815     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5816           Cst0, Cst1, X86CC, EFLAGS);
5817     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5818     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5819   }
5820   llvm_unreachable("Unsupported predicate operation");
5821 }
5822
5823 SDValue
5824 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5825   SDLoc dl(Op);
5826
5827   MVT VT = Op.getSimpleValueType();
5828   MVT ExtVT = VT.getVectorElementType();
5829   unsigned NumElems = Op.getNumOperands();
5830
5831   // Generate vectors for predicate vectors.
5832   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5833     return LowerBUILD_VECTORvXi1(Op, DAG);
5834
5835   // Vectors containing all zeros can be matched by pxor and xorps later
5836   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5837     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5838     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5839     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5840       return Op;
5841
5842     return getZeroVector(VT, Subtarget, DAG, dl);
5843   }
5844
5845   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5846   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5847   // vpcmpeqd on 256-bit vectors.
5848   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5849     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5850       return Op;
5851
5852     if (!VT.is512BitVector())
5853       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5854   }
5855
5856   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5857   if (Broadcast.getNode())
5858     return Broadcast;
5859
5860   unsigned EVTBits = ExtVT.getSizeInBits();
5861
5862   unsigned NumZero  = 0;
5863   unsigned NumNonZero = 0;
5864   unsigned NonZeros = 0;
5865   bool IsAllConstants = true;
5866   SmallSet<SDValue, 8> Values;
5867   for (unsigned i = 0; i < NumElems; ++i) {
5868     SDValue Elt = Op.getOperand(i);
5869     if (Elt.getOpcode() == ISD::UNDEF)
5870       continue;
5871     Values.insert(Elt);
5872     if (Elt.getOpcode() != ISD::Constant &&
5873         Elt.getOpcode() != ISD::ConstantFP)
5874       IsAllConstants = false;
5875     if (X86::isZeroNode(Elt))
5876       NumZero++;
5877     else {
5878       NonZeros |= (1 << i);
5879       NumNonZero++;
5880     }
5881   }
5882
5883   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5884   if (NumNonZero == 0)
5885     return DAG.getUNDEF(VT);
5886
5887   // Special case for single non-zero, non-undef, element.
5888   if (NumNonZero == 1) {
5889     unsigned Idx = countTrailingZeros(NonZeros);
5890     SDValue Item = Op.getOperand(Idx);
5891
5892     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5893     // the value are obviously zero, truncate the value to i32 and do the
5894     // insertion that way.  Only do this if the value is non-constant or if the
5895     // value is a constant being inserted into element 0.  It is cheaper to do
5896     // a constant pool load than it is to do a movd + shuffle.
5897     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5898         (!IsAllConstants || Idx == 0)) {
5899       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5900         // Handle SSE only.
5901         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5902         EVT VecVT = MVT::v4i32;
5903         unsigned VecElts = 4;
5904
5905         // Truncate the value (which may itself be a constant) to i32, and
5906         // convert it to a vector with movd (S2V+shuffle to zero extend).
5907         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5908         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5909         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5910
5911         // Now we have our 32-bit value zero extended in the low element of
5912         // a vector.  If Idx != 0, swizzle it into place.
5913         if (Idx != 0) {
5914           SmallVector<int, 4> Mask;
5915           Mask.push_back(Idx);
5916           for (unsigned i = 1; i != VecElts; ++i)
5917             Mask.push_back(i);
5918           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5919                                       &Mask[0]);
5920         }
5921         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5922       }
5923     }
5924
5925     // If we have a constant or non-constant insertion into the low element of
5926     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5927     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5928     // depending on what the source datatype is.
5929     if (Idx == 0) {
5930       if (NumZero == 0)
5931         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5932
5933       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5934           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5935         if (VT.is256BitVector() || VT.is512BitVector()) {
5936           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5937           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5938                              Item, DAG.getIntPtrConstant(0));
5939         }
5940         assert(VT.is128BitVector() && "Expected an SSE value type!");
5941         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5942         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5943         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5944       }
5945
5946       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5947         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5948         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5949         if (VT.is256BitVector()) {
5950           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5951           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5952         } else {
5953           assert(VT.is128BitVector() && "Expected an SSE value type!");
5954           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5955         }
5956         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5957       }
5958     }
5959
5960     // Is it a vector logical left shift?
5961     if (NumElems == 2 && Idx == 1 &&
5962         X86::isZeroNode(Op.getOperand(0)) &&
5963         !X86::isZeroNode(Op.getOperand(1))) {
5964       unsigned NumBits = VT.getSizeInBits();
5965       return getVShift(true, VT,
5966                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5967                                    VT, Op.getOperand(1)),
5968                        NumBits/2, DAG, *this, dl);
5969     }
5970
5971     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5972       return SDValue();
5973
5974     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5975     // is a non-constant being inserted into an element other than the low one,
5976     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5977     // movd/movss) to move this into the low element, then shuffle it into
5978     // place.
5979     if (EVTBits == 32) {
5980       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5981
5982       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5983       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5984       SmallVector<int, 8> MaskVec;
5985       for (unsigned i = 0; i != NumElems; ++i)
5986         MaskVec.push_back(i == Idx ? 0 : 1);
5987       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5988     }
5989   }
5990
5991   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5992   if (Values.size() == 1) {
5993     if (EVTBits == 32) {
5994       // Instead of a shuffle like this:
5995       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5996       // Check if it's possible to issue this instead.
5997       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5998       unsigned Idx = countTrailingZeros(NonZeros);
5999       SDValue Item = Op.getOperand(Idx);
6000       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6001         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6002     }
6003     return SDValue();
6004   }
6005
6006   // A vector full of immediates; various special cases are already
6007   // handled, so this is best done with a single constant-pool load.
6008   if (IsAllConstants)
6009     return SDValue();
6010
6011   // For AVX-length vectors, build the individual 128-bit pieces and use
6012   // shuffles to put them in place.
6013   if (VT.is256BitVector()) {
6014     SmallVector<SDValue, 32> V;
6015     for (unsigned i = 0; i != NumElems; ++i)
6016       V.push_back(Op.getOperand(i));
6017
6018     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6019
6020     // Build both the lower and upper subvector.
6021     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6022     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6023                                 NumElems/2);
6024
6025     // Recreate the wider vector with the lower and upper part.
6026     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6027   }
6028
6029   // Let legalizer expand 2-wide build_vectors.
6030   if (EVTBits == 64) {
6031     if (NumNonZero == 1) {
6032       // One half is zero or undef.
6033       unsigned Idx = countTrailingZeros(NonZeros);
6034       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6035                                  Op.getOperand(Idx));
6036       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6037     }
6038     return SDValue();
6039   }
6040
6041   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6042   if (EVTBits == 8 && NumElems == 16) {
6043     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6044                                         Subtarget, *this);
6045     if (V.getNode()) return V;
6046   }
6047
6048   if (EVTBits == 16 && NumElems == 8) {
6049     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6050                                       Subtarget, *this);
6051     if (V.getNode()) return V;
6052   }
6053
6054   // If element VT is == 32 bits, turn it into a number of shuffles.
6055   SmallVector<SDValue, 8> V(NumElems);
6056   if (NumElems == 4 && NumZero > 0) {
6057     for (unsigned i = 0; i < 4; ++i) {
6058       bool isZero = !(NonZeros & (1 << i));
6059       if (isZero)
6060         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6061       else
6062         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6063     }
6064
6065     for (unsigned i = 0; i < 2; ++i) {
6066       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6067         default: break;
6068         case 0:
6069           V[i] = V[i*2];  // Must be a zero vector.
6070           break;
6071         case 1:
6072           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6073           break;
6074         case 2:
6075           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6076           break;
6077         case 3:
6078           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6079           break;
6080       }
6081     }
6082
6083     bool Reverse1 = (NonZeros & 0x3) == 2;
6084     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6085     int MaskVec[] = {
6086       Reverse1 ? 1 : 0,
6087       Reverse1 ? 0 : 1,
6088       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6089       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6090     };
6091     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6092   }
6093
6094   if (Values.size() > 1 && VT.is128BitVector()) {
6095     // Check for a build vector of consecutive loads.
6096     for (unsigned i = 0; i < NumElems; ++i)
6097       V[i] = Op.getOperand(i);
6098
6099     // Check for elements which are consecutive loads.
6100     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
6101     if (LD.getNode())
6102       return LD;
6103
6104     // Check for a build vector from mostly shuffle plus few inserting.
6105     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6106     if (Sh.getNode())
6107       return Sh;
6108
6109     // For SSE 4.1, use insertps to put the high elements into the low element.
6110     if (getSubtarget()->hasSSE41()) {
6111       SDValue Result;
6112       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6113         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6114       else
6115         Result = DAG.getUNDEF(VT);
6116
6117       for (unsigned i = 1; i < NumElems; ++i) {
6118         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6119         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6120                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6121       }
6122       return Result;
6123     }
6124
6125     // Otherwise, expand into a number of unpckl*, start by extending each of
6126     // our (non-undef) elements to the full vector width with the element in the
6127     // bottom slot of the vector (which generates no code for SSE).
6128     for (unsigned i = 0; i < NumElems; ++i) {
6129       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6130         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6131       else
6132         V[i] = DAG.getUNDEF(VT);
6133     }
6134
6135     // Next, we iteratively mix elements, e.g. for v4f32:
6136     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6137     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6138     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6139     unsigned EltStride = NumElems >> 1;
6140     while (EltStride != 0) {
6141       for (unsigned i = 0; i < EltStride; ++i) {
6142         // If V[i+EltStride] is undef and this is the first round of mixing,
6143         // then it is safe to just drop this shuffle: V[i] is already in the
6144         // right place, the one element (since it's the first round) being
6145         // inserted as undef can be dropped.  This isn't safe for successive
6146         // rounds because they will permute elements within both vectors.
6147         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6148             EltStride == NumElems/2)
6149           continue;
6150
6151         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6152       }
6153       EltStride >>= 1;
6154     }
6155     return V[0];
6156   }
6157   return SDValue();
6158 }
6159
6160 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6161 // to create 256-bit vectors from two other 128-bit ones.
6162 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6163   SDLoc dl(Op);
6164   MVT ResVT = Op.getSimpleValueType();
6165
6166   assert((ResVT.is256BitVector() ||
6167           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6168
6169   SDValue V1 = Op.getOperand(0);
6170   SDValue V2 = Op.getOperand(1);
6171   unsigned NumElems = ResVT.getVectorNumElements();
6172   if(ResVT.is256BitVector())
6173     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6174
6175   if (Op.getNumOperands() == 4) {
6176     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6177                                 ResVT.getVectorNumElements()/2);
6178     SDValue V3 = Op.getOperand(2);
6179     SDValue V4 = Op.getOperand(3);
6180     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6181       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6182   }
6183   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6184 }
6185
6186 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6187   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6188   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6189          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6190           Op.getNumOperands() == 4)));
6191
6192   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6193   // from two other 128-bit ones.
6194
6195   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6196   return LowerAVXCONCAT_VECTORS(Op, DAG);
6197 }
6198
6199 // Try to lower a shuffle node into a simple blend instruction.
6200 static SDValue
6201 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6202                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6203   SDValue V1 = SVOp->getOperand(0);
6204   SDValue V2 = SVOp->getOperand(1);
6205   SDLoc dl(SVOp);
6206   MVT VT = SVOp->getSimpleValueType(0);
6207   MVT EltVT = VT.getVectorElementType();
6208   unsigned NumElems = VT.getVectorNumElements();
6209
6210   // There is no blend with immediate in AVX-512.
6211   if (VT.is512BitVector())
6212     return SDValue();
6213
6214   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6215     return SDValue();
6216   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6217     return SDValue();
6218
6219   // Check the mask for BLEND and build the value.
6220   unsigned MaskValue = 0;
6221   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6222   unsigned NumLanes = (NumElems-1)/8 + 1;
6223   unsigned NumElemsInLane = NumElems / NumLanes;
6224
6225   // Blend for v16i16 should be symetric for the both lanes.
6226   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6227
6228     int SndLaneEltIdx = (NumLanes == 2) ?
6229       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6230     int EltIdx = SVOp->getMaskElt(i);
6231
6232     if ((EltIdx < 0 || EltIdx == (int)i) &&
6233         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6234       continue;
6235
6236     if (((unsigned)EltIdx == (i + NumElems)) &&
6237         (SndLaneEltIdx < 0 ||
6238          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6239       MaskValue |= (1<<i);
6240     else
6241       return SDValue();
6242   }
6243
6244   // Convert i32 vectors to floating point if it is not AVX2.
6245   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6246   MVT BlendVT = VT;
6247   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6248     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6249                                NumElems);
6250     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6251     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6252   }
6253
6254   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6255                             DAG.getConstant(MaskValue, MVT::i32));
6256   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6257 }
6258
6259 // v8i16 shuffles - Prefer shuffles in the following order:
6260 // 1. [all]   pshuflw, pshufhw, optional move
6261 // 2. [ssse3] 1 x pshufb
6262 // 3. [ssse3] 2 x pshufb + 1 x por
6263 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6264 static SDValue
6265 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6266                          SelectionDAG &DAG) {
6267   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6268   SDValue V1 = SVOp->getOperand(0);
6269   SDValue V2 = SVOp->getOperand(1);
6270   SDLoc dl(SVOp);
6271   SmallVector<int, 8> MaskVals;
6272
6273   // Determine if more than 1 of the words in each of the low and high quadwords
6274   // of the result come from the same quadword of one of the two inputs.  Undef
6275   // mask values count as coming from any quadword, for better codegen.
6276   unsigned LoQuad[] = { 0, 0, 0, 0 };
6277   unsigned HiQuad[] = { 0, 0, 0, 0 };
6278   std::bitset<4> InputQuads;
6279   for (unsigned i = 0; i < 8; ++i) {
6280     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6281     int EltIdx = SVOp->getMaskElt(i);
6282     MaskVals.push_back(EltIdx);
6283     if (EltIdx < 0) {
6284       ++Quad[0];
6285       ++Quad[1];
6286       ++Quad[2];
6287       ++Quad[3];
6288       continue;
6289     }
6290     ++Quad[EltIdx / 4];
6291     InputQuads.set(EltIdx / 4);
6292   }
6293
6294   int BestLoQuad = -1;
6295   unsigned MaxQuad = 1;
6296   for (unsigned i = 0; i < 4; ++i) {
6297     if (LoQuad[i] > MaxQuad) {
6298       BestLoQuad = i;
6299       MaxQuad = LoQuad[i];
6300     }
6301   }
6302
6303   int BestHiQuad = -1;
6304   MaxQuad = 1;
6305   for (unsigned i = 0; i < 4; ++i) {
6306     if (HiQuad[i] > MaxQuad) {
6307       BestHiQuad = i;
6308       MaxQuad = HiQuad[i];
6309     }
6310   }
6311
6312   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6313   // of the two input vectors, shuffle them into one input vector so only a
6314   // single pshufb instruction is necessary. If There are more than 2 input
6315   // quads, disable the next transformation since it does not help SSSE3.
6316   bool V1Used = InputQuads[0] || InputQuads[1];
6317   bool V2Used = InputQuads[2] || InputQuads[3];
6318   if (Subtarget->hasSSSE3()) {
6319     if (InputQuads.count() == 2 && V1Used && V2Used) {
6320       BestLoQuad = InputQuads[0] ? 0 : 1;
6321       BestHiQuad = InputQuads[2] ? 2 : 3;
6322     }
6323     if (InputQuads.count() > 2) {
6324       BestLoQuad = -1;
6325       BestHiQuad = -1;
6326     }
6327   }
6328
6329   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6330   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6331   // words from all 4 input quadwords.
6332   SDValue NewV;
6333   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6334     int MaskV[] = {
6335       BestLoQuad < 0 ? 0 : BestLoQuad,
6336       BestHiQuad < 0 ? 1 : BestHiQuad
6337     };
6338     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6339                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6340                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6341     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6342
6343     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6344     // source words for the shuffle, to aid later transformations.
6345     bool AllWordsInNewV = true;
6346     bool InOrder[2] = { true, true };
6347     for (unsigned i = 0; i != 8; ++i) {
6348       int idx = MaskVals[i];
6349       if (idx != (int)i)
6350         InOrder[i/4] = false;
6351       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6352         continue;
6353       AllWordsInNewV = false;
6354       break;
6355     }
6356
6357     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6358     if (AllWordsInNewV) {
6359       for (int i = 0; i != 8; ++i) {
6360         int idx = MaskVals[i];
6361         if (idx < 0)
6362           continue;
6363         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6364         if ((idx != i) && idx < 4)
6365           pshufhw = false;
6366         if ((idx != i) && idx > 3)
6367           pshuflw = false;
6368       }
6369       V1 = NewV;
6370       V2Used = false;
6371       BestLoQuad = 0;
6372       BestHiQuad = 1;
6373     }
6374
6375     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6376     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6377     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6378       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6379       unsigned TargetMask = 0;
6380       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6381                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6382       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6383       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6384                              getShufflePSHUFLWImmediate(SVOp);
6385       V1 = NewV.getOperand(0);
6386       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6387     }
6388   }
6389
6390   // Promote splats to a larger type which usually leads to more efficient code.
6391   // FIXME: Is this true if pshufb is available?
6392   if (SVOp->isSplat())
6393     return PromoteSplat(SVOp, DAG);
6394
6395   // If we have SSSE3, and all words of the result are from 1 input vector,
6396   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6397   // is present, fall back to case 4.
6398   if (Subtarget->hasSSSE3()) {
6399     SmallVector<SDValue,16> pshufbMask;
6400
6401     // If we have elements from both input vectors, set the high bit of the
6402     // shuffle mask element to zero out elements that come from V2 in the V1
6403     // mask, and elements that come from V1 in the V2 mask, so that the two
6404     // results can be OR'd together.
6405     bool TwoInputs = V1Used && V2Used;
6406     for (unsigned i = 0; i != 8; ++i) {
6407       int EltIdx = MaskVals[i] * 2;
6408       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6409       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6410       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6411       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6412     }
6413     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6414     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6415                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6416                                  MVT::v16i8, &pshufbMask[0], 16));
6417     if (!TwoInputs)
6418       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6419
6420     // Calculate the shuffle mask for the second input, shuffle it, and
6421     // OR it with the first shuffled input.
6422     pshufbMask.clear();
6423     for (unsigned i = 0; i != 8; ++i) {
6424       int EltIdx = MaskVals[i] * 2;
6425       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6426       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6427       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6428       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6429     }
6430     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6431     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6432                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6433                                  MVT::v16i8, &pshufbMask[0], 16));
6434     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6435     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6436   }
6437
6438   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6439   // and update MaskVals with new element order.
6440   std::bitset<8> InOrder;
6441   if (BestLoQuad >= 0) {
6442     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6443     for (int i = 0; i != 4; ++i) {
6444       int idx = MaskVals[i];
6445       if (idx < 0) {
6446         InOrder.set(i);
6447       } else if ((idx / 4) == BestLoQuad) {
6448         MaskV[i] = idx & 3;
6449         InOrder.set(i);
6450       }
6451     }
6452     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6453                                 &MaskV[0]);
6454
6455     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6456       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6457       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6458                                   NewV.getOperand(0),
6459                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6460     }
6461   }
6462
6463   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6464   // and update MaskVals with the new element order.
6465   if (BestHiQuad >= 0) {
6466     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6467     for (unsigned i = 4; i != 8; ++i) {
6468       int idx = MaskVals[i];
6469       if (idx < 0) {
6470         InOrder.set(i);
6471       } else if ((idx / 4) == BestHiQuad) {
6472         MaskV[i] = (idx & 3) + 4;
6473         InOrder.set(i);
6474       }
6475     }
6476     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6477                                 &MaskV[0]);
6478
6479     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6480       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6481       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6482                                   NewV.getOperand(0),
6483                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6484     }
6485   }
6486
6487   // In case BestHi & BestLo were both -1, which means each quadword has a word
6488   // from each of the four input quadwords, calculate the InOrder bitvector now
6489   // before falling through to the insert/extract cleanup.
6490   if (BestLoQuad == -1 && BestHiQuad == -1) {
6491     NewV = V1;
6492     for (int i = 0; i != 8; ++i)
6493       if (MaskVals[i] < 0 || MaskVals[i] == i)
6494         InOrder.set(i);
6495   }
6496
6497   // The other elements are put in the right place using pextrw and pinsrw.
6498   for (unsigned i = 0; i != 8; ++i) {
6499     if (InOrder[i])
6500       continue;
6501     int EltIdx = MaskVals[i];
6502     if (EltIdx < 0)
6503       continue;
6504     SDValue ExtOp = (EltIdx < 8) ?
6505       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6506                   DAG.getIntPtrConstant(EltIdx)) :
6507       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6508                   DAG.getIntPtrConstant(EltIdx - 8));
6509     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6510                        DAG.getIntPtrConstant(i));
6511   }
6512   return NewV;
6513 }
6514
6515 // v16i8 shuffles - Prefer shuffles in the following order:
6516 // 1. [ssse3] 1 x pshufb
6517 // 2. [ssse3] 2 x pshufb + 1 x por
6518 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6519 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6520                                         const X86Subtarget* Subtarget,
6521                                         SelectionDAG &DAG) {
6522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6523   SDValue V1 = SVOp->getOperand(0);
6524   SDValue V2 = SVOp->getOperand(1);
6525   SDLoc dl(SVOp);
6526   ArrayRef<int> MaskVals = SVOp->getMask();
6527
6528   // Promote splats to a larger type which usually leads to more efficient code.
6529   // FIXME: Is this true if pshufb is available?
6530   if (SVOp->isSplat())
6531     return PromoteSplat(SVOp, DAG);
6532
6533   // If we have SSSE3, case 1 is generated when all result bytes come from
6534   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6535   // present, fall back to case 3.
6536
6537   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6538   if (Subtarget->hasSSSE3()) {
6539     SmallVector<SDValue,16> pshufbMask;
6540
6541     // If all result elements are from one input vector, then only translate
6542     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6543     //
6544     // Otherwise, we have elements from both input vectors, and must zero out
6545     // elements that come from V2 in the first mask, and V1 in the second mask
6546     // so that we can OR them together.
6547     for (unsigned i = 0; i != 16; ++i) {
6548       int EltIdx = MaskVals[i];
6549       if (EltIdx < 0 || EltIdx >= 16)
6550         EltIdx = 0x80;
6551       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6552     }
6553     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6554                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6555                                  MVT::v16i8, &pshufbMask[0], 16));
6556
6557     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6558     // the 2nd operand if it's undefined or zero.
6559     if (V2.getOpcode() == ISD::UNDEF ||
6560         ISD::isBuildVectorAllZeros(V2.getNode()))
6561       return V1;
6562
6563     // Calculate the shuffle mask for the second input, shuffle it, and
6564     // OR it with the first shuffled input.
6565     pshufbMask.clear();
6566     for (unsigned i = 0; i != 16; ++i) {
6567       int EltIdx = MaskVals[i];
6568       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6569       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6570     }
6571     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6572                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6573                                  MVT::v16i8, &pshufbMask[0], 16));
6574     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6575   }
6576
6577   // No SSSE3 - Calculate in place words and then fix all out of place words
6578   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6579   // the 16 different words that comprise the two doublequadword input vectors.
6580   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6581   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6582   SDValue NewV = V1;
6583   for (int i = 0; i != 8; ++i) {
6584     int Elt0 = MaskVals[i*2];
6585     int Elt1 = MaskVals[i*2+1];
6586
6587     // This word of the result is all undef, skip it.
6588     if (Elt0 < 0 && Elt1 < 0)
6589       continue;
6590
6591     // This word of the result is already in the correct place, skip it.
6592     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6593       continue;
6594
6595     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6596     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6597     SDValue InsElt;
6598
6599     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6600     // using a single extract together, load it and store it.
6601     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6602       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6603                            DAG.getIntPtrConstant(Elt1 / 2));
6604       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6605                         DAG.getIntPtrConstant(i));
6606       continue;
6607     }
6608
6609     // If Elt1 is defined, extract it from the appropriate source.  If the
6610     // source byte is not also odd, shift the extracted word left 8 bits
6611     // otherwise clear the bottom 8 bits if we need to do an or.
6612     if (Elt1 >= 0) {
6613       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6614                            DAG.getIntPtrConstant(Elt1 / 2));
6615       if ((Elt1 & 1) == 0)
6616         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6617                              DAG.getConstant(8,
6618                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6619       else if (Elt0 >= 0)
6620         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6621                              DAG.getConstant(0xFF00, MVT::i16));
6622     }
6623     // If Elt0 is defined, extract it from the appropriate source.  If the
6624     // source byte is not also even, shift the extracted word right 8 bits. If
6625     // Elt1 was also defined, OR the extracted values together before
6626     // inserting them in the result.
6627     if (Elt0 >= 0) {
6628       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6629                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6630       if ((Elt0 & 1) != 0)
6631         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6632                               DAG.getConstant(8,
6633                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6634       else if (Elt1 >= 0)
6635         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6636                              DAG.getConstant(0x00FF, MVT::i16));
6637       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6638                          : InsElt0;
6639     }
6640     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6641                        DAG.getIntPtrConstant(i));
6642   }
6643   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6644 }
6645
6646 // v32i8 shuffles - Translate to VPSHUFB if possible.
6647 static
6648 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6649                                  const X86Subtarget *Subtarget,
6650                                  SelectionDAG &DAG) {
6651   MVT VT = SVOp->getSimpleValueType(0);
6652   SDValue V1 = SVOp->getOperand(0);
6653   SDValue V2 = SVOp->getOperand(1);
6654   SDLoc dl(SVOp);
6655   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6656
6657   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6658   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6659   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6660
6661   // VPSHUFB may be generated if
6662   // (1) one of input vector is undefined or zeroinitializer.
6663   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6664   // And (2) the mask indexes don't cross the 128-bit lane.
6665   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6666       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6667     return SDValue();
6668
6669   if (V1IsAllZero && !V2IsAllZero) {
6670     CommuteVectorShuffleMask(MaskVals, 32);
6671     V1 = V2;
6672   }
6673   SmallVector<SDValue, 32> pshufbMask;
6674   for (unsigned i = 0; i != 32; i++) {
6675     int EltIdx = MaskVals[i];
6676     if (EltIdx < 0 || EltIdx >= 32)
6677       EltIdx = 0x80;
6678     else {
6679       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6680         // Cross lane is not allowed.
6681         return SDValue();
6682       EltIdx &= 0xf;
6683     }
6684     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6685   }
6686   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6687                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6688                                   MVT::v32i8, &pshufbMask[0], 32));
6689 }
6690
6691 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6692 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6693 /// done when every pair / quad of shuffle mask elements point to elements in
6694 /// the right sequence. e.g.
6695 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6696 static
6697 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6698                                  SelectionDAG &DAG) {
6699   MVT VT = SVOp->getSimpleValueType(0);
6700   SDLoc dl(SVOp);
6701   unsigned NumElems = VT.getVectorNumElements();
6702   MVT NewVT;
6703   unsigned Scale;
6704   switch (VT.SimpleTy) {
6705   default: llvm_unreachable("Unexpected!");
6706   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6707   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6708   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6709   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6710   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6711   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6712   }
6713
6714   SmallVector<int, 8> MaskVec;
6715   for (unsigned i = 0; i != NumElems; i += Scale) {
6716     int StartIdx = -1;
6717     for (unsigned j = 0; j != Scale; ++j) {
6718       int EltIdx = SVOp->getMaskElt(i+j);
6719       if (EltIdx < 0)
6720         continue;
6721       if (StartIdx < 0)
6722         StartIdx = (EltIdx / Scale);
6723       if (EltIdx != (int)(StartIdx*Scale + j))
6724         return SDValue();
6725     }
6726     MaskVec.push_back(StartIdx);
6727   }
6728
6729   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6730   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6731   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6732 }
6733
6734 /// getVZextMovL - Return a zero-extending vector move low node.
6735 ///
6736 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6737                             SDValue SrcOp, SelectionDAG &DAG,
6738                             const X86Subtarget *Subtarget, SDLoc dl) {
6739   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6740     LoadSDNode *LD = NULL;
6741     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6742       LD = dyn_cast<LoadSDNode>(SrcOp);
6743     if (!LD) {
6744       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6745       // instead.
6746       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6747       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6748           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6749           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6750           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6751         // PR2108
6752         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6753         return DAG.getNode(ISD::BITCAST, dl, VT,
6754                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6755                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6756                                                    OpVT,
6757                                                    SrcOp.getOperand(0)
6758                                                           .getOperand(0))));
6759       }
6760     }
6761   }
6762
6763   return DAG.getNode(ISD::BITCAST, dl, VT,
6764                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6765                                  DAG.getNode(ISD::BITCAST, dl,
6766                                              OpVT, SrcOp)));
6767 }
6768
6769 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6770 /// which could not be matched by any known target speficic shuffle
6771 static SDValue
6772 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6773
6774   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6775   if (NewOp.getNode())
6776     return NewOp;
6777
6778   MVT VT = SVOp->getSimpleValueType(0);
6779
6780   unsigned NumElems = VT.getVectorNumElements();
6781   unsigned NumLaneElems = NumElems / 2;
6782
6783   SDLoc dl(SVOp);
6784   MVT EltVT = VT.getVectorElementType();
6785   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6786   SDValue Output[2];
6787
6788   SmallVector<int, 16> Mask;
6789   for (unsigned l = 0; l < 2; ++l) {
6790     // Build a shuffle mask for the output, discovering on the fly which
6791     // input vectors to use as shuffle operands (recorded in InputUsed).
6792     // If building a suitable shuffle vector proves too hard, then bail
6793     // out with UseBuildVector set.
6794     bool UseBuildVector = false;
6795     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6796     unsigned LaneStart = l * NumLaneElems;
6797     for (unsigned i = 0; i != NumLaneElems; ++i) {
6798       // The mask element.  This indexes into the input.
6799       int Idx = SVOp->getMaskElt(i+LaneStart);
6800       if (Idx < 0) {
6801         // the mask element does not index into any input vector.
6802         Mask.push_back(-1);
6803         continue;
6804       }
6805
6806       // The input vector this mask element indexes into.
6807       int Input = Idx / NumLaneElems;
6808
6809       // Turn the index into an offset from the start of the input vector.
6810       Idx -= Input * NumLaneElems;
6811
6812       // Find or create a shuffle vector operand to hold this input.
6813       unsigned OpNo;
6814       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6815         if (InputUsed[OpNo] == Input)
6816           // This input vector is already an operand.
6817           break;
6818         if (InputUsed[OpNo] < 0) {
6819           // Create a new operand for this input vector.
6820           InputUsed[OpNo] = Input;
6821           break;
6822         }
6823       }
6824
6825       if (OpNo >= array_lengthof(InputUsed)) {
6826         // More than two input vectors used!  Give up on trying to create a
6827         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6828         UseBuildVector = true;
6829         break;
6830       }
6831
6832       // Add the mask index for the new shuffle vector.
6833       Mask.push_back(Idx + OpNo * NumLaneElems);
6834     }
6835
6836     if (UseBuildVector) {
6837       SmallVector<SDValue, 16> SVOps;
6838       for (unsigned i = 0; i != NumLaneElems; ++i) {
6839         // The mask element.  This indexes into the input.
6840         int Idx = SVOp->getMaskElt(i+LaneStart);
6841         if (Idx < 0) {
6842           SVOps.push_back(DAG.getUNDEF(EltVT));
6843           continue;
6844         }
6845
6846         // The input vector this mask element indexes into.
6847         int Input = Idx / NumElems;
6848
6849         // Turn the index into an offset from the start of the input vector.
6850         Idx -= Input * NumElems;
6851
6852         // Extract the vector element by hand.
6853         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6854                                     SVOp->getOperand(Input),
6855                                     DAG.getIntPtrConstant(Idx)));
6856       }
6857
6858       // Construct the output using a BUILD_VECTOR.
6859       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6860                               SVOps.size());
6861     } else if (InputUsed[0] < 0) {
6862       // No input vectors were used! The result is undefined.
6863       Output[l] = DAG.getUNDEF(NVT);
6864     } else {
6865       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6866                                         (InputUsed[0] % 2) * NumLaneElems,
6867                                         DAG, dl);
6868       // If only one input was used, use an undefined vector for the other.
6869       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6870         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6871                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6872       // At least one input vector was used. Create a new shuffle vector.
6873       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6874     }
6875
6876     Mask.clear();
6877   }
6878
6879   // Concatenate the result back
6880   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6881 }
6882
6883 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6884 /// 4 elements, and match them with several different shuffle types.
6885 static SDValue
6886 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6887   SDValue V1 = SVOp->getOperand(0);
6888   SDValue V2 = SVOp->getOperand(1);
6889   SDLoc dl(SVOp);
6890   MVT VT = SVOp->getSimpleValueType(0);
6891
6892   assert(VT.is128BitVector() && "Unsupported vector size");
6893
6894   std::pair<int, int> Locs[4];
6895   int Mask1[] = { -1, -1, -1, -1 };
6896   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6897
6898   unsigned NumHi = 0;
6899   unsigned NumLo = 0;
6900   for (unsigned i = 0; i != 4; ++i) {
6901     int Idx = PermMask[i];
6902     if (Idx < 0) {
6903       Locs[i] = std::make_pair(-1, -1);
6904     } else {
6905       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6906       if (Idx < 4) {
6907         Locs[i] = std::make_pair(0, NumLo);
6908         Mask1[NumLo] = Idx;
6909         NumLo++;
6910       } else {
6911         Locs[i] = std::make_pair(1, NumHi);
6912         if (2+NumHi < 4)
6913           Mask1[2+NumHi] = Idx;
6914         NumHi++;
6915       }
6916     }
6917   }
6918
6919   if (NumLo <= 2 && NumHi <= 2) {
6920     // If no more than two elements come from either vector. This can be
6921     // implemented with two shuffles. First shuffle gather the elements.
6922     // The second shuffle, which takes the first shuffle as both of its
6923     // vector operands, put the elements into the right order.
6924     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6925
6926     int Mask2[] = { -1, -1, -1, -1 };
6927
6928     for (unsigned i = 0; i != 4; ++i)
6929       if (Locs[i].first != -1) {
6930         unsigned Idx = (i < 2) ? 0 : 4;
6931         Idx += Locs[i].first * 2 + Locs[i].second;
6932         Mask2[i] = Idx;
6933       }
6934
6935     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6936   }
6937
6938   if (NumLo == 3 || NumHi == 3) {
6939     // Otherwise, we must have three elements from one vector, call it X, and
6940     // one element from the other, call it Y.  First, use a shufps to build an
6941     // intermediate vector with the one element from Y and the element from X
6942     // that will be in the same half in the final destination (the indexes don't
6943     // matter). Then, use a shufps to build the final vector, taking the half
6944     // containing the element from Y from the intermediate, and the other half
6945     // from X.
6946     if (NumHi == 3) {
6947       // Normalize it so the 3 elements come from V1.
6948       CommuteVectorShuffleMask(PermMask, 4);
6949       std::swap(V1, V2);
6950     }
6951
6952     // Find the element from V2.
6953     unsigned HiIndex;
6954     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6955       int Val = PermMask[HiIndex];
6956       if (Val < 0)
6957         continue;
6958       if (Val >= 4)
6959         break;
6960     }
6961
6962     Mask1[0] = PermMask[HiIndex];
6963     Mask1[1] = -1;
6964     Mask1[2] = PermMask[HiIndex^1];
6965     Mask1[3] = -1;
6966     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6967
6968     if (HiIndex >= 2) {
6969       Mask1[0] = PermMask[0];
6970       Mask1[1] = PermMask[1];
6971       Mask1[2] = HiIndex & 1 ? 6 : 4;
6972       Mask1[3] = HiIndex & 1 ? 4 : 6;
6973       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6974     }
6975
6976     Mask1[0] = HiIndex & 1 ? 2 : 0;
6977     Mask1[1] = HiIndex & 1 ? 0 : 2;
6978     Mask1[2] = PermMask[2];
6979     Mask1[3] = PermMask[3];
6980     if (Mask1[2] >= 0)
6981       Mask1[2] += 4;
6982     if (Mask1[3] >= 0)
6983       Mask1[3] += 4;
6984     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6985   }
6986
6987   // Break it into (shuffle shuffle_hi, shuffle_lo).
6988   int LoMask[] = { -1, -1, -1, -1 };
6989   int HiMask[] = { -1, -1, -1, -1 };
6990
6991   int *MaskPtr = LoMask;
6992   unsigned MaskIdx = 0;
6993   unsigned LoIdx = 0;
6994   unsigned HiIdx = 2;
6995   for (unsigned i = 0; i != 4; ++i) {
6996     if (i == 2) {
6997       MaskPtr = HiMask;
6998       MaskIdx = 1;
6999       LoIdx = 0;
7000       HiIdx = 2;
7001     }
7002     int Idx = PermMask[i];
7003     if (Idx < 0) {
7004       Locs[i] = std::make_pair(-1, -1);
7005     } else if (Idx < 4) {
7006       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7007       MaskPtr[LoIdx] = Idx;
7008       LoIdx++;
7009     } else {
7010       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7011       MaskPtr[HiIdx] = Idx;
7012       HiIdx++;
7013     }
7014   }
7015
7016   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7017   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7018   int MaskOps[] = { -1, -1, -1, -1 };
7019   for (unsigned i = 0; i != 4; ++i)
7020     if (Locs[i].first != -1)
7021       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7022   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7023 }
7024
7025 static bool MayFoldVectorLoad(SDValue V) {
7026   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7027     V = V.getOperand(0);
7028
7029   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7030     V = V.getOperand(0);
7031   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7032       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7033     // BUILD_VECTOR (load), undef
7034     V = V.getOperand(0);
7035
7036   return MayFoldLoad(V);
7037 }
7038
7039 static
7040 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7041   MVT VT = Op.getSimpleValueType();
7042
7043   // Canonizalize to v2f64.
7044   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7045   return DAG.getNode(ISD::BITCAST, dl, VT,
7046                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7047                                           V1, DAG));
7048 }
7049
7050 static
7051 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7052                         bool HasSSE2) {
7053   SDValue V1 = Op.getOperand(0);
7054   SDValue V2 = Op.getOperand(1);
7055   MVT VT = Op.getSimpleValueType();
7056
7057   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7058
7059   if (HasSSE2 && VT == MVT::v2f64)
7060     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7061
7062   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7063   return DAG.getNode(ISD::BITCAST, dl, VT,
7064                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7065                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7066                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7067 }
7068
7069 static
7070 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7071   SDValue V1 = Op.getOperand(0);
7072   SDValue V2 = Op.getOperand(1);
7073   MVT VT = Op.getSimpleValueType();
7074
7075   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7076          "unsupported shuffle type");
7077
7078   if (V2.getOpcode() == ISD::UNDEF)
7079     V2 = V1;
7080
7081   // v4i32 or v4f32
7082   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7083 }
7084
7085 static
7086 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7087   SDValue V1 = Op.getOperand(0);
7088   SDValue V2 = Op.getOperand(1);
7089   MVT VT = Op.getSimpleValueType();
7090   unsigned NumElems = VT.getVectorNumElements();
7091
7092   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7093   // operand of these instructions is only memory, so check if there's a
7094   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7095   // same masks.
7096   bool CanFoldLoad = false;
7097
7098   // Trivial case, when V2 comes from a load.
7099   if (MayFoldVectorLoad(V2))
7100     CanFoldLoad = true;
7101
7102   // When V1 is a load, it can be folded later into a store in isel, example:
7103   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7104   //    turns into:
7105   //  (MOVLPSmr addr:$src1, VR128:$src2)
7106   // So, recognize this potential and also use MOVLPS or MOVLPD
7107   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7108     CanFoldLoad = true;
7109
7110   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7111   if (CanFoldLoad) {
7112     if (HasSSE2 && NumElems == 2)
7113       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7114
7115     if (NumElems == 4)
7116       // If we don't care about the second element, proceed to use movss.
7117       if (SVOp->getMaskElt(1) != -1)
7118         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7119   }
7120
7121   // movl and movlp will both match v2i64, but v2i64 is never matched by
7122   // movl earlier because we make it strict to avoid messing with the movlp load
7123   // folding logic (see the code above getMOVLP call). Match it here then,
7124   // this is horrible, but will stay like this until we move all shuffle
7125   // matching to x86 specific nodes. Note that for the 1st condition all
7126   // types are matched with movsd.
7127   if (HasSSE2) {
7128     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7129     // as to remove this logic from here, as much as possible
7130     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7131       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7132     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7133   }
7134
7135   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7136
7137   // Invert the operand order and use SHUFPS to match it.
7138   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7139                               getShuffleSHUFImmediate(SVOp), DAG);
7140 }
7141
7142 // Reduce a vector shuffle to zext.
7143 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7144                                     SelectionDAG &DAG) {
7145   // PMOVZX is only available from SSE41.
7146   if (!Subtarget->hasSSE41())
7147     return SDValue();
7148
7149   MVT VT = Op.getSimpleValueType();
7150
7151   // Only AVX2 support 256-bit vector integer extending.
7152   if (!Subtarget->hasInt256() && VT.is256BitVector())
7153     return SDValue();
7154
7155   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7156   SDLoc DL(Op);
7157   SDValue V1 = Op.getOperand(0);
7158   SDValue V2 = Op.getOperand(1);
7159   unsigned NumElems = VT.getVectorNumElements();
7160
7161   // Extending is an unary operation and the element type of the source vector
7162   // won't be equal to or larger than i64.
7163   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7164       VT.getVectorElementType() == MVT::i64)
7165     return SDValue();
7166
7167   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7168   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7169   while ((1U << Shift) < NumElems) {
7170     if (SVOp->getMaskElt(1U << Shift) == 1)
7171       break;
7172     Shift += 1;
7173     // The maximal ratio is 8, i.e. from i8 to i64.
7174     if (Shift > 3)
7175       return SDValue();
7176   }
7177
7178   // Check the shuffle mask.
7179   unsigned Mask = (1U << Shift) - 1;
7180   for (unsigned i = 0; i != NumElems; ++i) {
7181     int EltIdx = SVOp->getMaskElt(i);
7182     if ((i & Mask) != 0 && EltIdx != -1)
7183       return SDValue();
7184     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7185       return SDValue();
7186   }
7187
7188   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7189   MVT NeVT = MVT::getIntegerVT(NBits);
7190   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7191
7192   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7193     return SDValue();
7194
7195   // Simplify the operand as it's prepared to be fed into shuffle.
7196   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7197   if (V1.getOpcode() == ISD::BITCAST &&
7198       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7199       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7200       V1.getOperand(0).getOperand(0)
7201         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7202     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7203     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7204     ConstantSDNode *CIdx =
7205       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7206     // If it's foldable, i.e. normal load with single use, we will let code
7207     // selection to fold it. Otherwise, we will short the conversion sequence.
7208     if (CIdx && CIdx->getZExtValue() == 0 &&
7209         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7210       MVT FullVT = V.getSimpleValueType();
7211       MVT V1VT = V1.getSimpleValueType();
7212       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7213         // The "ext_vec_elt" node is wider than the result node.
7214         // In this case we should extract subvector from V.
7215         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7216         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7217         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7218                                         FullVT.getVectorNumElements()/Ratio);
7219         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7220                         DAG.getIntPtrConstant(0));
7221       }
7222       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7223     }
7224   }
7225
7226   return DAG.getNode(ISD::BITCAST, DL, VT,
7227                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7228 }
7229
7230 static SDValue
7231 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7232                        SelectionDAG &DAG) {
7233   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7234   MVT VT = Op.getSimpleValueType();
7235   SDLoc dl(Op);
7236   SDValue V1 = Op.getOperand(0);
7237   SDValue V2 = Op.getOperand(1);
7238
7239   if (isZeroShuffle(SVOp))
7240     return getZeroVector(VT, Subtarget, DAG, dl);
7241
7242   // Handle splat operations
7243   if (SVOp->isSplat()) {
7244     // Use vbroadcast whenever the splat comes from a foldable load
7245     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7246     if (Broadcast.getNode())
7247       return Broadcast;
7248   }
7249
7250   // Check integer expanding shuffles.
7251   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7252   if (NewOp.getNode())
7253     return NewOp;
7254
7255   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7256   // do it!
7257   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7258       VT == MVT::v16i16 || VT == MVT::v32i8) {
7259     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7260     if (NewOp.getNode())
7261       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7262   } else if ((VT == MVT::v4i32 ||
7263              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7264     // FIXME: Figure out a cleaner way to do this.
7265     // Try to make use of movq to zero out the top part.
7266     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7267       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7268       if (NewOp.getNode()) {
7269         MVT NewVT = NewOp.getSimpleValueType();
7270         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7271                                NewVT, true, false))
7272           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7273                               DAG, Subtarget, dl);
7274       }
7275     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7276       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7277       if (NewOp.getNode()) {
7278         MVT NewVT = NewOp.getSimpleValueType();
7279         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7280           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7281                               DAG, Subtarget, dl);
7282       }
7283     }
7284   }
7285   return SDValue();
7286 }
7287
7288 SDValue
7289 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7290   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7291   SDValue V1 = Op.getOperand(0);
7292   SDValue V2 = Op.getOperand(1);
7293   MVT VT = Op.getSimpleValueType();
7294   SDLoc dl(Op);
7295   unsigned NumElems = VT.getVectorNumElements();
7296   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7297   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7298   bool V1IsSplat = false;
7299   bool V2IsSplat = false;
7300   bool HasSSE2 = Subtarget->hasSSE2();
7301   bool HasFp256    = Subtarget->hasFp256();
7302   bool HasInt256   = Subtarget->hasInt256();
7303   MachineFunction &MF = DAG.getMachineFunction();
7304   bool OptForSize = MF.getFunction()->getAttributes().
7305     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7306
7307   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7308
7309   if (V1IsUndef && V2IsUndef)
7310     return DAG.getUNDEF(VT);
7311
7312   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7313
7314   // Vector shuffle lowering takes 3 steps:
7315   //
7316   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7317   //    narrowing and commutation of operands should be handled.
7318   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7319   //    shuffle nodes.
7320   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7321   //    so the shuffle can be broken into other shuffles and the legalizer can
7322   //    try the lowering again.
7323   //
7324   // The general idea is that no vector_shuffle operation should be left to
7325   // be matched during isel, all of them must be converted to a target specific
7326   // node here.
7327
7328   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7329   // narrowing and commutation of operands should be handled. The actual code
7330   // doesn't include all of those, work in progress...
7331   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7332   if (NewOp.getNode())
7333     return NewOp;
7334
7335   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7336
7337   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7338   // unpckh_undef). Only use pshufd if speed is more important than size.
7339   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7340     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7341   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7342     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7343
7344   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7345       V2IsUndef && MayFoldVectorLoad(V1))
7346     return getMOVDDup(Op, dl, V1, DAG);
7347
7348   if (isMOVHLPS_v_undef_Mask(M, VT))
7349     return getMOVHighToLow(Op, dl, DAG);
7350
7351   // Use to match splats
7352   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7353       (VT == MVT::v2f64 || VT == MVT::v2i64))
7354     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7355
7356   if (isPSHUFDMask(M, VT)) {
7357     // The actual implementation will match the mask in the if above and then
7358     // during isel it can match several different instructions, not only pshufd
7359     // as its name says, sad but true, emulate the behavior for now...
7360     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7361       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7362
7363     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7364
7365     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7366       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7367
7368     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7369       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7370                                   DAG);
7371
7372     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7373                                 TargetMask, DAG);
7374   }
7375
7376   if (isPALIGNRMask(M, VT, Subtarget))
7377     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7378                                 getShufflePALIGNRImmediate(SVOp),
7379                                 DAG);
7380
7381   // Check if this can be converted into a logical shift.
7382   bool isLeft = false;
7383   unsigned ShAmt = 0;
7384   SDValue ShVal;
7385   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7386   if (isShift && ShVal.hasOneUse()) {
7387     // If the shifted value has multiple uses, it may be cheaper to use
7388     // v_set0 + movlhps or movhlps, etc.
7389     MVT EltVT = VT.getVectorElementType();
7390     ShAmt *= EltVT.getSizeInBits();
7391     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7392   }
7393
7394   if (isMOVLMask(M, VT)) {
7395     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7396       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7397     if (!isMOVLPMask(M, VT)) {
7398       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7399         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7400
7401       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7402         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7403     }
7404   }
7405
7406   // FIXME: fold these into legal mask.
7407   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7408     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7409
7410   if (isMOVHLPSMask(M, VT))
7411     return getMOVHighToLow(Op, dl, DAG);
7412
7413   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7414     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7415
7416   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7417     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7418
7419   if (isMOVLPMask(M, VT))
7420     return getMOVLP(Op, dl, DAG, HasSSE2);
7421
7422   if (ShouldXformToMOVHLPS(M, VT) ||
7423       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7424     return CommuteVectorShuffle(SVOp, DAG);
7425
7426   if (isShift) {
7427     // No better options. Use a vshldq / vsrldq.
7428     MVT EltVT = VT.getVectorElementType();
7429     ShAmt *= EltVT.getSizeInBits();
7430     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7431   }
7432
7433   bool Commuted = false;
7434   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7435   // 1,1,1,1 -> v8i16 though.
7436   V1IsSplat = isSplatVector(V1.getNode());
7437   V2IsSplat = isSplatVector(V2.getNode());
7438
7439   // Canonicalize the splat or undef, if present, to be on the RHS.
7440   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7441     CommuteVectorShuffleMask(M, NumElems);
7442     std::swap(V1, V2);
7443     std::swap(V1IsSplat, V2IsSplat);
7444     Commuted = true;
7445   }
7446
7447   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7448     // Shuffling low element of v1 into undef, just return v1.
7449     if (V2IsUndef)
7450       return V1;
7451     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7452     // the instruction selector will not match, so get a canonical MOVL with
7453     // swapped operands to undo the commute.
7454     return getMOVL(DAG, dl, VT, V2, V1);
7455   }
7456
7457   if (isUNPCKLMask(M, VT, HasInt256))
7458     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7459
7460   if (isUNPCKHMask(M, VT, HasInt256))
7461     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7462
7463   if (V2IsSplat) {
7464     // Normalize mask so all entries that point to V2 points to its first
7465     // element then try to match unpck{h|l} again. If match, return a
7466     // new vector_shuffle with the corrected mask.p
7467     SmallVector<int, 8> NewMask(M.begin(), M.end());
7468     NormalizeMask(NewMask, NumElems);
7469     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7470       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7471     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7472       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7473   }
7474
7475   if (Commuted) {
7476     // Commute is back and try unpck* again.
7477     // FIXME: this seems wrong.
7478     CommuteVectorShuffleMask(M, NumElems);
7479     std::swap(V1, V2);
7480     std::swap(V1IsSplat, V2IsSplat);
7481     Commuted = false;
7482
7483     if (isUNPCKLMask(M, VT, HasInt256))
7484       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7485
7486     if (isUNPCKHMask(M, VT, HasInt256))
7487       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7488   }
7489
7490   // Normalize the node to match x86 shuffle ops if needed
7491   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7492     return CommuteVectorShuffle(SVOp, DAG);
7493
7494   // The checks below are all present in isShuffleMaskLegal, but they are
7495   // inlined here right now to enable us to directly emit target specific
7496   // nodes, and remove one by one until they don't return Op anymore.
7497
7498   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7499       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7500     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7501       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7502   }
7503
7504   if (isPSHUFHWMask(M, VT, HasInt256))
7505     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7506                                 getShufflePSHUFHWImmediate(SVOp),
7507                                 DAG);
7508
7509   if (isPSHUFLWMask(M, VT, HasInt256))
7510     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7511                                 getShufflePSHUFLWImmediate(SVOp),
7512                                 DAG);
7513
7514   if (isSHUFPMask(M, VT))
7515     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7516                                 getShuffleSHUFImmediate(SVOp), DAG);
7517
7518   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7519     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7520   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7521     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7522
7523   //===--------------------------------------------------------------------===//
7524   // Generate target specific nodes for 128 or 256-bit shuffles only
7525   // supported in the AVX instruction set.
7526   //
7527
7528   // Handle VMOVDDUPY permutations
7529   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7530     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7531
7532   // Handle VPERMILPS/D* permutations
7533   if (isVPERMILPMask(M, VT)) {
7534     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7535       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7536                                   getShuffleSHUFImmediate(SVOp), DAG);
7537     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7538                                 getShuffleSHUFImmediate(SVOp), DAG);
7539   }
7540
7541   // Handle VPERM2F128/VPERM2I128 permutations
7542   if (isVPERM2X128Mask(M, VT, HasFp256))
7543     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7544                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7545
7546   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7547   if (BlendOp.getNode())
7548     return BlendOp;
7549
7550   unsigned Imm8;
7551   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7552     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7553
7554   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7555       VT.is512BitVector()) {
7556     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7557     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7558     SmallVector<SDValue, 16> permclMask;
7559     for (unsigned i = 0; i != NumElems; ++i) {
7560       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7561     }
7562
7563     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7564                                 &permclMask[0], NumElems);
7565     if (V2IsUndef)
7566       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7567       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7568                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7569     return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7570                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7571   }
7572
7573   //===--------------------------------------------------------------------===//
7574   // Since no target specific shuffle was selected for this generic one,
7575   // lower it into other known shuffles. FIXME: this isn't true yet, but
7576   // this is the plan.
7577   //
7578
7579   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7580   if (VT == MVT::v8i16) {
7581     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7582     if (NewOp.getNode())
7583       return NewOp;
7584   }
7585
7586   if (VT == MVT::v16i8) {
7587     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7588     if (NewOp.getNode())
7589       return NewOp;
7590   }
7591
7592   if (VT == MVT::v32i8) {
7593     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7594     if (NewOp.getNode())
7595       return NewOp;
7596   }
7597
7598   // Handle all 128-bit wide vectors with 4 elements, and match them with
7599   // several different shuffle types.
7600   if (NumElems == 4 && VT.is128BitVector())
7601     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7602
7603   // Handle general 256-bit shuffles
7604   if (VT.is256BitVector())
7605     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7606
7607   return SDValue();
7608 }
7609
7610 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7611   MVT VT = Op.getSimpleValueType();
7612   SDLoc dl(Op);
7613
7614   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7615     return SDValue();
7616
7617   if (VT.getSizeInBits() == 8) {
7618     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7619                                   Op.getOperand(0), Op.getOperand(1));
7620     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7621                                   DAG.getValueType(VT));
7622     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7623   }
7624
7625   if (VT.getSizeInBits() == 16) {
7626     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7627     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7628     if (Idx == 0)
7629       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7630                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7631                                      DAG.getNode(ISD::BITCAST, dl,
7632                                                  MVT::v4i32,
7633                                                  Op.getOperand(0)),
7634                                      Op.getOperand(1)));
7635     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7636                                   Op.getOperand(0), Op.getOperand(1));
7637     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7638                                   DAG.getValueType(VT));
7639     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7640   }
7641
7642   if (VT == MVT::f32) {
7643     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7644     // the result back to FR32 register. It's only worth matching if the
7645     // result has a single use which is a store or a bitcast to i32.  And in
7646     // the case of a store, it's not worth it if the index is a constant 0,
7647     // because a MOVSSmr can be used instead, which is smaller and faster.
7648     if (!Op.hasOneUse())
7649       return SDValue();
7650     SDNode *User = *Op.getNode()->use_begin();
7651     if ((User->getOpcode() != ISD::STORE ||
7652          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7653           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7654         (User->getOpcode() != ISD::BITCAST ||
7655          User->getValueType(0) != MVT::i32))
7656       return SDValue();
7657     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7658                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7659                                               Op.getOperand(0)),
7660                                               Op.getOperand(1));
7661     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7662   }
7663
7664   if (VT == MVT::i32 || VT == MVT::i64) {
7665     // ExtractPS/pextrq works with constant index.
7666     if (isa<ConstantSDNode>(Op.getOperand(1)))
7667       return Op;
7668   }
7669   return SDValue();
7670 }
7671
7672 SDValue
7673 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7674                                            SelectionDAG &DAG) const {
7675   SDLoc dl(Op);
7676   SDValue Vec = Op.getOperand(0);
7677   MVT VecVT = Vec.getSimpleValueType();
7678   SDValue Idx = Op.getOperand(1);
7679   if (!isa<ConstantSDNode>(Idx)) {
7680     if (VecVT.is512BitVector() ||
7681         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7682          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7683
7684       MVT MaskEltVT =
7685         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7686       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7687                                     MaskEltVT.getSizeInBits());
7688
7689       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7690       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7691                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7692                                 Idx, DAG.getConstant(0, getPointerTy()));
7693       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7694       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7695                         Perm, DAG.getConstant(0, getPointerTy()));
7696     }
7697     return SDValue();
7698   }
7699
7700   // If this is a 256-bit vector result, first extract the 128-bit vector and
7701   // then extract the element from the 128-bit vector.
7702   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7703
7704     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7705     // Get the 128-bit vector.
7706     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7707     MVT EltVT = VecVT.getVectorElementType();
7708
7709     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7710
7711     //if (IdxVal >= NumElems/2)
7712     //  IdxVal -= NumElems/2;
7713     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7714     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7715                        DAG.getConstant(IdxVal, MVT::i32));
7716   }
7717
7718   assert(VecVT.is128BitVector() && "Unexpected vector length");
7719
7720   if (Subtarget->hasSSE41()) {
7721     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7722     if (Res.getNode())
7723       return Res;
7724   }
7725
7726   MVT VT = Op.getSimpleValueType();
7727   // TODO: handle v16i8.
7728   if (VT.getSizeInBits() == 16) {
7729     SDValue Vec = Op.getOperand(0);
7730     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7731     if (Idx == 0)
7732       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7733                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7734                                      DAG.getNode(ISD::BITCAST, dl,
7735                                                  MVT::v4i32, Vec),
7736                                      Op.getOperand(1)));
7737     // Transform it so it match pextrw which produces a 32-bit result.
7738     MVT EltVT = MVT::i32;
7739     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7740                                   Op.getOperand(0), Op.getOperand(1));
7741     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7742                                   DAG.getValueType(VT));
7743     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7744   }
7745
7746   if (VT.getSizeInBits() == 32) {
7747     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7748     if (Idx == 0)
7749       return Op;
7750
7751     // SHUFPS the element to the lowest double word, then movss.
7752     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7753     MVT VVT = Op.getOperand(0).getSimpleValueType();
7754     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7755                                        DAG.getUNDEF(VVT), Mask);
7756     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7757                        DAG.getIntPtrConstant(0));
7758   }
7759
7760   if (VT.getSizeInBits() == 64) {
7761     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7762     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7763     //        to match extract_elt for f64.
7764     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7765     if (Idx == 0)
7766       return Op;
7767
7768     // UNPCKHPD the element to the lowest double word, then movsd.
7769     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7770     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7771     int Mask[2] = { 1, -1 };
7772     MVT VVT = Op.getOperand(0).getSimpleValueType();
7773     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7774                                        DAG.getUNDEF(VVT), Mask);
7775     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7776                        DAG.getIntPtrConstant(0));
7777   }
7778
7779   return SDValue();
7780 }
7781
7782 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7783   MVT VT = Op.getSimpleValueType();
7784   MVT EltVT = VT.getVectorElementType();
7785   SDLoc dl(Op);
7786
7787   SDValue N0 = Op.getOperand(0);
7788   SDValue N1 = Op.getOperand(1);
7789   SDValue N2 = Op.getOperand(2);
7790
7791   if (!VT.is128BitVector())
7792     return SDValue();
7793
7794   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7795       isa<ConstantSDNode>(N2)) {
7796     unsigned Opc;
7797     if (VT == MVT::v8i16)
7798       Opc = X86ISD::PINSRW;
7799     else if (VT == MVT::v16i8)
7800       Opc = X86ISD::PINSRB;
7801     else
7802       Opc = X86ISD::PINSRB;
7803
7804     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7805     // argument.
7806     if (N1.getValueType() != MVT::i32)
7807       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7808     if (N2.getValueType() != MVT::i32)
7809       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7810     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7811   }
7812
7813   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7814     // Bits [7:6] of the constant are the source select.  This will always be
7815     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7816     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7817     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7818     // Bits [5:4] of the constant are the destination select.  This is the
7819     //  value of the incoming immediate.
7820     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7821     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7822     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7823     // Create this as a scalar to vector..
7824     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7825     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7826   }
7827
7828   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7829     // PINSR* works with constant index.
7830     return Op;
7831   }
7832   return SDValue();
7833 }
7834
7835 SDValue
7836 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7837   MVT VT = Op.getSimpleValueType();
7838   MVT EltVT = VT.getVectorElementType();
7839
7840   SDLoc dl(Op);
7841   SDValue N0 = Op.getOperand(0);
7842   SDValue N1 = Op.getOperand(1);
7843   SDValue N2 = Op.getOperand(2);
7844
7845   // If this is a 256-bit vector result, first extract the 128-bit vector,
7846   // insert the element into the extracted half and then place it back.
7847   if (VT.is256BitVector() || VT.is512BitVector()) {
7848     if (!isa<ConstantSDNode>(N2))
7849       return SDValue();
7850
7851     // Get the desired 128-bit vector half.
7852     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7853     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7854
7855     // Insert the element into the desired half.
7856     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7857     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7858
7859     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7860                     DAG.getConstant(IdxIn128, MVT::i32));
7861
7862     // Insert the changed part back to the 256-bit vector
7863     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7864   }
7865
7866   if (Subtarget->hasSSE41())
7867     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7868
7869   if (EltVT == MVT::i8)
7870     return SDValue();
7871
7872   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7873     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7874     // as its second argument.
7875     if (N1.getValueType() != MVT::i32)
7876       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7877     if (N2.getValueType() != MVT::i32)
7878       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7879     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7880   }
7881   return SDValue();
7882 }
7883
7884 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7885   SDLoc dl(Op);
7886   MVT OpVT = Op.getSimpleValueType();
7887
7888   // If this is a 256-bit vector result, first insert into a 128-bit
7889   // vector and then insert into the 256-bit vector.
7890   if (!OpVT.is128BitVector()) {
7891     // Insert into a 128-bit vector.
7892     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7893     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7894                                  OpVT.getVectorNumElements() / SizeFactor);
7895
7896     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7897
7898     // Insert the 128-bit vector.
7899     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7900   }
7901
7902   if (OpVT == MVT::v1i64 &&
7903       Op.getOperand(0).getValueType() == MVT::i64)
7904     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7905
7906   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7907   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7908   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7909                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7910 }
7911
7912 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7913 // a simple subregister reference or explicit instructions to grab
7914 // upper bits of a vector.
7915 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7916                                       SelectionDAG &DAG) {
7917   SDLoc dl(Op);
7918   SDValue In =  Op.getOperand(0);
7919   SDValue Idx = Op.getOperand(1);
7920   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7921   MVT ResVT   = Op.getSimpleValueType();
7922   MVT InVT    = In.getSimpleValueType();
7923
7924   if (Subtarget->hasFp256()) {
7925     if (ResVT.is128BitVector() &&
7926         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7927         isa<ConstantSDNode>(Idx)) {
7928       return Extract128BitVector(In, IdxVal, DAG, dl);
7929     }
7930     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7931         isa<ConstantSDNode>(Idx)) {
7932       return Extract256BitVector(In, IdxVal, DAG, dl);
7933     }
7934   }
7935   return SDValue();
7936 }
7937
7938 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7939 // simple superregister reference or explicit instructions to insert
7940 // the upper bits of a vector.
7941 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7942                                      SelectionDAG &DAG) {
7943   if (Subtarget->hasFp256()) {
7944     SDLoc dl(Op.getNode());
7945     SDValue Vec = Op.getNode()->getOperand(0);
7946     SDValue SubVec = Op.getNode()->getOperand(1);
7947     SDValue Idx = Op.getNode()->getOperand(2);
7948
7949     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
7950          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
7951         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
7952         isa<ConstantSDNode>(Idx)) {
7953       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7954       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7955     }
7956
7957     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
7958         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
7959         isa<ConstantSDNode>(Idx)) {
7960       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7961       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7962     }
7963   }
7964   return SDValue();
7965 }
7966
7967 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7968 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7969 // one of the above mentioned nodes. It has to be wrapped because otherwise
7970 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7971 // be used to form addressing mode. These wrapped nodes will be selected
7972 // into MOV32ri.
7973 SDValue
7974 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7975   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7976
7977   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7978   // global base reg.
7979   unsigned char OpFlag = 0;
7980   unsigned WrapperKind = X86ISD::Wrapper;
7981   CodeModel::Model M = getTargetMachine().getCodeModel();
7982
7983   if (Subtarget->isPICStyleRIPRel() &&
7984       (M == CodeModel::Small || M == CodeModel::Kernel))
7985     WrapperKind = X86ISD::WrapperRIP;
7986   else if (Subtarget->isPICStyleGOT())
7987     OpFlag = X86II::MO_GOTOFF;
7988   else if (Subtarget->isPICStyleStubPIC())
7989     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7990
7991   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7992                                              CP->getAlignment(),
7993                                              CP->getOffset(), OpFlag);
7994   SDLoc DL(CP);
7995   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7996   // With PIC, the address is actually $g + Offset.
7997   if (OpFlag) {
7998     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7999                          DAG.getNode(X86ISD::GlobalBaseReg,
8000                                      SDLoc(), getPointerTy()),
8001                          Result);
8002   }
8003
8004   return Result;
8005 }
8006
8007 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8008   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8009
8010   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8011   // global base reg.
8012   unsigned char OpFlag = 0;
8013   unsigned WrapperKind = X86ISD::Wrapper;
8014   CodeModel::Model M = getTargetMachine().getCodeModel();
8015
8016   if (Subtarget->isPICStyleRIPRel() &&
8017       (M == CodeModel::Small || M == CodeModel::Kernel))
8018     WrapperKind = X86ISD::WrapperRIP;
8019   else if (Subtarget->isPICStyleGOT())
8020     OpFlag = X86II::MO_GOTOFF;
8021   else if (Subtarget->isPICStyleStubPIC())
8022     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8023
8024   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8025                                           OpFlag);
8026   SDLoc DL(JT);
8027   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8028
8029   // With PIC, the address is actually $g + Offset.
8030   if (OpFlag)
8031     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8032                          DAG.getNode(X86ISD::GlobalBaseReg,
8033                                      SDLoc(), getPointerTy()),
8034                          Result);
8035
8036   return Result;
8037 }
8038
8039 SDValue
8040 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8041   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8042
8043   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8044   // global base reg.
8045   unsigned char OpFlag = 0;
8046   unsigned WrapperKind = X86ISD::Wrapper;
8047   CodeModel::Model M = getTargetMachine().getCodeModel();
8048
8049   if (Subtarget->isPICStyleRIPRel() &&
8050       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8051     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8052       OpFlag = X86II::MO_GOTPCREL;
8053     WrapperKind = X86ISD::WrapperRIP;
8054   } else if (Subtarget->isPICStyleGOT()) {
8055     OpFlag = X86II::MO_GOT;
8056   } else if (Subtarget->isPICStyleStubPIC()) {
8057     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8058   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8059     OpFlag = X86II::MO_DARWIN_NONLAZY;
8060   }
8061
8062   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8063
8064   SDLoc DL(Op);
8065   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8066
8067   // With PIC, the address is actually $g + Offset.
8068   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8069       !Subtarget->is64Bit()) {
8070     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8071                          DAG.getNode(X86ISD::GlobalBaseReg,
8072                                      SDLoc(), getPointerTy()),
8073                          Result);
8074   }
8075
8076   // For symbols that require a load from a stub to get the address, emit the
8077   // load.
8078   if (isGlobalStubReference(OpFlag))
8079     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8080                          MachinePointerInfo::getGOT(), false, false, false, 0);
8081
8082   return Result;
8083 }
8084
8085 SDValue
8086 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8087   // Create the TargetBlockAddressAddress node.
8088   unsigned char OpFlags =
8089     Subtarget->ClassifyBlockAddressReference();
8090   CodeModel::Model M = getTargetMachine().getCodeModel();
8091   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8092   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8093   SDLoc dl(Op);
8094   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8095                                              OpFlags);
8096
8097   if (Subtarget->isPICStyleRIPRel() &&
8098       (M == CodeModel::Small || M == CodeModel::Kernel))
8099     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8100   else
8101     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8102
8103   // With PIC, the address is actually $g + Offset.
8104   if (isGlobalRelativeToPICBase(OpFlags)) {
8105     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8106                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8107                          Result);
8108   }
8109
8110   return Result;
8111 }
8112
8113 SDValue
8114 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8115                                       int64_t Offset, SelectionDAG &DAG) const {
8116   // Create the TargetGlobalAddress node, folding in the constant
8117   // offset if it is legal.
8118   unsigned char OpFlags =
8119     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8120   CodeModel::Model M = getTargetMachine().getCodeModel();
8121   SDValue Result;
8122   if (OpFlags == X86II::MO_NO_FLAG &&
8123       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8124     // A direct static reference to a global.
8125     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8126     Offset = 0;
8127   } else {
8128     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8129   }
8130
8131   if (Subtarget->isPICStyleRIPRel() &&
8132       (M == CodeModel::Small || M == CodeModel::Kernel))
8133     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8134   else
8135     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8136
8137   // With PIC, the address is actually $g + Offset.
8138   if (isGlobalRelativeToPICBase(OpFlags)) {
8139     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8140                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8141                          Result);
8142   }
8143
8144   // For globals that require a load from a stub to get the address, emit the
8145   // load.
8146   if (isGlobalStubReference(OpFlags))
8147     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8148                          MachinePointerInfo::getGOT(), false, false, false, 0);
8149
8150   // If there was a non-zero offset that we didn't fold, create an explicit
8151   // addition for it.
8152   if (Offset != 0)
8153     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8154                          DAG.getConstant(Offset, getPointerTy()));
8155
8156   return Result;
8157 }
8158
8159 SDValue
8160 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8161   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8162   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8163   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8164 }
8165
8166 static SDValue
8167 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8168            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8169            unsigned char OperandFlags, bool LocalDynamic = false) {
8170   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8171   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8172   SDLoc dl(GA);
8173   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8174                                            GA->getValueType(0),
8175                                            GA->getOffset(),
8176                                            OperandFlags);
8177
8178   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8179                                            : X86ISD::TLSADDR;
8180
8181   if (InFlag) {
8182     SDValue Ops[] = { Chain,  TGA, *InFlag };
8183     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8184   } else {
8185     SDValue Ops[]  = { Chain, TGA };
8186     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8187   }
8188
8189   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8190   MFI->setAdjustsStack(true);
8191
8192   SDValue Flag = Chain.getValue(1);
8193   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8194 }
8195
8196 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8197 static SDValue
8198 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8199                                 const EVT PtrVT) {
8200   SDValue InFlag;
8201   SDLoc dl(GA);  // ? function entry point might be better
8202   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8203                                    DAG.getNode(X86ISD::GlobalBaseReg,
8204                                                SDLoc(), PtrVT), InFlag);
8205   InFlag = Chain.getValue(1);
8206
8207   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8208 }
8209
8210 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8211 static SDValue
8212 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8213                                 const EVT PtrVT) {
8214   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8215                     X86::RAX, X86II::MO_TLSGD);
8216 }
8217
8218 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8219                                            SelectionDAG &DAG,
8220                                            const EVT PtrVT,
8221                                            bool is64Bit) {
8222   SDLoc dl(GA);
8223
8224   // Get the start address of the TLS block for this module.
8225   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8226       .getInfo<X86MachineFunctionInfo>();
8227   MFI->incNumLocalDynamicTLSAccesses();
8228
8229   SDValue Base;
8230   if (is64Bit) {
8231     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8232                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8233   } else {
8234     SDValue InFlag;
8235     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8236         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8237     InFlag = Chain.getValue(1);
8238     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8239                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8240   }
8241
8242   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8243   // of Base.
8244
8245   // Build x@dtpoff.
8246   unsigned char OperandFlags = X86II::MO_DTPOFF;
8247   unsigned WrapperKind = X86ISD::Wrapper;
8248   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8249                                            GA->getValueType(0),
8250                                            GA->getOffset(), OperandFlags);
8251   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8252
8253   // Add x@dtpoff with the base.
8254   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8255 }
8256
8257 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8258 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8259                                    const EVT PtrVT, TLSModel::Model model,
8260                                    bool is64Bit, bool isPIC) {
8261   SDLoc dl(GA);
8262
8263   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8264   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8265                                                          is64Bit ? 257 : 256));
8266
8267   SDValue ThreadPointer =
8268       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8269                   MachinePointerInfo(Ptr), false, false, false, 0);
8270
8271   unsigned char OperandFlags = 0;
8272   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8273   // initialexec.
8274   unsigned WrapperKind = X86ISD::Wrapper;
8275   if (model == TLSModel::LocalExec) {
8276     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8277   } else if (model == TLSModel::InitialExec) {
8278     if (is64Bit) {
8279       OperandFlags = X86II::MO_GOTTPOFF;
8280       WrapperKind = X86ISD::WrapperRIP;
8281     } else {
8282       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8283     }
8284   } else {
8285     llvm_unreachable("Unexpected model");
8286   }
8287
8288   // emit "addl x@ntpoff,%eax" (local exec)
8289   // or "addl x@indntpoff,%eax" (initial exec)
8290   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8291   SDValue TGA =
8292       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8293                                  GA->getOffset(), OperandFlags);
8294   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8295
8296   if (model == TLSModel::InitialExec) {
8297     if (isPIC && !is64Bit) {
8298       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8299                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8300                            Offset);
8301     }
8302
8303     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8304                          MachinePointerInfo::getGOT(), false, false, false, 0);
8305   }
8306
8307   // The address of the thread local variable is the add of the thread
8308   // pointer with the offset of the variable.
8309   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8310 }
8311
8312 SDValue
8313 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8314
8315   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8316   const GlobalValue *GV = GA->getGlobal();
8317
8318   if (Subtarget->isTargetELF()) {
8319     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8320
8321     switch (model) {
8322       case TLSModel::GeneralDynamic:
8323         if (Subtarget->is64Bit())
8324           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8325         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8326       case TLSModel::LocalDynamic:
8327         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8328                                            Subtarget->is64Bit());
8329       case TLSModel::InitialExec:
8330       case TLSModel::LocalExec:
8331         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8332                                    Subtarget->is64Bit(),
8333                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8334     }
8335     llvm_unreachable("Unknown TLS model.");
8336   }
8337
8338   if (Subtarget->isTargetDarwin()) {
8339     // Darwin only has one model of TLS.  Lower to that.
8340     unsigned char OpFlag = 0;
8341     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8342                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8343
8344     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8345     // global base reg.
8346     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8347                   !Subtarget->is64Bit();
8348     if (PIC32)
8349       OpFlag = X86II::MO_TLVP_PIC_BASE;
8350     else
8351       OpFlag = X86II::MO_TLVP;
8352     SDLoc DL(Op);
8353     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8354                                                 GA->getValueType(0),
8355                                                 GA->getOffset(), OpFlag);
8356     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8357
8358     // With PIC32, the address is actually $g + Offset.
8359     if (PIC32)
8360       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8361                            DAG.getNode(X86ISD::GlobalBaseReg,
8362                                        SDLoc(), getPointerTy()),
8363                            Offset);
8364
8365     // Lowering the machine isd will make sure everything is in the right
8366     // location.
8367     SDValue Chain = DAG.getEntryNode();
8368     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8369     SDValue Args[] = { Chain, Offset };
8370     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8371
8372     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8373     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8374     MFI->setAdjustsStack(true);
8375
8376     // And our return value (tls address) is in the standard call return value
8377     // location.
8378     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8379     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8380                               Chain.getValue(1));
8381   }
8382
8383   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8384     // Just use the implicit TLS architecture
8385     // Need to generate someting similar to:
8386     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8387     //                                  ; from TEB
8388     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8389     //   mov     rcx, qword [rdx+rcx*8]
8390     //   mov     eax, .tls$:tlsvar
8391     //   [rax+rcx] contains the address
8392     // Windows 64bit: gs:0x58
8393     // Windows 32bit: fs:__tls_array
8394
8395     // If GV is an alias then use the aliasee for determining
8396     // thread-localness.
8397     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8398       GV = GA->resolveAliasedGlobal(false);
8399     SDLoc dl(GA);
8400     SDValue Chain = DAG.getEntryNode();
8401
8402     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8403     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8404     // use its literal value of 0x2C.
8405     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8406                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8407                                                              256)
8408                                         : Type::getInt32PtrTy(*DAG.getContext(),
8409                                                               257));
8410
8411     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8412       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8413         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8414
8415     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8416                                         MachinePointerInfo(Ptr),
8417                                         false, false, false, 0);
8418
8419     // Load the _tls_index variable
8420     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8421     if (Subtarget->is64Bit())
8422       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8423                            IDX, MachinePointerInfo(), MVT::i32,
8424                            false, false, 0);
8425     else
8426       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8427                         false, false, false, 0);
8428
8429     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8430                                     getPointerTy());
8431     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8432
8433     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8434     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8435                       false, false, false, 0);
8436
8437     // Get the offset of start of .tls section
8438     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8439                                              GA->getValueType(0),
8440                                              GA->getOffset(), X86II::MO_SECREL);
8441     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8442
8443     // The address of the thread local variable is the add of the thread
8444     // pointer with the offset of the variable.
8445     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8446   }
8447
8448   llvm_unreachable("TLS not implemented for this target.");
8449 }
8450
8451 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8452 /// and take a 2 x i32 value to shift plus a shift amount.
8453 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8454   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8455   EVT VT = Op.getValueType();
8456   unsigned VTBits = VT.getSizeInBits();
8457   SDLoc dl(Op);
8458   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8459   SDValue ShOpLo = Op.getOperand(0);
8460   SDValue ShOpHi = Op.getOperand(1);
8461   SDValue ShAmt  = Op.getOperand(2);
8462   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8463                                      DAG.getConstant(VTBits - 1, MVT::i8))
8464                        : DAG.getConstant(0, VT);
8465
8466   SDValue Tmp2, Tmp3;
8467   if (Op.getOpcode() == ISD::SHL_PARTS) {
8468     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8469     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8470   } else {
8471     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8472     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8473   }
8474
8475   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8476                                 DAG.getConstant(VTBits, MVT::i8));
8477   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8478                              AndNode, DAG.getConstant(0, MVT::i8));
8479
8480   SDValue Hi, Lo;
8481   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8482   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8483   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8484
8485   if (Op.getOpcode() == ISD::SHL_PARTS) {
8486     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8487     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8488   } else {
8489     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8490     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8491   }
8492
8493   SDValue Ops[2] = { Lo, Hi };
8494   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8495 }
8496
8497 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8498                                            SelectionDAG &DAG) const {
8499   EVT SrcVT = Op.getOperand(0).getValueType();
8500
8501   if (SrcVT.isVector())
8502     return SDValue();
8503
8504   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8505          "Unknown SINT_TO_FP to lower!");
8506
8507   // These are really Legal; return the operand so the caller accepts it as
8508   // Legal.
8509   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8510     return Op;
8511   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8512       Subtarget->is64Bit()) {
8513     return Op;
8514   }
8515
8516   SDLoc dl(Op);
8517   unsigned Size = SrcVT.getSizeInBits()/8;
8518   MachineFunction &MF = DAG.getMachineFunction();
8519   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8520   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8521   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8522                                StackSlot,
8523                                MachinePointerInfo::getFixedStack(SSFI),
8524                                false, false, 0);
8525   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8526 }
8527
8528 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8529                                      SDValue StackSlot,
8530                                      SelectionDAG &DAG) const {
8531   // Build the FILD
8532   SDLoc DL(Op);
8533   SDVTList Tys;
8534   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8535   if (useSSE)
8536     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8537   else
8538     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8539
8540   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8541
8542   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8543   MachineMemOperand *MMO;
8544   if (FI) {
8545     int SSFI = FI->getIndex();
8546     MMO =
8547       DAG.getMachineFunction()
8548       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8549                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8550   } else {
8551     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8552     StackSlot = StackSlot.getOperand(1);
8553   }
8554   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8555   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8556                                            X86ISD::FILD, DL,
8557                                            Tys, Ops, array_lengthof(Ops),
8558                                            SrcVT, MMO);
8559
8560   if (useSSE) {
8561     Chain = Result.getValue(1);
8562     SDValue InFlag = Result.getValue(2);
8563
8564     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8565     // shouldn't be necessary except that RFP cannot be live across
8566     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8567     MachineFunction &MF = DAG.getMachineFunction();
8568     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8569     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8570     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8571     Tys = DAG.getVTList(MVT::Other);
8572     SDValue Ops[] = {
8573       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8574     };
8575     MachineMemOperand *MMO =
8576       DAG.getMachineFunction()
8577       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8578                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8579
8580     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8581                                     Ops, array_lengthof(Ops),
8582                                     Op.getValueType(), MMO);
8583     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8584                          MachinePointerInfo::getFixedStack(SSFI),
8585                          false, false, false, 0);
8586   }
8587
8588   return Result;
8589 }
8590
8591 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8592 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8593                                                SelectionDAG &DAG) const {
8594   // This algorithm is not obvious. Here it is what we're trying to output:
8595   /*
8596      movq       %rax,  %xmm0
8597      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8598      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8599      #ifdef __SSE3__
8600        haddpd   %xmm0, %xmm0
8601      #else
8602        pshufd   $0x4e, %xmm0, %xmm1
8603        addpd    %xmm1, %xmm0
8604      #endif
8605   */
8606
8607   SDLoc dl(Op);
8608   LLVMContext *Context = DAG.getContext();
8609
8610   // Build some magic constants.
8611   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8612   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8613   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8614
8615   SmallVector<Constant*,2> CV1;
8616   CV1.push_back(
8617     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8618                                       APInt(64, 0x4330000000000000ULL))));
8619   CV1.push_back(
8620     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8621                                       APInt(64, 0x4530000000000000ULL))));
8622   Constant *C1 = ConstantVector::get(CV1);
8623   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8624
8625   // Load the 64-bit value into an XMM register.
8626   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8627                             Op.getOperand(0));
8628   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8629                               MachinePointerInfo::getConstantPool(),
8630                               false, false, false, 16);
8631   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8632                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8633                               CLod0);
8634
8635   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8636                               MachinePointerInfo::getConstantPool(),
8637                               false, false, false, 16);
8638   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8639   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8640   SDValue Result;
8641
8642   if (Subtarget->hasSSE3()) {
8643     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8644     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8645   } else {
8646     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8647     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8648                                            S2F, 0x4E, DAG);
8649     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8650                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8651                          Sub);
8652   }
8653
8654   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8655                      DAG.getIntPtrConstant(0));
8656 }
8657
8658 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8659 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8660                                                SelectionDAG &DAG) const {
8661   SDLoc dl(Op);
8662   // FP constant to bias correct the final result.
8663   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8664                                    MVT::f64);
8665
8666   // Load the 32-bit value into an XMM register.
8667   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8668                              Op.getOperand(0));
8669
8670   // Zero out the upper parts of the register.
8671   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8672
8673   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8674                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8675                      DAG.getIntPtrConstant(0));
8676
8677   // Or the load with the bias.
8678   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8679                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8680                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8681                                                    MVT::v2f64, Load)),
8682                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8683                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8684                                                    MVT::v2f64, Bias)));
8685   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8686                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8687                    DAG.getIntPtrConstant(0));
8688
8689   // Subtract the bias.
8690   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8691
8692   // Handle final rounding.
8693   EVT DestVT = Op.getValueType();
8694
8695   if (DestVT.bitsLT(MVT::f64))
8696     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8697                        DAG.getIntPtrConstant(0));
8698   if (DestVT.bitsGT(MVT::f64))
8699     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8700
8701   // Handle final rounding.
8702   return Sub;
8703 }
8704
8705 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8706                                                SelectionDAG &DAG) const {
8707   SDValue N0 = Op.getOperand(0);
8708   EVT SVT = N0.getValueType();
8709   SDLoc dl(Op);
8710
8711   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8712           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8713          "Custom UINT_TO_FP is not supported!");
8714
8715   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8716                              SVT.getVectorNumElements());
8717   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8718                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8719 }
8720
8721 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8722                                            SelectionDAG &DAG) const {
8723   SDValue N0 = Op.getOperand(0);
8724   SDLoc dl(Op);
8725
8726   if (Op.getValueType().isVector())
8727     return lowerUINT_TO_FP_vec(Op, DAG);
8728
8729   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8730   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8731   // the optimization here.
8732   if (DAG.SignBitIsZero(N0))
8733     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8734
8735   EVT SrcVT = N0.getValueType();
8736   EVT DstVT = Op.getValueType();
8737   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8738     return LowerUINT_TO_FP_i64(Op, DAG);
8739   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8740     return LowerUINT_TO_FP_i32(Op, DAG);
8741   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8742     return SDValue();
8743
8744   // Make a 64-bit buffer, and use it to build an FILD.
8745   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8746   if (SrcVT == MVT::i32) {
8747     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8748     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8749                                      getPointerTy(), StackSlot, WordOff);
8750     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8751                                   StackSlot, MachinePointerInfo(),
8752                                   false, false, 0);
8753     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8754                                   OffsetSlot, MachinePointerInfo(),
8755                                   false, false, 0);
8756     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8757     return Fild;
8758   }
8759
8760   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8761   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8762                                StackSlot, MachinePointerInfo(),
8763                                false, false, 0);
8764   // For i64 source, we need to add the appropriate power of 2 if the input
8765   // was negative.  This is the same as the optimization in
8766   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8767   // we must be careful to do the computation in x87 extended precision, not
8768   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8769   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8770   MachineMemOperand *MMO =
8771     DAG.getMachineFunction()
8772     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8773                           MachineMemOperand::MOLoad, 8, 8);
8774
8775   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8776   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8777   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8778                                          array_lengthof(Ops), MVT::i64, MMO);
8779
8780   APInt FF(32, 0x5F800000ULL);
8781
8782   // Check whether the sign bit is set.
8783   SDValue SignSet = DAG.getSetCC(dl,
8784                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8785                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8786                                  ISD::SETLT);
8787
8788   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8789   SDValue FudgePtr = DAG.getConstantPool(
8790                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8791                                          getPointerTy());
8792
8793   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8794   SDValue Zero = DAG.getIntPtrConstant(0);
8795   SDValue Four = DAG.getIntPtrConstant(4);
8796   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8797                                Zero, Four);
8798   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8799
8800   // Load the value out, extending it from f32 to f80.
8801   // FIXME: Avoid the extend by constructing the right constant pool?
8802   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8803                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8804                                  MVT::f32, false, false, 4);
8805   // Extend everything to 80 bits to force it to be done on x87.
8806   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8807   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8808 }
8809
8810 std::pair<SDValue,SDValue>
8811 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8812                                     bool IsSigned, bool IsReplace) const {
8813   SDLoc DL(Op);
8814
8815   EVT DstTy = Op.getValueType();
8816
8817   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8818     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8819     DstTy = MVT::i64;
8820   }
8821
8822   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8823          DstTy.getSimpleVT() >= MVT::i16 &&
8824          "Unknown FP_TO_INT to lower!");
8825
8826   // These are really Legal.
8827   if (DstTy == MVT::i32 &&
8828       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8829     return std::make_pair(SDValue(), SDValue());
8830   if (Subtarget->is64Bit() &&
8831       DstTy == MVT::i64 &&
8832       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8833     return std::make_pair(SDValue(), SDValue());
8834
8835   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8836   // stack slot, or into the FTOL runtime function.
8837   MachineFunction &MF = DAG.getMachineFunction();
8838   unsigned MemSize = DstTy.getSizeInBits()/8;
8839   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8840   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8841
8842   unsigned Opc;
8843   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8844     Opc = X86ISD::WIN_FTOL;
8845   else
8846     switch (DstTy.getSimpleVT().SimpleTy) {
8847     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8848     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8849     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8850     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8851     }
8852
8853   SDValue Chain = DAG.getEntryNode();
8854   SDValue Value = Op.getOperand(0);
8855   EVT TheVT = Op.getOperand(0).getValueType();
8856   // FIXME This causes a redundant load/store if the SSE-class value is already
8857   // in memory, such as if it is on the callstack.
8858   if (isScalarFPTypeInSSEReg(TheVT)) {
8859     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8860     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8861                          MachinePointerInfo::getFixedStack(SSFI),
8862                          false, false, 0);
8863     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8864     SDValue Ops[] = {
8865       Chain, StackSlot, DAG.getValueType(TheVT)
8866     };
8867
8868     MachineMemOperand *MMO =
8869       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8870                               MachineMemOperand::MOLoad, MemSize, MemSize);
8871     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8872                                     array_lengthof(Ops), DstTy, MMO);
8873     Chain = Value.getValue(1);
8874     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8875     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8876   }
8877
8878   MachineMemOperand *MMO =
8879     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8880                             MachineMemOperand::MOStore, MemSize, MemSize);
8881
8882   if (Opc != X86ISD::WIN_FTOL) {
8883     // Build the FP_TO_INT*_IN_MEM
8884     SDValue Ops[] = { Chain, Value, StackSlot };
8885     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8886                                            Ops, array_lengthof(Ops), DstTy,
8887                                            MMO);
8888     return std::make_pair(FIST, StackSlot);
8889   } else {
8890     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8891       DAG.getVTList(MVT::Other, MVT::Glue),
8892       Chain, Value);
8893     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8894       MVT::i32, ftol.getValue(1));
8895     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8896       MVT::i32, eax.getValue(2));
8897     SDValue Ops[] = { eax, edx };
8898     SDValue pair = IsReplace
8899       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8900       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8901     return std::make_pair(pair, SDValue());
8902   }
8903 }
8904
8905 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8906                               const X86Subtarget *Subtarget) {
8907   MVT VT = Op->getSimpleValueType(0);
8908   SDValue In = Op->getOperand(0);
8909   MVT InVT = In.getSimpleValueType();
8910   SDLoc dl(Op);
8911
8912   // Optimize vectors in AVX mode:
8913   //
8914   //   v8i16 -> v8i32
8915   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8916   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8917   //   Concat upper and lower parts.
8918   //
8919   //   v4i32 -> v4i64
8920   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8921   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8922   //   Concat upper and lower parts.
8923   //
8924
8925   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
8926       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8927       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8928     return SDValue();
8929
8930   if (Subtarget->hasInt256())
8931     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8932
8933   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8934   SDValue Undef = DAG.getUNDEF(InVT);
8935   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8936   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8937   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8938
8939   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8940                              VT.getVectorNumElements()/2);
8941
8942   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8943   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8944
8945   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8946 }
8947
8948 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
8949                                         SelectionDAG &DAG) {
8950   MVT VT = Op->getValueType(0).getSimpleVT();
8951   SDValue In = Op->getOperand(0);
8952   MVT InVT = In.getValueType().getSimpleVT();
8953   SDLoc DL(Op);
8954   unsigned int NumElts = VT.getVectorNumElements();
8955   if (NumElts != 8 && NumElts != 16)
8956     return SDValue();
8957
8958   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
8959     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8960
8961   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
8962   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8963   // Now we have only mask extension
8964   assert(InVT.getVectorElementType() == MVT::i1);
8965   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
8966   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
8967   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
8968   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
8969   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
8970                            MachinePointerInfo::getConstantPool(),
8971                            false, false, false, Alignment);
8972
8973   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
8974   if (VT.is512BitVector())
8975     return Brcst;
8976   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
8977 }
8978
8979 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
8980                                SelectionDAG &DAG) {
8981   if (Subtarget->hasFp256()) {
8982     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8983     if (Res.getNode())
8984       return Res;
8985   }
8986
8987   return SDValue();
8988 }
8989
8990 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
8991                                 SelectionDAG &DAG) {
8992   SDLoc DL(Op);
8993   MVT VT = Op.getSimpleValueType();
8994   SDValue In = Op.getOperand(0);
8995   MVT SVT = In.getSimpleValueType();
8996
8997   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
8998     return LowerZERO_EXTEND_AVX512(Op, DAG);
8999
9000   if (Subtarget->hasFp256()) {
9001     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9002     if (Res.getNode())
9003       return Res;
9004   }
9005
9006   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9007          VT.getVectorNumElements() != SVT.getVectorNumElements());
9008   return SDValue();
9009 }
9010
9011 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9012   SDLoc DL(Op);
9013   MVT VT = Op.getSimpleValueType();
9014   SDValue In = Op.getOperand(0);
9015   MVT InVT = In.getSimpleValueType();
9016   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9017          "Invalid TRUNCATE operation");
9018
9019   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9020     if (VT.getVectorElementType().getSizeInBits() >=8)
9021       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9022
9023     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9024     unsigned NumElts = InVT.getVectorNumElements();
9025     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9026     if (InVT.getSizeInBits() < 512) {
9027       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9028       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9029       InVT = ExtVT;
9030     }
9031     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9032     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9033     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9034     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9035     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9036                            MachinePointerInfo::getConstantPool(),
9037                            false, false, false, Alignment);
9038     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9039     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9040     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9041   }
9042
9043   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9044     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9045     if (Subtarget->hasInt256()) {
9046       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9047       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9048       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9049                                 ShufMask);
9050       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9051                          DAG.getIntPtrConstant(0));
9052     }
9053
9054     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9055     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9056                                DAG.getIntPtrConstant(0));
9057     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9058                                DAG.getIntPtrConstant(2));
9059
9060     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9061     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9062
9063     // The PSHUFD mask:
9064     static const int ShufMask1[] = {0, 2, 0, 0};
9065     SDValue Undef = DAG.getUNDEF(VT);
9066     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9067     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9068
9069     // The MOVLHPS mask:
9070     static const int ShufMask2[] = {0, 1, 4, 5};
9071     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9072   }
9073
9074   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9075     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9076     if (Subtarget->hasInt256()) {
9077       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9078
9079       SmallVector<SDValue,32> pshufbMask;
9080       for (unsigned i = 0; i < 2; ++i) {
9081         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9082         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9083         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9084         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9085         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9086         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9087         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9088         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9089         for (unsigned j = 0; j < 8; ++j)
9090           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9091       }
9092       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9093                                &pshufbMask[0], 32);
9094       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9095       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9096
9097       static const int ShufMask[] = {0,  2,  -1,  -1};
9098       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9099                                 &ShufMask[0]);
9100       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9101                        DAG.getIntPtrConstant(0));
9102       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9103     }
9104
9105     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9106                                DAG.getIntPtrConstant(0));
9107
9108     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9109                                DAG.getIntPtrConstant(4));
9110
9111     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9112     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9113
9114     // The PSHUFB mask:
9115     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9116                                    -1, -1, -1, -1, -1, -1, -1, -1};
9117
9118     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9119     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9120     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9121
9122     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9123     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9124
9125     // The MOVLHPS Mask:
9126     static const int ShufMask2[] = {0, 1, 4, 5};
9127     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9128     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9129   }
9130
9131   // Handle truncation of V256 to V128 using shuffles.
9132   if (!VT.is128BitVector() || !InVT.is256BitVector())
9133     return SDValue();
9134
9135   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9136
9137   unsigned NumElems = VT.getVectorNumElements();
9138   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9139                              NumElems * 2);
9140
9141   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9142   // Prepare truncation shuffle mask
9143   for (unsigned i = 0; i != NumElems; ++i)
9144     MaskVec[i] = i * 2;
9145   SDValue V = DAG.getVectorShuffle(NVT, DL,
9146                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9147                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9148   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9149                      DAG.getIntPtrConstant(0));
9150 }
9151
9152 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9153                                            SelectionDAG &DAG) const {
9154   MVT VT = Op.getSimpleValueType();
9155   if (VT.isVector()) {
9156     if (VT == MVT::v8i16)
9157       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9158                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9159                                      MVT::v8i32, Op.getOperand(0)));
9160     return SDValue();
9161   }
9162
9163   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9164     /*IsSigned=*/ true, /*IsReplace=*/ false);
9165   SDValue FIST = Vals.first, StackSlot = Vals.second;
9166   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9167   if (FIST.getNode() == 0) return Op;
9168
9169   if (StackSlot.getNode())
9170     // Load the result.
9171     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9172                        FIST, StackSlot, MachinePointerInfo(),
9173                        false, false, false, 0);
9174
9175   // The node is the result.
9176   return FIST;
9177 }
9178
9179 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9180                                            SelectionDAG &DAG) const {
9181   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9182     /*IsSigned=*/ false, /*IsReplace=*/ false);
9183   SDValue FIST = Vals.first, StackSlot = Vals.second;
9184   assert(FIST.getNode() && "Unexpected failure");
9185
9186   if (StackSlot.getNode())
9187     // Load the result.
9188     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9189                        FIST, StackSlot, MachinePointerInfo(),
9190                        false, false, false, 0);
9191
9192   // The node is the result.
9193   return FIST;
9194 }
9195
9196 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9197   SDLoc DL(Op);
9198   MVT VT = Op.getSimpleValueType();
9199   SDValue In = Op.getOperand(0);
9200   MVT SVT = In.getSimpleValueType();
9201
9202   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9203
9204   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9205                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9206                                  In, DAG.getUNDEF(SVT)));
9207 }
9208
9209 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9210   LLVMContext *Context = DAG.getContext();
9211   SDLoc dl(Op);
9212   MVT VT = Op.getSimpleValueType();
9213   MVT EltVT = VT;
9214   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9215   if (VT.isVector()) {
9216     EltVT = VT.getVectorElementType();
9217     NumElts = VT.getVectorNumElements();
9218   }
9219   Constant *C;
9220   if (EltVT == MVT::f64)
9221     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9222                                           APInt(64, ~(1ULL << 63))));
9223   else
9224     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9225                                           APInt(32, ~(1U << 31))));
9226   C = ConstantVector::getSplat(NumElts, C);
9227   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9228   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9229   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9230                              MachinePointerInfo::getConstantPool(),
9231                              false, false, false, Alignment);
9232   if (VT.isVector()) {
9233     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9234     return DAG.getNode(ISD::BITCAST, dl, VT,
9235                        DAG.getNode(ISD::AND, dl, ANDVT,
9236                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9237                                                Op.getOperand(0)),
9238                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9239   }
9240   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9241 }
9242
9243 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9244   LLVMContext *Context = DAG.getContext();
9245   SDLoc dl(Op);
9246   MVT VT = Op.getSimpleValueType();
9247   MVT EltVT = VT;
9248   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9249   if (VT.isVector()) {
9250     EltVT = VT.getVectorElementType();
9251     NumElts = VT.getVectorNumElements();
9252   }
9253   Constant *C;
9254   if (EltVT == MVT::f64)
9255     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9256                                           APInt(64, 1ULL << 63)));
9257   else
9258     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9259                                           APInt(32, 1U << 31)));
9260   C = ConstantVector::getSplat(NumElts, C);
9261   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9262   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9263   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9264                              MachinePointerInfo::getConstantPool(),
9265                              false, false, false, Alignment);
9266   if (VT.isVector()) {
9267     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9268     return DAG.getNode(ISD::BITCAST, dl, VT,
9269                        DAG.getNode(ISD::XOR, dl, XORVT,
9270                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9271                                                Op.getOperand(0)),
9272                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9273   }
9274
9275   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9276 }
9277
9278 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9279   LLVMContext *Context = DAG.getContext();
9280   SDValue Op0 = Op.getOperand(0);
9281   SDValue Op1 = Op.getOperand(1);
9282   SDLoc dl(Op);
9283   MVT VT = Op.getSimpleValueType();
9284   MVT SrcVT = Op1.getSimpleValueType();
9285
9286   // If second operand is smaller, extend it first.
9287   if (SrcVT.bitsLT(VT)) {
9288     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9289     SrcVT = VT;
9290   }
9291   // And if it is bigger, shrink it first.
9292   if (SrcVT.bitsGT(VT)) {
9293     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9294     SrcVT = VT;
9295   }
9296
9297   // At this point the operands and the result should have the same
9298   // type, and that won't be f80 since that is not custom lowered.
9299
9300   // First get the sign bit of second operand.
9301   SmallVector<Constant*,4> CV;
9302   if (SrcVT == MVT::f64) {
9303     const fltSemantics &Sem = APFloat::IEEEdouble;
9304     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9305     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9306   } else {
9307     const fltSemantics &Sem = APFloat::IEEEsingle;
9308     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9309     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9310     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9311     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9312   }
9313   Constant *C = ConstantVector::get(CV);
9314   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9315   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9316                               MachinePointerInfo::getConstantPool(),
9317                               false, false, false, 16);
9318   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9319
9320   // Shift sign bit right or left if the two operands have different types.
9321   if (SrcVT.bitsGT(VT)) {
9322     // Op0 is MVT::f32, Op1 is MVT::f64.
9323     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9324     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9325                           DAG.getConstant(32, MVT::i32));
9326     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9327     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9328                           DAG.getIntPtrConstant(0));
9329   }
9330
9331   // Clear first operand sign bit.
9332   CV.clear();
9333   if (VT == MVT::f64) {
9334     const fltSemantics &Sem = APFloat::IEEEdouble;
9335     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9336                                                    APInt(64, ~(1ULL << 63)))));
9337     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9338   } else {
9339     const fltSemantics &Sem = APFloat::IEEEsingle;
9340     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9341                                                    APInt(32, ~(1U << 31)))));
9342     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9343     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9344     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9345   }
9346   C = ConstantVector::get(CV);
9347   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9348   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9349                               MachinePointerInfo::getConstantPool(),
9350                               false, false, false, 16);
9351   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9352
9353   // Or the value with the sign bit.
9354   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9355 }
9356
9357 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9358   SDValue N0 = Op.getOperand(0);
9359   SDLoc dl(Op);
9360   MVT VT = Op.getSimpleValueType();
9361
9362   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9363   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9364                                   DAG.getConstant(1, VT));
9365   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9366 }
9367
9368 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9369 //
9370 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9371                                       SelectionDAG &DAG) {
9372   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9373
9374   if (!Subtarget->hasSSE41())
9375     return SDValue();
9376
9377   if (!Op->hasOneUse())
9378     return SDValue();
9379
9380   SDNode *N = Op.getNode();
9381   SDLoc DL(N);
9382
9383   SmallVector<SDValue, 8> Opnds;
9384   DenseMap<SDValue, unsigned> VecInMap;
9385   EVT VT = MVT::Other;
9386
9387   // Recognize a special case where a vector is casted into wide integer to
9388   // test all 0s.
9389   Opnds.push_back(N->getOperand(0));
9390   Opnds.push_back(N->getOperand(1));
9391
9392   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9393     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9394     // BFS traverse all OR'd operands.
9395     if (I->getOpcode() == ISD::OR) {
9396       Opnds.push_back(I->getOperand(0));
9397       Opnds.push_back(I->getOperand(1));
9398       // Re-evaluate the number of nodes to be traversed.
9399       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9400       continue;
9401     }
9402
9403     // Quit if a non-EXTRACT_VECTOR_ELT
9404     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9405       return SDValue();
9406
9407     // Quit if without a constant index.
9408     SDValue Idx = I->getOperand(1);
9409     if (!isa<ConstantSDNode>(Idx))
9410       return SDValue();
9411
9412     SDValue ExtractedFromVec = I->getOperand(0);
9413     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9414     if (M == VecInMap.end()) {
9415       VT = ExtractedFromVec.getValueType();
9416       // Quit if not 128/256-bit vector.
9417       if (!VT.is128BitVector() && !VT.is256BitVector())
9418         return SDValue();
9419       // Quit if not the same type.
9420       if (VecInMap.begin() != VecInMap.end() &&
9421           VT != VecInMap.begin()->first.getValueType())
9422         return SDValue();
9423       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9424     }
9425     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9426   }
9427
9428   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9429          "Not extracted from 128-/256-bit vector.");
9430
9431   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9432   SmallVector<SDValue, 8> VecIns;
9433
9434   for (DenseMap<SDValue, unsigned>::const_iterator
9435         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9436     // Quit if not all elements are used.
9437     if (I->second != FullMask)
9438       return SDValue();
9439     VecIns.push_back(I->first);
9440   }
9441
9442   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9443
9444   // Cast all vectors into TestVT for PTEST.
9445   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9446     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9447
9448   // If more than one full vectors are evaluated, OR them first before PTEST.
9449   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9450     // Each iteration will OR 2 nodes and append the result until there is only
9451     // 1 node left, i.e. the final OR'd value of all vectors.
9452     SDValue LHS = VecIns[Slot];
9453     SDValue RHS = VecIns[Slot + 1];
9454     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9455   }
9456
9457   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9458                      VecIns.back(), VecIns.back());
9459 }
9460
9461 /// Emit nodes that will be selected as "test Op0,Op0", or something
9462 /// equivalent.
9463 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9464                                     SelectionDAG &DAG) const {
9465   SDLoc dl(Op);
9466
9467   // CF and OF aren't always set the way we want. Determine which
9468   // of these we need.
9469   bool NeedCF = false;
9470   bool NeedOF = false;
9471   switch (X86CC) {
9472   default: break;
9473   case X86::COND_A: case X86::COND_AE:
9474   case X86::COND_B: case X86::COND_BE:
9475     NeedCF = true;
9476     break;
9477   case X86::COND_G: case X86::COND_GE:
9478   case X86::COND_L: case X86::COND_LE:
9479   case X86::COND_O: case X86::COND_NO:
9480     NeedOF = true;
9481     break;
9482   }
9483
9484   // See if we can use the EFLAGS value from the operand instead of
9485   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9486   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9487   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9488     // Emit a CMP with 0, which is the TEST pattern.
9489     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9490                        DAG.getConstant(0, Op.getValueType()));
9491
9492   unsigned Opcode = 0;
9493   unsigned NumOperands = 0;
9494
9495   // Truncate operations may prevent the merge of the SETCC instruction
9496   // and the arithmetic instruction before it. Attempt to truncate the operands
9497   // of the arithmetic instruction and use a reduced bit-width instruction.
9498   bool NeedTruncation = false;
9499   SDValue ArithOp = Op;
9500   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9501     SDValue Arith = Op->getOperand(0);
9502     // Both the trunc and the arithmetic op need to have one user each.
9503     if (Arith->hasOneUse())
9504       switch (Arith.getOpcode()) {
9505         default: break;
9506         case ISD::ADD:
9507         case ISD::SUB:
9508         case ISD::AND:
9509         case ISD::OR:
9510         case ISD::XOR: {
9511           NeedTruncation = true;
9512           ArithOp = Arith;
9513         }
9514       }
9515   }
9516
9517   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9518   // which may be the result of a CAST.  We use the variable 'Op', which is the
9519   // non-casted variable when we check for possible users.
9520   switch (ArithOp.getOpcode()) {
9521   case ISD::ADD:
9522     // Due to an isel shortcoming, be conservative if this add is likely to be
9523     // selected as part of a load-modify-store instruction. When the root node
9524     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9525     // uses of other nodes in the match, such as the ADD in this case. This
9526     // leads to the ADD being left around and reselected, with the result being
9527     // two adds in the output.  Alas, even if none our users are stores, that
9528     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9529     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9530     // climbing the DAG back to the root, and it doesn't seem to be worth the
9531     // effort.
9532     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9533          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9534       if (UI->getOpcode() != ISD::CopyToReg &&
9535           UI->getOpcode() != ISD::SETCC &&
9536           UI->getOpcode() != ISD::STORE)
9537         goto default_case;
9538
9539     if (ConstantSDNode *C =
9540         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9541       // An add of one will be selected as an INC.
9542       if (C->getAPIntValue() == 1) {
9543         Opcode = X86ISD::INC;
9544         NumOperands = 1;
9545         break;
9546       }
9547
9548       // An add of negative one (subtract of one) will be selected as a DEC.
9549       if (C->getAPIntValue().isAllOnesValue()) {
9550         Opcode = X86ISD::DEC;
9551         NumOperands = 1;
9552         break;
9553       }
9554     }
9555
9556     // Otherwise use a regular EFLAGS-setting add.
9557     Opcode = X86ISD::ADD;
9558     NumOperands = 2;
9559     break;
9560   case ISD::AND: {
9561     // If the primary and result isn't used, don't bother using X86ISD::AND,
9562     // because a TEST instruction will be better.
9563     bool NonFlagUse = false;
9564     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9565            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9566       SDNode *User = *UI;
9567       unsigned UOpNo = UI.getOperandNo();
9568       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9569         // Look pass truncate.
9570         UOpNo = User->use_begin().getOperandNo();
9571         User = *User->use_begin();
9572       }
9573
9574       if (User->getOpcode() != ISD::BRCOND &&
9575           User->getOpcode() != ISD::SETCC &&
9576           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9577         NonFlagUse = true;
9578         break;
9579       }
9580     }
9581
9582     if (!NonFlagUse)
9583       break;
9584   }
9585     // FALL THROUGH
9586   case ISD::SUB:
9587   case ISD::OR:
9588   case ISD::XOR:
9589     // Due to the ISEL shortcoming noted above, be conservative if this op is
9590     // likely to be selected as part of a load-modify-store instruction.
9591     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9592            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9593       if (UI->getOpcode() == ISD::STORE)
9594         goto default_case;
9595
9596     // Otherwise use a regular EFLAGS-setting instruction.
9597     switch (ArithOp.getOpcode()) {
9598     default: llvm_unreachable("unexpected operator!");
9599     case ISD::SUB: Opcode = X86ISD::SUB; break;
9600     case ISD::XOR: Opcode = X86ISD::XOR; break;
9601     case ISD::AND: Opcode = X86ISD::AND; break;
9602     case ISD::OR: {
9603       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9604         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9605         if (EFLAGS.getNode())
9606           return EFLAGS;
9607       }
9608       Opcode = X86ISD::OR;
9609       break;
9610     }
9611     }
9612
9613     NumOperands = 2;
9614     break;
9615   case X86ISD::ADD:
9616   case X86ISD::SUB:
9617   case X86ISD::INC:
9618   case X86ISD::DEC:
9619   case X86ISD::OR:
9620   case X86ISD::XOR:
9621   case X86ISD::AND:
9622     return SDValue(Op.getNode(), 1);
9623   default:
9624   default_case:
9625     break;
9626   }
9627
9628   // If we found that truncation is beneficial, perform the truncation and
9629   // update 'Op'.
9630   if (NeedTruncation) {
9631     EVT VT = Op.getValueType();
9632     SDValue WideVal = Op->getOperand(0);
9633     EVT WideVT = WideVal.getValueType();
9634     unsigned ConvertedOp = 0;
9635     // Use a target machine opcode to prevent further DAGCombine
9636     // optimizations that may separate the arithmetic operations
9637     // from the setcc node.
9638     switch (WideVal.getOpcode()) {
9639       default: break;
9640       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9641       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9642       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9643       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9644       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9645     }
9646
9647     if (ConvertedOp) {
9648       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9649       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9650         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9651         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9652         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9653       }
9654     }
9655   }
9656
9657   if (Opcode == 0)
9658     // Emit a CMP with 0, which is the TEST pattern.
9659     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9660                        DAG.getConstant(0, Op.getValueType()));
9661
9662   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9663   SmallVector<SDValue, 4> Ops;
9664   for (unsigned i = 0; i != NumOperands; ++i)
9665     Ops.push_back(Op.getOperand(i));
9666
9667   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9668   DAG.ReplaceAllUsesWith(Op, New);
9669   return SDValue(New.getNode(), 1);
9670 }
9671
9672 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9673 /// equivalent.
9674 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9675                                    SelectionDAG &DAG) const {
9676   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9677     if (C->getAPIntValue() == 0)
9678       return EmitTest(Op0, X86CC, DAG);
9679
9680   SDLoc dl(Op0);
9681   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9682        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9683     // Do the comparison at i32 if it's smaller. This avoids subregister
9684     // aliasing issues. Keep the smaller reference if we're optimizing for
9685     // size, however, as that'll allow better folding of memory operations.
9686     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9687         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9688              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9689       unsigned ExtendOp =
9690           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9691       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9692       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9693     }
9694     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9695     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9696     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9697                               Op0, Op1);
9698     return SDValue(Sub.getNode(), 1);
9699   }
9700   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9701 }
9702
9703 /// Convert a comparison if required by the subtarget.
9704 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9705                                                  SelectionDAG &DAG) const {
9706   // If the subtarget does not support the FUCOMI instruction, floating-point
9707   // comparisons have to be converted.
9708   if (Subtarget->hasCMov() ||
9709       Cmp.getOpcode() != X86ISD::CMP ||
9710       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9711       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9712     return Cmp;
9713
9714   // The instruction selector will select an FUCOM instruction instead of
9715   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9716   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9717   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9718   SDLoc dl(Cmp);
9719   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9720   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9721   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9722                             DAG.getConstant(8, MVT::i8));
9723   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9724   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9725 }
9726
9727 static bool isAllOnes(SDValue V) {
9728   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9729   return C && C->isAllOnesValue();
9730 }
9731
9732 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9733 /// if it's possible.
9734 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9735                                      SDLoc dl, SelectionDAG &DAG) const {
9736   SDValue Op0 = And.getOperand(0);
9737   SDValue Op1 = And.getOperand(1);
9738   if (Op0.getOpcode() == ISD::TRUNCATE)
9739     Op0 = Op0.getOperand(0);
9740   if (Op1.getOpcode() == ISD::TRUNCATE)
9741     Op1 = Op1.getOperand(0);
9742
9743   SDValue LHS, RHS;
9744   if (Op1.getOpcode() == ISD::SHL)
9745     std::swap(Op0, Op1);
9746   if (Op0.getOpcode() == ISD::SHL) {
9747     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9748       if (And00C->getZExtValue() == 1) {
9749         // If we looked past a truncate, check that it's only truncating away
9750         // known zeros.
9751         unsigned BitWidth = Op0.getValueSizeInBits();
9752         unsigned AndBitWidth = And.getValueSizeInBits();
9753         if (BitWidth > AndBitWidth) {
9754           APInt Zeros, Ones;
9755           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9756           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9757             return SDValue();
9758         }
9759         LHS = Op1;
9760         RHS = Op0.getOperand(1);
9761       }
9762   } else if (Op1.getOpcode() == ISD::Constant) {
9763     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9764     uint64_t AndRHSVal = AndRHS->getZExtValue();
9765     SDValue AndLHS = Op0;
9766
9767     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9768       LHS = AndLHS.getOperand(0);
9769       RHS = AndLHS.getOperand(1);
9770     }
9771
9772     // Use BT if the immediate can't be encoded in a TEST instruction.
9773     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9774       LHS = AndLHS;
9775       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9776     }
9777   }
9778
9779   if (LHS.getNode()) {
9780     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9781     // instruction.  Since the shift amount is in-range-or-undefined, we know
9782     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9783     // the encoding for the i16 version is larger than the i32 version.
9784     // Also promote i16 to i32 for performance / code size reason.
9785     if (LHS.getValueType() == MVT::i8 ||
9786         LHS.getValueType() == MVT::i16)
9787       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9788
9789     // If the operand types disagree, extend the shift amount to match.  Since
9790     // BT ignores high bits (like shifts) we can use anyextend.
9791     if (LHS.getValueType() != RHS.getValueType())
9792       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9793
9794     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9795     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9796     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9797                        DAG.getConstant(Cond, MVT::i8), BT);
9798   }
9799
9800   return SDValue();
9801 }
9802
9803 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9804 /// mask CMPs.
9805 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9806                               SDValue &Op1) {
9807   unsigned SSECC;
9808   bool Swap = false;
9809
9810   // SSE Condition code mapping:
9811   //  0 - EQ
9812   //  1 - LT
9813   //  2 - LE
9814   //  3 - UNORD
9815   //  4 - NEQ
9816   //  5 - NLT
9817   //  6 - NLE
9818   //  7 - ORD
9819   switch (SetCCOpcode) {
9820   default: llvm_unreachable("Unexpected SETCC condition");
9821   case ISD::SETOEQ:
9822   case ISD::SETEQ:  SSECC = 0; break;
9823   case ISD::SETOGT:
9824   case ISD::SETGT:  Swap = true; // Fallthrough
9825   case ISD::SETLT:
9826   case ISD::SETOLT: SSECC = 1; break;
9827   case ISD::SETOGE:
9828   case ISD::SETGE:  Swap = true; // Fallthrough
9829   case ISD::SETLE:
9830   case ISD::SETOLE: SSECC = 2; break;
9831   case ISD::SETUO:  SSECC = 3; break;
9832   case ISD::SETUNE:
9833   case ISD::SETNE:  SSECC = 4; break;
9834   case ISD::SETULE: Swap = true; // Fallthrough
9835   case ISD::SETUGE: SSECC = 5; break;
9836   case ISD::SETULT: Swap = true; // Fallthrough
9837   case ISD::SETUGT: SSECC = 6; break;
9838   case ISD::SETO:   SSECC = 7; break;
9839   case ISD::SETUEQ:
9840   case ISD::SETONE: SSECC = 8; break;
9841   }
9842   if (Swap)
9843     std::swap(Op0, Op1);
9844
9845   return SSECC;
9846 }
9847
9848 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9849 // ones, and then concatenate the result back.
9850 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9851   MVT VT = Op.getSimpleValueType();
9852
9853   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9854          "Unsupported value type for operation");
9855
9856   unsigned NumElems = VT.getVectorNumElements();
9857   SDLoc dl(Op);
9858   SDValue CC = Op.getOperand(2);
9859
9860   // Extract the LHS vectors
9861   SDValue LHS = Op.getOperand(0);
9862   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9863   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9864
9865   // Extract the RHS vectors
9866   SDValue RHS = Op.getOperand(1);
9867   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9868   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9869
9870   // Issue the operation on the smaller types and concatenate the result back
9871   MVT EltVT = VT.getVectorElementType();
9872   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9873   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9874                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9875                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9876 }
9877
9878 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9879   SDValue Op0 = Op.getOperand(0);
9880   SDValue Op1 = Op.getOperand(1);
9881   SDValue CC = Op.getOperand(2);
9882   MVT VT = Op.getSimpleValueType();
9883
9884   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9885          Op.getValueType().getScalarType() == MVT::i1 &&
9886          "Cannot set masked compare for this operation");
9887
9888   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9889   SDLoc dl(Op);
9890
9891   bool Unsigned = false;
9892   unsigned SSECC;
9893   switch (SetCCOpcode) {
9894   default: llvm_unreachable("Unexpected SETCC condition");
9895   case ISD::SETNE:  SSECC = 4; break;
9896   case ISD::SETEQ:  SSECC = 0; break;
9897   case ISD::SETUGT: Unsigned = true;
9898   case ISD::SETGT:  SSECC = 6; break; // NLE
9899   case ISD::SETULT: Unsigned = true;
9900   case ISD::SETLT:  SSECC = 1; break;
9901   case ISD::SETUGE: Unsigned = true;
9902   case ISD::SETGE:  SSECC = 5; break; // NLT
9903   case ISD::SETULE: Unsigned = true;
9904   case ISD::SETLE:  SSECC = 2; break;
9905   }
9906   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9907   return DAG.getNode(Opc, dl, VT, Op0, Op1,
9908                      DAG.getConstant(SSECC, MVT::i8));
9909
9910 }
9911
9912 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9913                            SelectionDAG &DAG) {
9914   SDValue Op0 = Op.getOperand(0);
9915   SDValue Op1 = Op.getOperand(1);
9916   SDValue CC = Op.getOperand(2);
9917   MVT VT = Op.getSimpleValueType();
9918   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9919   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
9920   SDLoc dl(Op);
9921
9922   if (isFP) {
9923 #ifndef NDEBUG
9924     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
9925     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9926 #endif
9927
9928     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9929     unsigned Opc = X86ISD::CMPP;
9930     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
9931       assert(VT.getVectorNumElements() <= 16);
9932       Opc = X86ISD::CMPM;
9933     }
9934     // In the two special cases we can't handle, emit two comparisons.
9935     if (SSECC == 8) {
9936       unsigned CC0, CC1;
9937       unsigned CombineOpc;
9938       if (SetCCOpcode == ISD::SETUEQ) {
9939         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9940       } else {
9941         assert(SetCCOpcode == ISD::SETONE);
9942         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9943       }
9944
9945       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9946                                  DAG.getConstant(CC0, MVT::i8));
9947       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9948                                  DAG.getConstant(CC1, MVT::i8));
9949       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9950     }
9951     // Handle all other FP comparisons here.
9952     return DAG.getNode(Opc, dl, VT, Op0, Op1,
9953                        DAG.getConstant(SSECC, MVT::i8));
9954   }
9955
9956   // Break 256-bit integer vector compare into smaller ones.
9957   if (VT.is256BitVector() && !Subtarget->hasInt256())
9958     return Lower256IntVSETCC(Op, DAG);
9959
9960   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
9961   EVT OpVT = Op1.getValueType();
9962   if (Subtarget->hasAVX512()) {
9963     if (Op1.getValueType().is512BitVector() ||
9964         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
9965       return LowerIntVSETCC_AVX512(Op, DAG);
9966
9967     // In AVX-512 architecture setcc returns mask with i1 elements,
9968     // But there is no compare instruction for i8 and i16 elements.
9969     // We are not talking about 512-bit operands in this case, these
9970     // types are illegal.
9971     if (MaskResult &&
9972         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
9973          OpVT.getVectorElementType().getSizeInBits() >= 8))
9974       return DAG.getNode(ISD::TRUNCATE, dl, VT,
9975                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
9976   }
9977
9978   // We are handling one of the integer comparisons here.  Since SSE only has
9979   // GT and EQ comparisons for integer, swapping operands and multiple
9980   // operations may be required for some comparisons.
9981   unsigned Opc;
9982   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9983
9984   switch (SetCCOpcode) {
9985   default: llvm_unreachable("Unexpected SETCC condition");
9986   case ISD::SETNE:  Invert = true;
9987   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
9988   case ISD::SETLT:  Swap = true;
9989   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
9990   case ISD::SETGE:  Swap = true;
9991   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9992                     Invert = true; break;
9993   case ISD::SETULT: Swap = true;
9994   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9995                     FlipSigns = true; break;
9996   case ISD::SETUGE: Swap = true;
9997   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9998                     FlipSigns = true; Invert = true; break;
9999   }
10000
10001   // Special case: Use min/max operations for SETULE/SETUGE
10002   MVT VET = VT.getVectorElementType();
10003   bool hasMinMax =
10004        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10005     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10006
10007   if (hasMinMax) {
10008     switch (SetCCOpcode) {
10009     default: break;
10010     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10011     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10012     }
10013
10014     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10015   }
10016
10017   if (Swap)
10018     std::swap(Op0, Op1);
10019
10020   // Check that the operation in question is available (most are plain SSE2,
10021   // but PCMPGTQ and PCMPEQQ have different requirements).
10022   if (VT == MVT::v2i64) {
10023     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10024       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10025
10026       // First cast everything to the right type.
10027       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10028       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10029
10030       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10031       // bits of the inputs before performing those operations. The lower
10032       // compare is always unsigned.
10033       SDValue SB;
10034       if (FlipSigns) {
10035         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10036       } else {
10037         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10038         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10039         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10040                          Sign, Zero, Sign, Zero);
10041       }
10042       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10043       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10044
10045       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10046       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10047       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10048
10049       // Create masks for only the low parts/high parts of the 64 bit integers.
10050       static const int MaskHi[] = { 1, 1, 3, 3 };
10051       static const int MaskLo[] = { 0, 0, 2, 2 };
10052       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10053       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10054       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10055
10056       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10057       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10058
10059       if (Invert)
10060         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10061
10062       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10063     }
10064
10065     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10066       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10067       // pcmpeqd + pshufd + pand.
10068       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10069
10070       // First cast everything to the right type.
10071       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10072       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10073
10074       // Do the compare.
10075       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10076
10077       // Make sure the lower and upper halves are both all-ones.
10078       static const int Mask[] = { 1, 0, 3, 2 };
10079       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10080       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10081
10082       if (Invert)
10083         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10084
10085       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10086     }
10087   }
10088
10089   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10090   // bits of the inputs before performing those operations.
10091   if (FlipSigns) {
10092     EVT EltVT = VT.getVectorElementType();
10093     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10094     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10095     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10096   }
10097
10098   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10099
10100   // If the logical-not of the result is required, perform that now.
10101   if (Invert)
10102     Result = DAG.getNOT(dl, Result, VT);
10103
10104   if (MinMax)
10105     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10106
10107   return Result;
10108 }
10109
10110 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10111
10112   MVT VT = Op.getSimpleValueType();
10113
10114   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10115
10116   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
10117   SDValue Op0 = Op.getOperand(0);
10118   SDValue Op1 = Op.getOperand(1);
10119   SDLoc dl(Op);
10120   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10121
10122   // Optimize to BT if possible.
10123   // Lower (X & (1 << N)) == 0 to BT(X, N).
10124   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10125   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10126   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10127       Op1.getOpcode() == ISD::Constant &&
10128       cast<ConstantSDNode>(Op1)->isNullValue() &&
10129       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10130     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10131     if (NewSetCC.getNode())
10132       return NewSetCC;
10133   }
10134
10135   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10136   // these.
10137   if (Op1.getOpcode() == ISD::Constant &&
10138       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10139        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10140       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10141
10142     // If the input is a setcc, then reuse the input setcc or use a new one with
10143     // the inverted condition.
10144     if (Op0.getOpcode() == X86ISD::SETCC) {
10145       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10146       bool Invert = (CC == ISD::SETNE) ^
10147         cast<ConstantSDNode>(Op1)->isNullValue();
10148       if (!Invert) return Op0;
10149
10150       CCode = X86::GetOppositeBranchCondition(CCode);
10151       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10152                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
10153     }
10154   }
10155
10156   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10157   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10158   if (X86CC == X86::COND_INVALID)
10159     return SDValue();
10160
10161   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10162   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10163   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10164                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10165 }
10166
10167 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10168 static bool isX86LogicalCmp(SDValue Op) {
10169   unsigned Opc = Op.getNode()->getOpcode();
10170   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10171       Opc == X86ISD::SAHF)
10172     return true;
10173   if (Op.getResNo() == 1 &&
10174       (Opc == X86ISD::ADD ||
10175        Opc == X86ISD::SUB ||
10176        Opc == X86ISD::ADC ||
10177        Opc == X86ISD::SBB ||
10178        Opc == X86ISD::SMUL ||
10179        Opc == X86ISD::UMUL ||
10180        Opc == X86ISD::INC ||
10181        Opc == X86ISD::DEC ||
10182        Opc == X86ISD::OR ||
10183        Opc == X86ISD::XOR ||
10184        Opc == X86ISD::AND))
10185     return true;
10186
10187   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10188     return true;
10189
10190   return false;
10191 }
10192
10193 static bool isZero(SDValue V) {
10194   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10195   return C && C->isNullValue();
10196 }
10197
10198 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10199   if (V.getOpcode() != ISD::TRUNCATE)
10200     return false;
10201
10202   SDValue VOp0 = V.getOperand(0);
10203   unsigned InBits = VOp0.getValueSizeInBits();
10204   unsigned Bits = V.getValueSizeInBits();
10205   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10206 }
10207
10208 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10209   bool addTest = true;
10210   SDValue Cond  = Op.getOperand(0);
10211   SDValue Op1 = Op.getOperand(1);
10212   SDValue Op2 = Op.getOperand(2);
10213   SDLoc DL(Op);
10214   EVT VT = Op1.getValueType();
10215   SDValue CC;
10216
10217   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10218   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10219   // sequence later on.
10220   if (Cond.getOpcode() == ISD::SETCC &&
10221       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10222        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10223       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10224     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10225     int SSECC = translateX86FSETCC(
10226         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10227
10228     if (SSECC != 8) {
10229       unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
10230       SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
10231                                 DAG.getConstant(SSECC, MVT::i8));
10232       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10233       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10234       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10235     }
10236   }
10237
10238   if (Cond.getOpcode() == ISD::SETCC) {
10239     SDValue NewCond = LowerSETCC(Cond, DAG);
10240     if (NewCond.getNode())
10241       Cond = NewCond;
10242   }
10243
10244   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10245   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10246   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10247   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10248   if (Cond.getOpcode() == X86ISD::SETCC &&
10249       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10250       isZero(Cond.getOperand(1).getOperand(1))) {
10251     SDValue Cmp = Cond.getOperand(1);
10252
10253     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10254
10255     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10256         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10257       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10258
10259       SDValue CmpOp0 = Cmp.getOperand(0);
10260       // Apply further optimizations for special cases
10261       // (select (x != 0), -1, 0) -> neg & sbb
10262       // (select (x == 0), 0, -1) -> neg & sbb
10263       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10264         if (YC->isNullValue() &&
10265             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10266           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10267           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10268                                     DAG.getConstant(0, CmpOp0.getValueType()),
10269                                     CmpOp0);
10270           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10271                                     DAG.getConstant(X86::COND_B, MVT::i8),
10272                                     SDValue(Neg.getNode(), 1));
10273           return Res;
10274         }
10275
10276       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10277                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10278       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10279
10280       SDValue Res =   // Res = 0 or -1.
10281         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10282                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10283
10284       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10285         Res = DAG.getNOT(DL, Res, Res.getValueType());
10286
10287       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10288       if (N2C == 0 || !N2C->isNullValue())
10289         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10290       return Res;
10291     }
10292   }
10293
10294   // Look past (and (setcc_carry (cmp ...)), 1).
10295   if (Cond.getOpcode() == ISD::AND &&
10296       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10297     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10298     if (C && C->getAPIntValue() == 1)
10299       Cond = Cond.getOperand(0);
10300   }
10301
10302   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10303   // setting operand in place of the X86ISD::SETCC.
10304   unsigned CondOpcode = Cond.getOpcode();
10305   if (CondOpcode == X86ISD::SETCC ||
10306       CondOpcode == X86ISD::SETCC_CARRY) {
10307     CC = Cond.getOperand(0);
10308
10309     SDValue Cmp = Cond.getOperand(1);
10310     unsigned Opc = Cmp.getOpcode();
10311     MVT VT = Op.getSimpleValueType();
10312
10313     bool IllegalFPCMov = false;
10314     if (VT.isFloatingPoint() && !VT.isVector() &&
10315         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10316       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10317
10318     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10319         Opc == X86ISD::BT) { // FIXME
10320       Cond = Cmp;
10321       addTest = false;
10322     }
10323   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10324              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10325              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10326               Cond.getOperand(0).getValueType() != MVT::i8)) {
10327     SDValue LHS = Cond.getOperand(0);
10328     SDValue RHS = Cond.getOperand(1);
10329     unsigned X86Opcode;
10330     unsigned X86Cond;
10331     SDVTList VTs;
10332     switch (CondOpcode) {
10333     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10334     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10335     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10336     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10337     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10338     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10339     default: llvm_unreachable("unexpected overflowing operator");
10340     }
10341     if (CondOpcode == ISD::UMULO)
10342       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10343                           MVT::i32);
10344     else
10345       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10346
10347     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10348
10349     if (CondOpcode == ISD::UMULO)
10350       Cond = X86Op.getValue(2);
10351     else
10352       Cond = X86Op.getValue(1);
10353
10354     CC = DAG.getConstant(X86Cond, MVT::i8);
10355     addTest = false;
10356   }
10357
10358   if (addTest) {
10359     // Look pass the truncate if the high bits are known zero.
10360     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10361         Cond = Cond.getOperand(0);
10362
10363     // We know the result of AND is compared against zero. Try to match
10364     // it to BT.
10365     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10366       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10367       if (NewSetCC.getNode()) {
10368         CC = NewSetCC.getOperand(0);
10369         Cond = NewSetCC.getOperand(1);
10370         addTest = false;
10371       }
10372     }
10373   }
10374
10375   if (addTest) {
10376     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10377     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10378   }
10379
10380   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10381   // a <  b ?  0 : -1 -> RES = setcc_carry
10382   // a >= b ? -1 :  0 -> RES = setcc_carry
10383   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10384   if (Cond.getOpcode() == X86ISD::SUB) {
10385     Cond = ConvertCmpIfNecessary(Cond, DAG);
10386     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10387
10388     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10389         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10390       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10391                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10392       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10393         return DAG.getNOT(DL, Res, Res.getValueType());
10394       return Res;
10395     }
10396   }
10397
10398   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10399   // widen the cmov and push the truncate through. This avoids introducing a new
10400   // branch during isel and doesn't add any extensions.
10401   if (Op.getValueType() == MVT::i8 &&
10402       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10403     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10404     if (T1.getValueType() == T2.getValueType() &&
10405         // Blacklist CopyFromReg to avoid partial register stalls.
10406         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10407       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10408       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10409       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10410     }
10411   }
10412
10413   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10414   // condition is true.
10415   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10416   SDValue Ops[] = { Op2, Op1, CC, Cond };
10417   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10418 }
10419
10420 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10421   MVT VT = Op->getSimpleValueType(0);
10422   SDValue In = Op->getOperand(0);
10423   MVT InVT = In.getSimpleValueType();
10424   SDLoc dl(Op);
10425
10426   unsigned int NumElts = VT.getVectorNumElements();
10427   if (NumElts != 8 && NumElts != 16)
10428     return SDValue();
10429
10430   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10431     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10432
10433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10434   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10435
10436   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10437   Constant *C = ConstantInt::get(*DAG.getContext(),
10438     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10439
10440   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10441   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10442   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10443                           MachinePointerInfo::getConstantPool(),
10444                           false, false, false, Alignment);
10445   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10446   if (VT.is512BitVector())
10447     return Brcst;
10448   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10449 }
10450
10451 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10452                                 SelectionDAG &DAG) {
10453   MVT VT = Op->getSimpleValueType(0);
10454   SDValue In = Op->getOperand(0);
10455   MVT InVT = In.getSimpleValueType();
10456   SDLoc dl(Op);
10457
10458   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10459     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10460
10461   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10462       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10463       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10464     return SDValue();
10465
10466   if (Subtarget->hasInt256())
10467     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10468
10469   // Optimize vectors in AVX mode
10470   // Sign extend  v8i16 to v8i32 and
10471   //              v4i32 to v4i64
10472   //
10473   // Divide input vector into two parts
10474   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10475   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10476   // concat the vectors to original VT
10477
10478   unsigned NumElems = InVT.getVectorNumElements();
10479   SDValue Undef = DAG.getUNDEF(InVT);
10480
10481   SmallVector<int,8> ShufMask1(NumElems, -1);
10482   for (unsigned i = 0; i != NumElems/2; ++i)
10483     ShufMask1[i] = i;
10484
10485   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10486
10487   SmallVector<int,8> ShufMask2(NumElems, -1);
10488   for (unsigned i = 0; i != NumElems/2; ++i)
10489     ShufMask2[i] = i + NumElems/2;
10490
10491   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10492
10493   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10494                                 VT.getVectorNumElements()/2);
10495
10496   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10497   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10498
10499   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10500 }
10501
10502 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10503 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10504 // from the AND / OR.
10505 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10506   Opc = Op.getOpcode();
10507   if (Opc != ISD::OR && Opc != ISD::AND)
10508     return false;
10509   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10510           Op.getOperand(0).hasOneUse() &&
10511           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10512           Op.getOperand(1).hasOneUse());
10513 }
10514
10515 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10516 // 1 and that the SETCC node has a single use.
10517 static bool isXor1OfSetCC(SDValue Op) {
10518   if (Op.getOpcode() != ISD::XOR)
10519     return false;
10520   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10521   if (N1C && N1C->getAPIntValue() == 1) {
10522     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10523       Op.getOperand(0).hasOneUse();
10524   }
10525   return false;
10526 }
10527
10528 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10529   bool addTest = true;
10530   SDValue Chain = Op.getOperand(0);
10531   SDValue Cond  = Op.getOperand(1);
10532   SDValue Dest  = Op.getOperand(2);
10533   SDLoc dl(Op);
10534   SDValue CC;
10535   bool Inverted = false;
10536
10537   if (Cond.getOpcode() == ISD::SETCC) {
10538     // Check for setcc([su]{add,sub,mul}o == 0).
10539     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10540         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10541         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10542         Cond.getOperand(0).getResNo() == 1 &&
10543         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10544          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10545          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10546          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10547          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10548          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10549       Inverted = true;
10550       Cond = Cond.getOperand(0);
10551     } else {
10552       SDValue NewCond = LowerSETCC(Cond, DAG);
10553       if (NewCond.getNode())
10554         Cond = NewCond;
10555     }
10556   }
10557 #if 0
10558   // FIXME: LowerXALUO doesn't handle these!!
10559   else if (Cond.getOpcode() == X86ISD::ADD  ||
10560            Cond.getOpcode() == X86ISD::SUB  ||
10561            Cond.getOpcode() == X86ISD::SMUL ||
10562            Cond.getOpcode() == X86ISD::UMUL)
10563     Cond = LowerXALUO(Cond, DAG);
10564 #endif
10565
10566   // Look pass (and (setcc_carry (cmp ...)), 1).
10567   if (Cond.getOpcode() == ISD::AND &&
10568       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10569     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10570     if (C && C->getAPIntValue() == 1)
10571       Cond = Cond.getOperand(0);
10572   }
10573
10574   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10575   // setting operand in place of the X86ISD::SETCC.
10576   unsigned CondOpcode = Cond.getOpcode();
10577   if (CondOpcode == X86ISD::SETCC ||
10578       CondOpcode == X86ISD::SETCC_CARRY) {
10579     CC = Cond.getOperand(0);
10580
10581     SDValue Cmp = Cond.getOperand(1);
10582     unsigned Opc = Cmp.getOpcode();
10583     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10584     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10585       Cond = Cmp;
10586       addTest = false;
10587     } else {
10588       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10589       default: break;
10590       case X86::COND_O:
10591       case X86::COND_B:
10592         // These can only come from an arithmetic instruction with overflow,
10593         // e.g. SADDO, UADDO.
10594         Cond = Cond.getNode()->getOperand(1);
10595         addTest = false;
10596         break;
10597       }
10598     }
10599   }
10600   CondOpcode = Cond.getOpcode();
10601   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10602       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10603       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10604        Cond.getOperand(0).getValueType() != MVT::i8)) {
10605     SDValue LHS = Cond.getOperand(0);
10606     SDValue RHS = Cond.getOperand(1);
10607     unsigned X86Opcode;
10608     unsigned X86Cond;
10609     SDVTList VTs;
10610     switch (CondOpcode) {
10611     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10612     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10613     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10614     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10615     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10616     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10617     default: llvm_unreachable("unexpected overflowing operator");
10618     }
10619     if (Inverted)
10620       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10621     if (CondOpcode == ISD::UMULO)
10622       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10623                           MVT::i32);
10624     else
10625       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10626
10627     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10628
10629     if (CondOpcode == ISD::UMULO)
10630       Cond = X86Op.getValue(2);
10631     else
10632       Cond = X86Op.getValue(1);
10633
10634     CC = DAG.getConstant(X86Cond, MVT::i8);
10635     addTest = false;
10636   } else {
10637     unsigned CondOpc;
10638     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10639       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10640       if (CondOpc == ISD::OR) {
10641         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10642         // two branches instead of an explicit OR instruction with a
10643         // separate test.
10644         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10645             isX86LogicalCmp(Cmp)) {
10646           CC = Cond.getOperand(0).getOperand(0);
10647           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10648                               Chain, Dest, CC, Cmp);
10649           CC = Cond.getOperand(1).getOperand(0);
10650           Cond = Cmp;
10651           addTest = false;
10652         }
10653       } else { // ISD::AND
10654         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10655         // two branches instead of an explicit AND instruction with a
10656         // separate test. However, we only do this if this block doesn't
10657         // have a fall-through edge, because this requires an explicit
10658         // jmp when the condition is false.
10659         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10660             isX86LogicalCmp(Cmp) &&
10661             Op.getNode()->hasOneUse()) {
10662           X86::CondCode CCode =
10663             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10664           CCode = X86::GetOppositeBranchCondition(CCode);
10665           CC = DAG.getConstant(CCode, MVT::i8);
10666           SDNode *User = *Op.getNode()->use_begin();
10667           // Look for an unconditional branch following this conditional branch.
10668           // We need this because we need to reverse the successors in order
10669           // to implement FCMP_OEQ.
10670           if (User->getOpcode() == ISD::BR) {
10671             SDValue FalseBB = User->getOperand(1);
10672             SDNode *NewBR =
10673               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10674             assert(NewBR == User);
10675             (void)NewBR;
10676             Dest = FalseBB;
10677
10678             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10679                                 Chain, Dest, CC, Cmp);
10680             X86::CondCode CCode =
10681               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10682             CCode = X86::GetOppositeBranchCondition(CCode);
10683             CC = DAG.getConstant(CCode, MVT::i8);
10684             Cond = Cmp;
10685             addTest = false;
10686           }
10687         }
10688       }
10689     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10690       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10691       // It should be transformed during dag combiner except when the condition
10692       // is set by a arithmetics with overflow node.
10693       X86::CondCode CCode =
10694         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10695       CCode = X86::GetOppositeBranchCondition(CCode);
10696       CC = DAG.getConstant(CCode, MVT::i8);
10697       Cond = Cond.getOperand(0).getOperand(1);
10698       addTest = false;
10699     } else if (Cond.getOpcode() == ISD::SETCC &&
10700                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10701       // For FCMP_OEQ, we can emit
10702       // two branches instead of an explicit AND instruction with a
10703       // separate test. However, we only do this if this block doesn't
10704       // have a fall-through edge, because this requires an explicit
10705       // jmp when the condition is false.
10706       if (Op.getNode()->hasOneUse()) {
10707         SDNode *User = *Op.getNode()->use_begin();
10708         // Look for an unconditional branch following this conditional branch.
10709         // We need this because we need to reverse the successors in order
10710         // to implement FCMP_OEQ.
10711         if (User->getOpcode() == ISD::BR) {
10712           SDValue FalseBB = User->getOperand(1);
10713           SDNode *NewBR =
10714             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10715           assert(NewBR == User);
10716           (void)NewBR;
10717           Dest = FalseBB;
10718
10719           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10720                                     Cond.getOperand(0), Cond.getOperand(1));
10721           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10722           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10723           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10724                               Chain, Dest, CC, Cmp);
10725           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10726           Cond = Cmp;
10727           addTest = false;
10728         }
10729       }
10730     } else if (Cond.getOpcode() == ISD::SETCC &&
10731                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10732       // For FCMP_UNE, we can emit
10733       // two branches instead of an explicit AND instruction with a
10734       // separate test. However, we only do this if this block doesn't
10735       // have a fall-through edge, because this requires an explicit
10736       // jmp when the condition is false.
10737       if (Op.getNode()->hasOneUse()) {
10738         SDNode *User = *Op.getNode()->use_begin();
10739         // Look for an unconditional branch following this conditional branch.
10740         // We need this because we need to reverse the successors in order
10741         // to implement FCMP_UNE.
10742         if (User->getOpcode() == ISD::BR) {
10743           SDValue FalseBB = User->getOperand(1);
10744           SDNode *NewBR =
10745             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10746           assert(NewBR == User);
10747           (void)NewBR;
10748
10749           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10750                                     Cond.getOperand(0), Cond.getOperand(1));
10751           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10752           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10753           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10754                               Chain, Dest, CC, Cmp);
10755           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10756           Cond = Cmp;
10757           addTest = false;
10758           Dest = FalseBB;
10759         }
10760       }
10761     }
10762   }
10763
10764   if (addTest) {
10765     // Look pass the truncate if the high bits are known zero.
10766     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10767         Cond = Cond.getOperand(0);
10768
10769     // We know the result of AND is compared against zero. Try to match
10770     // it to BT.
10771     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10772       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10773       if (NewSetCC.getNode()) {
10774         CC = NewSetCC.getOperand(0);
10775         Cond = NewSetCC.getOperand(1);
10776         addTest = false;
10777       }
10778     }
10779   }
10780
10781   if (addTest) {
10782     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10783     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10784   }
10785   Cond = ConvertCmpIfNecessary(Cond, DAG);
10786   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10787                      Chain, Dest, CC, Cond);
10788 }
10789
10790 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10791 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10792 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10793 // that the guard pages used by the OS virtual memory manager are allocated in
10794 // correct sequence.
10795 SDValue
10796 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10797                                            SelectionDAG &DAG) const {
10798   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10799           getTargetMachine().Options.EnableSegmentedStacks) &&
10800          "This should be used only on Windows targets or when segmented stacks "
10801          "are being used");
10802   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10803   SDLoc dl(Op);
10804
10805   // Get the inputs.
10806   SDValue Chain = Op.getOperand(0);
10807   SDValue Size  = Op.getOperand(1);
10808   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10809   EVT VT = Op.getNode()->getValueType(0);
10810
10811   bool Is64Bit = Subtarget->is64Bit();
10812   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10813
10814   if (getTargetMachine().Options.EnableSegmentedStacks) {
10815     MachineFunction &MF = DAG.getMachineFunction();
10816     MachineRegisterInfo &MRI = MF.getRegInfo();
10817
10818     if (Is64Bit) {
10819       // The 64 bit implementation of segmented stacks needs to clobber both r10
10820       // r11. This makes it impossible to use it along with nested parameters.
10821       const Function *F = MF.getFunction();
10822
10823       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10824            I != E; ++I)
10825         if (I->hasNestAttr())
10826           report_fatal_error("Cannot use segmented stacks with functions that "
10827                              "have nested arguments.");
10828     }
10829
10830     const TargetRegisterClass *AddrRegClass =
10831       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10832     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10833     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10834     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10835                                 DAG.getRegister(Vreg, SPTy));
10836     SDValue Ops1[2] = { Value, Chain };
10837     return DAG.getMergeValues(Ops1, 2, dl);
10838   } else {
10839     SDValue Flag;
10840     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10841
10842     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10843     Flag = Chain.getValue(1);
10844     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10845
10846     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10847
10848     const X86RegisterInfo *RegInfo =
10849       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10850     unsigned SPReg = RegInfo->getStackRegister();
10851     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
10852     Chain = SP.getValue(1);
10853
10854     if (Align) {
10855       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10856                        DAG.getConstant(-(uint64_t)Align, VT));
10857       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
10858     }
10859
10860     SDValue Ops1[2] = { SP, Chain };
10861     return DAG.getMergeValues(Ops1, 2, dl);
10862   }
10863 }
10864
10865 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10866   MachineFunction &MF = DAG.getMachineFunction();
10867   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10868
10869   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10870   SDLoc DL(Op);
10871
10872   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10873     // vastart just stores the address of the VarArgsFrameIndex slot into the
10874     // memory location argument.
10875     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10876                                    getPointerTy());
10877     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10878                         MachinePointerInfo(SV), false, false, 0);
10879   }
10880
10881   // __va_list_tag:
10882   //   gp_offset         (0 - 6 * 8)
10883   //   fp_offset         (48 - 48 + 8 * 16)
10884   //   overflow_arg_area (point to parameters coming in memory).
10885   //   reg_save_area
10886   SmallVector<SDValue, 8> MemOps;
10887   SDValue FIN = Op.getOperand(1);
10888   // Store gp_offset
10889   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10890                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10891                                                MVT::i32),
10892                                FIN, MachinePointerInfo(SV), false, false, 0);
10893   MemOps.push_back(Store);
10894
10895   // Store fp_offset
10896   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10897                     FIN, DAG.getIntPtrConstant(4));
10898   Store = DAG.getStore(Op.getOperand(0), DL,
10899                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10900                                        MVT::i32),
10901                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10902   MemOps.push_back(Store);
10903
10904   // Store ptr to overflow_arg_area
10905   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10906                     FIN, DAG.getIntPtrConstant(4));
10907   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10908                                     getPointerTy());
10909   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10910                        MachinePointerInfo(SV, 8),
10911                        false, false, 0);
10912   MemOps.push_back(Store);
10913
10914   // Store ptr to reg_save_area.
10915   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10916                     FIN, DAG.getIntPtrConstant(8));
10917   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10918                                     getPointerTy());
10919   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10920                        MachinePointerInfo(SV, 16), false, false, 0);
10921   MemOps.push_back(Store);
10922   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10923                      &MemOps[0], MemOps.size());
10924 }
10925
10926 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10927   assert(Subtarget->is64Bit() &&
10928          "LowerVAARG only handles 64-bit va_arg!");
10929   assert((Subtarget->isTargetLinux() ||
10930           Subtarget->isTargetDarwin()) &&
10931           "Unhandled target in LowerVAARG");
10932   assert(Op.getNode()->getNumOperands() == 4);
10933   SDValue Chain = Op.getOperand(0);
10934   SDValue SrcPtr = Op.getOperand(1);
10935   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10936   unsigned Align = Op.getConstantOperandVal(3);
10937   SDLoc dl(Op);
10938
10939   EVT ArgVT = Op.getNode()->getValueType(0);
10940   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10941   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10942   uint8_t ArgMode;
10943
10944   // Decide which area this value should be read from.
10945   // TODO: Implement the AMD64 ABI in its entirety. This simple
10946   // selection mechanism works only for the basic types.
10947   if (ArgVT == MVT::f80) {
10948     llvm_unreachable("va_arg for f80 not yet implemented");
10949   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10950     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10951   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10952     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10953   } else {
10954     llvm_unreachable("Unhandled argument type in LowerVAARG");
10955   }
10956
10957   if (ArgMode == 2) {
10958     // Sanity Check: Make sure using fp_offset makes sense.
10959     assert(!getTargetMachine().Options.UseSoftFloat &&
10960            !(DAG.getMachineFunction()
10961                 .getFunction()->getAttributes()
10962                 .hasAttribute(AttributeSet::FunctionIndex,
10963                               Attribute::NoImplicitFloat)) &&
10964            Subtarget->hasSSE1());
10965   }
10966
10967   // Insert VAARG_64 node into the DAG
10968   // VAARG_64 returns two values: Variable Argument Address, Chain
10969   SmallVector<SDValue, 11> InstOps;
10970   InstOps.push_back(Chain);
10971   InstOps.push_back(SrcPtr);
10972   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10973   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10974   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10975   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10976   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10977                                           VTs, &InstOps[0], InstOps.size(),
10978                                           MVT::i64,
10979                                           MachinePointerInfo(SV),
10980                                           /*Align=*/0,
10981                                           /*Volatile=*/false,
10982                                           /*ReadMem=*/true,
10983                                           /*WriteMem=*/true);
10984   Chain = VAARG.getValue(1);
10985
10986   // Load the next argument and return it
10987   return DAG.getLoad(ArgVT, dl,
10988                      Chain,
10989                      VAARG,
10990                      MachinePointerInfo(),
10991                      false, false, false, 0);
10992 }
10993
10994 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10995                            SelectionDAG &DAG) {
10996   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10997   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10998   SDValue Chain = Op.getOperand(0);
10999   SDValue DstPtr = Op.getOperand(1);
11000   SDValue SrcPtr = Op.getOperand(2);
11001   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11002   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11003   SDLoc DL(Op);
11004
11005   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11006                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11007                        false,
11008                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11009 }
11010
11011 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11012 // amount is a constant. Takes immediate version of shift as input.
11013 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, EVT VT,
11014                                           SDValue SrcOp, uint64_t ShiftAmt,
11015                                           SelectionDAG &DAG) {
11016
11017   // Check for ShiftAmt >= element width
11018   if (ShiftAmt >= VT.getVectorElementType().getSizeInBits()) {
11019     if (Opc == X86ISD::VSRAI)
11020       ShiftAmt = VT.getVectorElementType().getSizeInBits() - 1;
11021     else
11022       return DAG.getConstant(0, VT);
11023   }
11024
11025   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11026          && "Unknown target vector shift-by-constant node");
11027
11028   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11029 }
11030
11031 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11032 // may or may not be a constant. Takes immediate version of shift as input.
11033 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
11034                                    SDValue SrcOp, SDValue ShAmt,
11035                                    SelectionDAG &DAG) {
11036   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11037
11038   // Catch shift-by-constant.
11039   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11040     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11041                                       CShAmt->getZExtValue(), DAG);
11042
11043   // Change opcode to non-immediate version
11044   switch (Opc) {
11045     default: llvm_unreachable("Unknown target vector shift node");
11046     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11047     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11048     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11049   }
11050
11051   // Need to build a vector containing shift amount
11052   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11053   SDValue ShOps[4];
11054   ShOps[0] = ShAmt;
11055   ShOps[1] = DAG.getConstant(0, MVT::i32);
11056   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11057   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11058
11059   // The return type has to be a 128-bit type with the same element
11060   // type as the input type.
11061   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11062   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11063
11064   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11065   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11066 }
11067
11068 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11069   SDLoc dl(Op);
11070   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11071   switch (IntNo) {
11072   default: return SDValue();    // Don't custom lower most intrinsics.
11073   // Comparison intrinsics.
11074   case Intrinsic::x86_sse_comieq_ss:
11075   case Intrinsic::x86_sse_comilt_ss:
11076   case Intrinsic::x86_sse_comile_ss:
11077   case Intrinsic::x86_sse_comigt_ss:
11078   case Intrinsic::x86_sse_comige_ss:
11079   case Intrinsic::x86_sse_comineq_ss:
11080   case Intrinsic::x86_sse_ucomieq_ss:
11081   case Intrinsic::x86_sse_ucomilt_ss:
11082   case Intrinsic::x86_sse_ucomile_ss:
11083   case Intrinsic::x86_sse_ucomigt_ss:
11084   case Intrinsic::x86_sse_ucomige_ss:
11085   case Intrinsic::x86_sse_ucomineq_ss:
11086   case Intrinsic::x86_sse2_comieq_sd:
11087   case Intrinsic::x86_sse2_comilt_sd:
11088   case Intrinsic::x86_sse2_comile_sd:
11089   case Intrinsic::x86_sse2_comigt_sd:
11090   case Intrinsic::x86_sse2_comige_sd:
11091   case Intrinsic::x86_sse2_comineq_sd:
11092   case Intrinsic::x86_sse2_ucomieq_sd:
11093   case Intrinsic::x86_sse2_ucomilt_sd:
11094   case Intrinsic::x86_sse2_ucomile_sd:
11095   case Intrinsic::x86_sse2_ucomigt_sd:
11096   case Intrinsic::x86_sse2_ucomige_sd:
11097   case Intrinsic::x86_sse2_ucomineq_sd: {
11098     unsigned Opc;
11099     ISD::CondCode CC;
11100     switch (IntNo) {
11101     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11102     case Intrinsic::x86_sse_comieq_ss:
11103     case Intrinsic::x86_sse2_comieq_sd:
11104       Opc = X86ISD::COMI;
11105       CC = ISD::SETEQ;
11106       break;
11107     case Intrinsic::x86_sse_comilt_ss:
11108     case Intrinsic::x86_sse2_comilt_sd:
11109       Opc = X86ISD::COMI;
11110       CC = ISD::SETLT;
11111       break;
11112     case Intrinsic::x86_sse_comile_ss:
11113     case Intrinsic::x86_sse2_comile_sd:
11114       Opc = X86ISD::COMI;
11115       CC = ISD::SETLE;
11116       break;
11117     case Intrinsic::x86_sse_comigt_ss:
11118     case Intrinsic::x86_sse2_comigt_sd:
11119       Opc = X86ISD::COMI;
11120       CC = ISD::SETGT;
11121       break;
11122     case Intrinsic::x86_sse_comige_ss:
11123     case Intrinsic::x86_sse2_comige_sd:
11124       Opc = X86ISD::COMI;
11125       CC = ISD::SETGE;
11126       break;
11127     case Intrinsic::x86_sse_comineq_ss:
11128     case Intrinsic::x86_sse2_comineq_sd:
11129       Opc = X86ISD::COMI;
11130       CC = ISD::SETNE;
11131       break;
11132     case Intrinsic::x86_sse_ucomieq_ss:
11133     case Intrinsic::x86_sse2_ucomieq_sd:
11134       Opc = X86ISD::UCOMI;
11135       CC = ISD::SETEQ;
11136       break;
11137     case Intrinsic::x86_sse_ucomilt_ss:
11138     case Intrinsic::x86_sse2_ucomilt_sd:
11139       Opc = X86ISD::UCOMI;
11140       CC = ISD::SETLT;
11141       break;
11142     case Intrinsic::x86_sse_ucomile_ss:
11143     case Intrinsic::x86_sse2_ucomile_sd:
11144       Opc = X86ISD::UCOMI;
11145       CC = ISD::SETLE;
11146       break;
11147     case Intrinsic::x86_sse_ucomigt_ss:
11148     case Intrinsic::x86_sse2_ucomigt_sd:
11149       Opc = X86ISD::UCOMI;
11150       CC = ISD::SETGT;
11151       break;
11152     case Intrinsic::x86_sse_ucomige_ss:
11153     case Intrinsic::x86_sse2_ucomige_sd:
11154       Opc = X86ISD::UCOMI;
11155       CC = ISD::SETGE;
11156       break;
11157     case Intrinsic::x86_sse_ucomineq_ss:
11158     case Intrinsic::x86_sse2_ucomineq_sd:
11159       Opc = X86ISD::UCOMI;
11160       CC = ISD::SETNE;
11161       break;
11162     }
11163
11164     SDValue LHS = Op.getOperand(1);
11165     SDValue RHS = Op.getOperand(2);
11166     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11167     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11168     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11169     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11170                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11171     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11172   }
11173
11174   // Arithmetic intrinsics.
11175   case Intrinsic::x86_sse2_pmulu_dq:
11176   case Intrinsic::x86_avx2_pmulu_dq:
11177     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11178                        Op.getOperand(1), Op.getOperand(2));
11179
11180   // SSE2/AVX2 sub with unsigned saturation intrinsics
11181   case Intrinsic::x86_sse2_psubus_b:
11182   case Intrinsic::x86_sse2_psubus_w:
11183   case Intrinsic::x86_avx2_psubus_b:
11184   case Intrinsic::x86_avx2_psubus_w:
11185     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11186                        Op.getOperand(1), Op.getOperand(2));
11187
11188   // SSE3/AVX horizontal add/sub intrinsics
11189   case Intrinsic::x86_sse3_hadd_ps:
11190   case Intrinsic::x86_sse3_hadd_pd:
11191   case Intrinsic::x86_avx_hadd_ps_256:
11192   case Intrinsic::x86_avx_hadd_pd_256:
11193   case Intrinsic::x86_sse3_hsub_ps:
11194   case Intrinsic::x86_sse3_hsub_pd:
11195   case Intrinsic::x86_avx_hsub_ps_256:
11196   case Intrinsic::x86_avx_hsub_pd_256:
11197   case Intrinsic::x86_ssse3_phadd_w_128:
11198   case Intrinsic::x86_ssse3_phadd_d_128:
11199   case Intrinsic::x86_avx2_phadd_w:
11200   case Intrinsic::x86_avx2_phadd_d:
11201   case Intrinsic::x86_ssse3_phsub_w_128:
11202   case Intrinsic::x86_ssse3_phsub_d_128:
11203   case Intrinsic::x86_avx2_phsub_w:
11204   case Intrinsic::x86_avx2_phsub_d: {
11205     unsigned Opcode;
11206     switch (IntNo) {
11207     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11208     case Intrinsic::x86_sse3_hadd_ps:
11209     case Intrinsic::x86_sse3_hadd_pd:
11210     case Intrinsic::x86_avx_hadd_ps_256:
11211     case Intrinsic::x86_avx_hadd_pd_256:
11212       Opcode = X86ISD::FHADD;
11213       break;
11214     case Intrinsic::x86_sse3_hsub_ps:
11215     case Intrinsic::x86_sse3_hsub_pd:
11216     case Intrinsic::x86_avx_hsub_ps_256:
11217     case Intrinsic::x86_avx_hsub_pd_256:
11218       Opcode = X86ISD::FHSUB;
11219       break;
11220     case Intrinsic::x86_ssse3_phadd_w_128:
11221     case Intrinsic::x86_ssse3_phadd_d_128:
11222     case Intrinsic::x86_avx2_phadd_w:
11223     case Intrinsic::x86_avx2_phadd_d:
11224       Opcode = X86ISD::HADD;
11225       break;
11226     case Intrinsic::x86_ssse3_phsub_w_128:
11227     case Intrinsic::x86_ssse3_phsub_d_128:
11228     case Intrinsic::x86_avx2_phsub_w:
11229     case Intrinsic::x86_avx2_phsub_d:
11230       Opcode = X86ISD::HSUB;
11231       break;
11232     }
11233     return DAG.getNode(Opcode, dl, Op.getValueType(),
11234                        Op.getOperand(1), Op.getOperand(2));
11235   }
11236
11237   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11238   case Intrinsic::x86_sse2_pmaxu_b:
11239   case Intrinsic::x86_sse41_pmaxuw:
11240   case Intrinsic::x86_sse41_pmaxud:
11241   case Intrinsic::x86_avx2_pmaxu_b:
11242   case Intrinsic::x86_avx2_pmaxu_w:
11243   case Intrinsic::x86_avx2_pmaxu_d:
11244   case Intrinsic::x86_avx512_pmaxu_d:
11245   case Intrinsic::x86_avx512_pmaxu_q:
11246   case Intrinsic::x86_sse2_pminu_b:
11247   case Intrinsic::x86_sse41_pminuw:
11248   case Intrinsic::x86_sse41_pminud:
11249   case Intrinsic::x86_avx2_pminu_b:
11250   case Intrinsic::x86_avx2_pminu_w:
11251   case Intrinsic::x86_avx2_pminu_d:
11252   case Intrinsic::x86_avx512_pminu_d:
11253   case Intrinsic::x86_avx512_pminu_q:
11254   case Intrinsic::x86_sse41_pmaxsb:
11255   case Intrinsic::x86_sse2_pmaxs_w:
11256   case Intrinsic::x86_sse41_pmaxsd:
11257   case Intrinsic::x86_avx2_pmaxs_b:
11258   case Intrinsic::x86_avx2_pmaxs_w:
11259   case Intrinsic::x86_avx2_pmaxs_d:
11260   case Intrinsic::x86_avx512_pmaxs_d:
11261   case Intrinsic::x86_avx512_pmaxs_q:
11262   case Intrinsic::x86_sse41_pminsb:
11263   case Intrinsic::x86_sse2_pmins_w:
11264   case Intrinsic::x86_sse41_pminsd:
11265   case Intrinsic::x86_avx2_pmins_b:
11266   case Intrinsic::x86_avx2_pmins_w:
11267   case Intrinsic::x86_avx2_pmins_d:
11268   case Intrinsic::x86_avx512_pmins_d:
11269   case Intrinsic::x86_avx512_pmins_q: {
11270     unsigned Opcode;
11271     switch (IntNo) {
11272     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11273     case Intrinsic::x86_sse2_pmaxu_b:
11274     case Intrinsic::x86_sse41_pmaxuw:
11275     case Intrinsic::x86_sse41_pmaxud:
11276     case Intrinsic::x86_avx2_pmaxu_b:
11277     case Intrinsic::x86_avx2_pmaxu_w:
11278     case Intrinsic::x86_avx2_pmaxu_d:
11279     case Intrinsic::x86_avx512_pmaxu_d:
11280     case Intrinsic::x86_avx512_pmaxu_q:
11281       Opcode = X86ISD::UMAX;
11282       break;
11283     case Intrinsic::x86_sse2_pminu_b:
11284     case Intrinsic::x86_sse41_pminuw:
11285     case Intrinsic::x86_sse41_pminud:
11286     case Intrinsic::x86_avx2_pminu_b:
11287     case Intrinsic::x86_avx2_pminu_w:
11288     case Intrinsic::x86_avx2_pminu_d:
11289     case Intrinsic::x86_avx512_pminu_d:
11290     case Intrinsic::x86_avx512_pminu_q:
11291       Opcode = X86ISD::UMIN;
11292       break;
11293     case Intrinsic::x86_sse41_pmaxsb:
11294     case Intrinsic::x86_sse2_pmaxs_w:
11295     case Intrinsic::x86_sse41_pmaxsd:
11296     case Intrinsic::x86_avx2_pmaxs_b:
11297     case Intrinsic::x86_avx2_pmaxs_w:
11298     case Intrinsic::x86_avx2_pmaxs_d:
11299     case Intrinsic::x86_avx512_pmaxs_d:
11300     case Intrinsic::x86_avx512_pmaxs_q:
11301       Opcode = X86ISD::SMAX;
11302       break;
11303     case Intrinsic::x86_sse41_pminsb:
11304     case Intrinsic::x86_sse2_pmins_w:
11305     case Intrinsic::x86_sse41_pminsd:
11306     case Intrinsic::x86_avx2_pmins_b:
11307     case Intrinsic::x86_avx2_pmins_w:
11308     case Intrinsic::x86_avx2_pmins_d:
11309     case Intrinsic::x86_avx512_pmins_d:
11310     case Intrinsic::x86_avx512_pmins_q:
11311       Opcode = X86ISD::SMIN;
11312       break;
11313     }
11314     return DAG.getNode(Opcode, dl, Op.getValueType(),
11315                        Op.getOperand(1), Op.getOperand(2));
11316   }
11317
11318   // SSE/SSE2/AVX floating point max/min intrinsics.
11319   case Intrinsic::x86_sse_max_ps:
11320   case Intrinsic::x86_sse2_max_pd:
11321   case Intrinsic::x86_avx_max_ps_256:
11322   case Intrinsic::x86_avx_max_pd_256:
11323   case Intrinsic::x86_avx512_max_ps_512:
11324   case Intrinsic::x86_avx512_max_pd_512:
11325   case Intrinsic::x86_sse_min_ps:
11326   case Intrinsic::x86_sse2_min_pd:
11327   case Intrinsic::x86_avx_min_ps_256:
11328   case Intrinsic::x86_avx_min_pd_256:
11329   case Intrinsic::x86_avx512_min_ps_512:
11330   case Intrinsic::x86_avx512_min_pd_512:  {
11331     unsigned Opcode;
11332     switch (IntNo) {
11333     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11334     case Intrinsic::x86_sse_max_ps:
11335     case Intrinsic::x86_sse2_max_pd:
11336     case Intrinsic::x86_avx_max_ps_256:
11337     case Intrinsic::x86_avx_max_pd_256:
11338     case Intrinsic::x86_avx512_max_ps_512:
11339     case Intrinsic::x86_avx512_max_pd_512:
11340       Opcode = X86ISD::FMAX;
11341       break;
11342     case Intrinsic::x86_sse_min_ps:
11343     case Intrinsic::x86_sse2_min_pd:
11344     case Intrinsic::x86_avx_min_ps_256:
11345     case Intrinsic::x86_avx_min_pd_256:
11346     case Intrinsic::x86_avx512_min_ps_512:
11347     case Intrinsic::x86_avx512_min_pd_512:
11348       Opcode = X86ISD::FMIN;
11349       break;
11350     }
11351     return DAG.getNode(Opcode, dl, Op.getValueType(),
11352                        Op.getOperand(1), Op.getOperand(2));
11353   }
11354
11355   // AVX2 variable shift intrinsics
11356   case Intrinsic::x86_avx2_psllv_d:
11357   case Intrinsic::x86_avx2_psllv_q:
11358   case Intrinsic::x86_avx2_psllv_d_256:
11359   case Intrinsic::x86_avx2_psllv_q_256:
11360   case Intrinsic::x86_avx2_psrlv_d:
11361   case Intrinsic::x86_avx2_psrlv_q:
11362   case Intrinsic::x86_avx2_psrlv_d_256:
11363   case Intrinsic::x86_avx2_psrlv_q_256:
11364   case Intrinsic::x86_avx2_psrav_d:
11365   case Intrinsic::x86_avx2_psrav_d_256: {
11366     unsigned Opcode;
11367     switch (IntNo) {
11368     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11369     case Intrinsic::x86_avx2_psllv_d:
11370     case Intrinsic::x86_avx2_psllv_q:
11371     case Intrinsic::x86_avx2_psllv_d_256:
11372     case Intrinsic::x86_avx2_psllv_q_256:
11373       Opcode = ISD::SHL;
11374       break;
11375     case Intrinsic::x86_avx2_psrlv_d:
11376     case Intrinsic::x86_avx2_psrlv_q:
11377     case Intrinsic::x86_avx2_psrlv_d_256:
11378     case Intrinsic::x86_avx2_psrlv_q_256:
11379       Opcode = ISD::SRL;
11380       break;
11381     case Intrinsic::x86_avx2_psrav_d:
11382     case Intrinsic::x86_avx2_psrav_d_256:
11383       Opcode = ISD::SRA;
11384       break;
11385     }
11386     return DAG.getNode(Opcode, dl, Op.getValueType(),
11387                        Op.getOperand(1), Op.getOperand(2));
11388   }
11389
11390   case Intrinsic::x86_ssse3_pshuf_b_128:
11391   case Intrinsic::x86_avx2_pshuf_b:
11392     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11393                        Op.getOperand(1), Op.getOperand(2));
11394
11395   case Intrinsic::x86_ssse3_psign_b_128:
11396   case Intrinsic::x86_ssse3_psign_w_128:
11397   case Intrinsic::x86_ssse3_psign_d_128:
11398   case Intrinsic::x86_avx2_psign_b:
11399   case Intrinsic::x86_avx2_psign_w:
11400   case Intrinsic::x86_avx2_psign_d:
11401     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11402                        Op.getOperand(1), Op.getOperand(2));
11403
11404   case Intrinsic::x86_sse41_insertps:
11405     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11406                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11407
11408   case Intrinsic::x86_avx_vperm2f128_ps_256:
11409   case Intrinsic::x86_avx_vperm2f128_pd_256:
11410   case Intrinsic::x86_avx_vperm2f128_si_256:
11411   case Intrinsic::x86_avx2_vperm2i128:
11412     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11413                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11414
11415   case Intrinsic::x86_avx2_permd:
11416   case Intrinsic::x86_avx2_permps:
11417     // Operands intentionally swapped. Mask is last operand to intrinsic,
11418     // but second operand for node/instruction.
11419     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11420                        Op.getOperand(2), Op.getOperand(1));
11421
11422   case Intrinsic::x86_sse_sqrt_ps:
11423   case Intrinsic::x86_sse2_sqrt_pd:
11424   case Intrinsic::x86_avx_sqrt_ps_256:
11425   case Intrinsic::x86_avx_sqrt_pd_256:
11426     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11427
11428   // ptest and testp intrinsics. The intrinsic these come from are designed to
11429   // return an integer value, not just an instruction so lower it to the ptest
11430   // or testp pattern and a setcc for the result.
11431   case Intrinsic::x86_sse41_ptestz:
11432   case Intrinsic::x86_sse41_ptestc:
11433   case Intrinsic::x86_sse41_ptestnzc:
11434   case Intrinsic::x86_avx_ptestz_256:
11435   case Intrinsic::x86_avx_ptestc_256:
11436   case Intrinsic::x86_avx_ptestnzc_256:
11437   case Intrinsic::x86_avx_vtestz_ps:
11438   case Intrinsic::x86_avx_vtestc_ps:
11439   case Intrinsic::x86_avx_vtestnzc_ps:
11440   case Intrinsic::x86_avx_vtestz_pd:
11441   case Intrinsic::x86_avx_vtestc_pd:
11442   case Intrinsic::x86_avx_vtestnzc_pd:
11443   case Intrinsic::x86_avx_vtestz_ps_256:
11444   case Intrinsic::x86_avx_vtestc_ps_256:
11445   case Intrinsic::x86_avx_vtestnzc_ps_256:
11446   case Intrinsic::x86_avx_vtestz_pd_256:
11447   case Intrinsic::x86_avx_vtestc_pd_256:
11448   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11449     bool IsTestPacked = false;
11450     unsigned X86CC;
11451     switch (IntNo) {
11452     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11453     case Intrinsic::x86_avx_vtestz_ps:
11454     case Intrinsic::x86_avx_vtestz_pd:
11455     case Intrinsic::x86_avx_vtestz_ps_256:
11456     case Intrinsic::x86_avx_vtestz_pd_256:
11457       IsTestPacked = true; // Fallthrough
11458     case Intrinsic::x86_sse41_ptestz:
11459     case Intrinsic::x86_avx_ptestz_256:
11460       // ZF = 1
11461       X86CC = X86::COND_E;
11462       break;
11463     case Intrinsic::x86_avx_vtestc_ps:
11464     case Intrinsic::x86_avx_vtestc_pd:
11465     case Intrinsic::x86_avx_vtestc_ps_256:
11466     case Intrinsic::x86_avx_vtestc_pd_256:
11467       IsTestPacked = true; // Fallthrough
11468     case Intrinsic::x86_sse41_ptestc:
11469     case Intrinsic::x86_avx_ptestc_256:
11470       // CF = 1
11471       X86CC = X86::COND_B;
11472       break;
11473     case Intrinsic::x86_avx_vtestnzc_ps:
11474     case Intrinsic::x86_avx_vtestnzc_pd:
11475     case Intrinsic::x86_avx_vtestnzc_ps_256:
11476     case Intrinsic::x86_avx_vtestnzc_pd_256:
11477       IsTestPacked = true; // Fallthrough
11478     case Intrinsic::x86_sse41_ptestnzc:
11479     case Intrinsic::x86_avx_ptestnzc_256:
11480       // ZF and CF = 0
11481       X86CC = X86::COND_A;
11482       break;
11483     }
11484
11485     SDValue LHS = Op.getOperand(1);
11486     SDValue RHS = Op.getOperand(2);
11487     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11488     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11489     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11490     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11491     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11492   }
11493   case Intrinsic::x86_avx512_kortestz:
11494   case Intrinsic::x86_avx512_kortestc: {
11495     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz)? X86::COND_E: X86::COND_B;
11496     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11497     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11498     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11499     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11500     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11501     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11502   }
11503
11504   // SSE/AVX shift intrinsics
11505   case Intrinsic::x86_sse2_psll_w:
11506   case Intrinsic::x86_sse2_psll_d:
11507   case Intrinsic::x86_sse2_psll_q:
11508   case Intrinsic::x86_avx2_psll_w:
11509   case Intrinsic::x86_avx2_psll_d:
11510   case Intrinsic::x86_avx2_psll_q:
11511   case Intrinsic::x86_sse2_psrl_w:
11512   case Intrinsic::x86_sse2_psrl_d:
11513   case Intrinsic::x86_sse2_psrl_q:
11514   case Intrinsic::x86_avx2_psrl_w:
11515   case Intrinsic::x86_avx2_psrl_d:
11516   case Intrinsic::x86_avx2_psrl_q:
11517   case Intrinsic::x86_sse2_psra_w:
11518   case Intrinsic::x86_sse2_psra_d:
11519   case Intrinsic::x86_avx2_psra_w:
11520   case Intrinsic::x86_avx2_psra_d: {
11521     unsigned Opcode;
11522     switch (IntNo) {
11523     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11524     case Intrinsic::x86_sse2_psll_w:
11525     case Intrinsic::x86_sse2_psll_d:
11526     case Intrinsic::x86_sse2_psll_q:
11527     case Intrinsic::x86_avx2_psll_w:
11528     case Intrinsic::x86_avx2_psll_d:
11529     case Intrinsic::x86_avx2_psll_q:
11530       Opcode = X86ISD::VSHL;
11531       break;
11532     case Intrinsic::x86_sse2_psrl_w:
11533     case Intrinsic::x86_sse2_psrl_d:
11534     case Intrinsic::x86_sse2_psrl_q:
11535     case Intrinsic::x86_avx2_psrl_w:
11536     case Intrinsic::x86_avx2_psrl_d:
11537     case Intrinsic::x86_avx2_psrl_q:
11538       Opcode = X86ISD::VSRL;
11539       break;
11540     case Intrinsic::x86_sse2_psra_w:
11541     case Intrinsic::x86_sse2_psra_d:
11542     case Intrinsic::x86_avx2_psra_w:
11543     case Intrinsic::x86_avx2_psra_d:
11544       Opcode = X86ISD::VSRA;
11545       break;
11546     }
11547     return DAG.getNode(Opcode, dl, Op.getValueType(),
11548                        Op.getOperand(1), Op.getOperand(2));
11549   }
11550
11551   // SSE/AVX immediate shift intrinsics
11552   case Intrinsic::x86_sse2_pslli_w:
11553   case Intrinsic::x86_sse2_pslli_d:
11554   case Intrinsic::x86_sse2_pslli_q:
11555   case Intrinsic::x86_avx2_pslli_w:
11556   case Intrinsic::x86_avx2_pslli_d:
11557   case Intrinsic::x86_avx2_pslli_q:
11558   case Intrinsic::x86_sse2_psrli_w:
11559   case Intrinsic::x86_sse2_psrli_d:
11560   case Intrinsic::x86_sse2_psrli_q:
11561   case Intrinsic::x86_avx2_psrli_w:
11562   case Intrinsic::x86_avx2_psrli_d:
11563   case Intrinsic::x86_avx2_psrli_q:
11564   case Intrinsic::x86_sse2_psrai_w:
11565   case Intrinsic::x86_sse2_psrai_d:
11566   case Intrinsic::x86_avx2_psrai_w:
11567   case Intrinsic::x86_avx2_psrai_d: {
11568     unsigned Opcode;
11569     switch (IntNo) {
11570     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11571     case Intrinsic::x86_sse2_pslli_w:
11572     case Intrinsic::x86_sse2_pslli_d:
11573     case Intrinsic::x86_sse2_pslli_q:
11574     case Intrinsic::x86_avx2_pslli_w:
11575     case Intrinsic::x86_avx2_pslli_d:
11576     case Intrinsic::x86_avx2_pslli_q:
11577       Opcode = X86ISD::VSHLI;
11578       break;
11579     case Intrinsic::x86_sse2_psrli_w:
11580     case Intrinsic::x86_sse2_psrli_d:
11581     case Intrinsic::x86_sse2_psrli_q:
11582     case Intrinsic::x86_avx2_psrli_w:
11583     case Intrinsic::x86_avx2_psrli_d:
11584     case Intrinsic::x86_avx2_psrli_q:
11585       Opcode = X86ISD::VSRLI;
11586       break;
11587     case Intrinsic::x86_sse2_psrai_w:
11588     case Intrinsic::x86_sse2_psrai_d:
11589     case Intrinsic::x86_avx2_psrai_w:
11590     case Intrinsic::x86_avx2_psrai_d:
11591       Opcode = X86ISD::VSRAI;
11592       break;
11593     }
11594     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11595                                Op.getOperand(1), Op.getOperand(2), DAG);
11596   }
11597
11598   case Intrinsic::x86_sse42_pcmpistria128:
11599   case Intrinsic::x86_sse42_pcmpestria128:
11600   case Intrinsic::x86_sse42_pcmpistric128:
11601   case Intrinsic::x86_sse42_pcmpestric128:
11602   case Intrinsic::x86_sse42_pcmpistrio128:
11603   case Intrinsic::x86_sse42_pcmpestrio128:
11604   case Intrinsic::x86_sse42_pcmpistris128:
11605   case Intrinsic::x86_sse42_pcmpestris128:
11606   case Intrinsic::x86_sse42_pcmpistriz128:
11607   case Intrinsic::x86_sse42_pcmpestriz128: {
11608     unsigned Opcode;
11609     unsigned X86CC;
11610     switch (IntNo) {
11611     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11612     case Intrinsic::x86_sse42_pcmpistria128:
11613       Opcode = X86ISD::PCMPISTRI;
11614       X86CC = X86::COND_A;
11615       break;
11616     case Intrinsic::x86_sse42_pcmpestria128:
11617       Opcode = X86ISD::PCMPESTRI;
11618       X86CC = X86::COND_A;
11619       break;
11620     case Intrinsic::x86_sse42_pcmpistric128:
11621       Opcode = X86ISD::PCMPISTRI;
11622       X86CC = X86::COND_B;
11623       break;
11624     case Intrinsic::x86_sse42_pcmpestric128:
11625       Opcode = X86ISD::PCMPESTRI;
11626       X86CC = X86::COND_B;
11627       break;
11628     case Intrinsic::x86_sse42_pcmpistrio128:
11629       Opcode = X86ISD::PCMPISTRI;
11630       X86CC = X86::COND_O;
11631       break;
11632     case Intrinsic::x86_sse42_pcmpestrio128:
11633       Opcode = X86ISD::PCMPESTRI;
11634       X86CC = X86::COND_O;
11635       break;
11636     case Intrinsic::x86_sse42_pcmpistris128:
11637       Opcode = X86ISD::PCMPISTRI;
11638       X86CC = X86::COND_S;
11639       break;
11640     case Intrinsic::x86_sse42_pcmpestris128:
11641       Opcode = X86ISD::PCMPESTRI;
11642       X86CC = X86::COND_S;
11643       break;
11644     case Intrinsic::x86_sse42_pcmpistriz128:
11645       Opcode = X86ISD::PCMPISTRI;
11646       X86CC = X86::COND_E;
11647       break;
11648     case Intrinsic::x86_sse42_pcmpestriz128:
11649       Opcode = X86ISD::PCMPESTRI;
11650       X86CC = X86::COND_E;
11651       break;
11652     }
11653     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11654     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11655     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11656     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11657                                 DAG.getConstant(X86CC, MVT::i8),
11658                                 SDValue(PCMP.getNode(), 1));
11659     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11660   }
11661
11662   case Intrinsic::x86_sse42_pcmpistri128:
11663   case Intrinsic::x86_sse42_pcmpestri128: {
11664     unsigned Opcode;
11665     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11666       Opcode = X86ISD::PCMPISTRI;
11667     else
11668       Opcode = X86ISD::PCMPESTRI;
11669
11670     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11671     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11672     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11673   }
11674   case Intrinsic::x86_fma_vfmadd_ps:
11675   case Intrinsic::x86_fma_vfmadd_pd:
11676   case Intrinsic::x86_fma_vfmsub_ps:
11677   case Intrinsic::x86_fma_vfmsub_pd:
11678   case Intrinsic::x86_fma_vfnmadd_ps:
11679   case Intrinsic::x86_fma_vfnmadd_pd:
11680   case Intrinsic::x86_fma_vfnmsub_ps:
11681   case Intrinsic::x86_fma_vfnmsub_pd:
11682   case Intrinsic::x86_fma_vfmaddsub_ps:
11683   case Intrinsic::x86_fma_vfmaddsub_pd:
11684   case Intrinsic::x86_fma_vfmsubadd_ps:
11685   case Intrinsic::x86_fma_vfmsubadd_pd:
11686   case Intrinsic::x86_fma_vfmadd_ps_256:
11687   case Intrinsic::x86_fma_vfmadd_pd_256:
11688   case Intrinsic::x86_fma_vfmsub_ps_256:
11689   case Intrinsic::x86_fma_vfmsub_pd_256:
11690   case Intrinsic::x86_fma_vfnmadd_ps_256:
11691   case Intrinsic::x86_fma_vfnmadd_pd_256:
11692   case Intrinsic::x86_fma_vfnmsub_ps_256:
11693   case Intrinsic::x86_fma_vfnmsub_pd_256:
11694   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11695   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11696   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11697   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11698   case Intrinsic::x86_fma_vfmadd_ps_512:
11699   case Intrinsic::x86_fma_vfmadd_pd_512:
11700   case Intrinsic::x86_fma_vfmsub_ps_512:
11701   case Intrinsic::x86_fma_vfmsub_pd_512:
11702   case Intrinsic::x86_fma_vfnmadd_ps_512:
11703   case Intrinsic::x86_fma_vfnmadd_pd_512:
11704   case Intrinsic::x86_fma_vfnmsub_ps_512:
11705   case Intrinsic::x86_fma_vfnmsub_pd_512:
11706   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11707   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11708   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11709   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11710     unsigned Opc;
11711     switch (IntNo) {
11712     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11713     case Intrinsic::x86_fma_vfmadd_ps:
11714     case Intrinsic::x86_fma_vfmadd_pd:
11715     case Intrinsic::x86_fma_vfmadd_ps_256:
11716     case Intrinsic::x86_fma_vfmadd_pd_256:
11717     case Intrinsic::x86_fma_vfmadd_ps_512:
11718     case Intrinsic::x86_fma_vfmadd_pd_512:
11719       Opc = X86ISD::FMADD;
11720       break;
11721     case Intrinsic::x86_fma_vfmsub_ps:
11722     case Intrinsic::x86_fma_vfmsub_pd:
11723     case Intrinsic::x86_fma_vfmsub_ps_256:
11724     case Intrinsic::x86_fma_vfmsub_pd_256:
11725     case Intrinsic::x86_fma_vfmsub_ps_512:
11726     case Intrinsic::x86_fma_vfmsub_pd_512:
11727       Opc = X86ISD::FMSUB;
11728       break;
11729     case Intrinsic::x86_fma_vfnmadd_ps:
11730     case Intrinsic::x86_fma_vfnmadd_pd:
11731     case Intrinsic::x86_fma_vfnmadd_ps_256:
11732     case Intrinsic::x86_fma_vfnmadd_pd_256:
11733     case Intrinsic::x86_fma_vfnmadd_ps_512:
11734     case Intrinsic::x86_fma_vfnmadd_pd_512:
11735       Opc = X86ISD::FNMADD;
11736       break;
11737     case Intrinsic::x86_fma_vfnmsub_ps:
11738     case Intrinsic::x86_fma_vfnmsub_pd:
11739     case Intrinsic::x86_fma_vfnmsub_ps_256:
11740     case Intrinsic::x86_fma_vfnmsub_pd_256:
11741     case Intrinsic::x86_fma_vfnmsub_ps_512:
11742     case Intrinsic::x86_fma_vfnmsub_pd_512:
11743       Opc = X86ISD::FNMSUB;
11744       break;
11745     case Intrinsic::x86_fma_vfmaddsub_ps:
11746     case Intrinsic::x86_fma_vfmaddsub_pd:
11747     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11748     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11749     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11750     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11751       Opc = X86ISD::FMADDSUB;
11752       break;
11753     case Intrinsic::x86_fma_vfmsubadd_ps:
11754     case Intrinsic::x86_fma_vfmsubadd_pd:
11755     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11756     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11757     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11758     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11759       Opc = X86ISD::FMSUBADD;
11760       break;
11761     }
11762
11763     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11764                        Op.getOperand(2), Op.getOperand(3));
11765   }
11766   }
11767 }
11768
11769 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11770                              SDValue Base, SDValue Index,
11771                              SDValue ScaleOp, SDValue Chain,
11772                              const X86Subtarget * Subtarget) {
11773   SDLoc dl(Op);
11774   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11775   assert(C && "Invalid scale type");
11776   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11777   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11778   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11779                                 Index.getValueType().getVectorNumElements());
11780   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11781   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11782   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11783   SDValue Segment = DAG.getRegister(0, MVT::i32);
11784   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11785   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11786   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11787   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11788 }
11789
11790 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11791                               SDValue Src, SDValue Mask, SDValue Base,
11792                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11793                               const X86Subtarget * Subtarget) {
11794   SDLoc dl(Op);
11795   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11796   assert(C && "Invalid scale type");
11797   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11798   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11799                                 Index.getValueType().getVectorNumElements());
11800   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11801   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11802   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11803   SDValue Segment = DAG.getRegister(0, MVT::i32);
11804   if (Src.getOpcode() == ISD::UNDEF)
11805     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11806   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11807   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11808   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11809   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11810 }
11811
11812 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11813                               SDValue Src, SDValue Base, SDValue Index,
11814                               SDValue ScaleOp, SDValue Chain) {
11815   SDLoc dl(Op);
11816   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11817   assert(C && "Invalid scale type");
11818   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11819   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11820   SDValue Segment = DAG.getRegister(0, MVT::i32);
11821   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11822                                 Index.getValueType().getVectorNumElements());
11823   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11824   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11825   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11826   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11827   return SDValue(Res, 1);
11828 }
11829
11830 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11831                                SDValue Src, SDValue Mask, SDValue Base,
11832                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
11833   SDLoc dl(Op);
11834   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11835   assert(C && "Invalid scale type");
11836   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11837   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11838   SDValue Segment = DAG.getRegister(0, MVT::i32);
11839   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11840                                 Index.getValueType().getVectorNumElements());
11841   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11842   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11843   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11844   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11845   return SDValue(Res, 1);
11846 }
11847
11848 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11849                                       SelectionDAG &DAG) {
11850   SDLoc dl(Op);
11851   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11852   switch (IntNo) {
11853   default: return SDValue();    // Don't custom lower most intrinsics.
11854
11855   // RDRAND/RDSEED intrinsics.
11856   case Intrinsic::x86_rdrand_16:
11857   case Intrinsic::x86_rdrand_32:
11858   case Intrinsic::x86_rdrand_64:
11859   case Intrinsic::x86_rdseed_16:
11860   case Intrinsic::x86_rdseed_32:
11861   case Intrinsic::x86_rdseed_64: {
11862     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11863                        IntNo == Intrinsic::x86_rdseed_32 ||
11864                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11865                                                             X86ISD::RDRAND;
11866     // Emit the node with the right value type.
11867     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11868     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11869
11870     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11871     // Otherwise return the value from Rand, which is always 0, casted to i32.
11872     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11873                       DAG.getConstant(1, Op->getValueType(1)),
11874                       DAG.getConstant(X86::COND_B, MVT::i32),
11875                       SDValue(Result.getNode(), 1) };
11876     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11877                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11878                                   Ops, array_lengthof(Ops));
11879
11880     // Return { result, isValid, chain }.
11881     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11882                        SDValue(Result.getNode(), 2));
11883   }
11884   //int_gather(index, base, scale);
11885   case Intrinsic::x86_avx512_gather_qpd_512:
11886   case Intrinsic::x86_avx512_gather_qps_512:
11887   case Intrinsic::x86_avx512_gather_dpd_512:
11888   case Intrinsic::x86_avx512_gather_qpi_512:
11889   case Intrinsic::x86_avx512_gather_qpq_512:
11890   case Intrinsic::x86_avx512_gather_dpq_512:
11891   case Intrinsic::x86_avx512_gather_dps_512:
11892   case Intrinsic::x86_avx512_gather_dpi_512: {
11893     unsigned Opc;
11894     switch (IntNo) {
11895       default: llvm_unreachable("Unexpected intrinsic!");
11896       case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
11897       case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
11898       case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
11899       case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
11900       case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
11901       case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
11902       case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
11903       case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
11904     }
11905     SDValue Chain = Op.getOperand(0);
11906     SDValue Index = Op.getOperand(2);
11907     SDValue Base  = Op.getOperand(3);
11908     SDValue Scale = Op.getOperand(4);
11909     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
11910   }
11911   //int_gather_mask(v1, mask, index, base, scale);
11912   case Intrinsic::x86_avx512_gather_qps_mask_512:
11913   case Intrinsic::x86_avx512_gather_qpd_mask_512:
11914   case Intrinsic::x86_avx512_gather_dpd_mask_512:
11915   case Intrinsic::x86_avx512_gather_dps_mask_512:
11916   case Intrinsic::x86_avx512_gather_qpi_mask_512:
11917   case Intrinsic::x86_avx512_gather_qpq_mask_512:
11918   case Intrinsic::x86_avx512_gather_dpi_mask_512:
11919   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
11920     unsigned Opc;
11921     switch (IntNo) {
11922       default: llvm_unreachable("Unexpected intrinsic!");
11923       case Intrinsic::x86_avx512_gather_qps_mask_512:
11924         Opc = X86::VGATHERQPSZrm; break;
11925       case Intrinsic::x86_avx512_gather_qpd_mask_512:
11926         Opc = X86::VGATHERQPDZrm; break;
11927       case Intrinsic::x86_avx512_gather_dpd_mask_512:
11928         Opc = X86::VGATHERDPDZrm; break;
11929       case Intrinsic::x86_avx512_gather_dps_mask_512:
11930         Opc = X86::VGATHERDPSZrm; break;
11931       case Intrinsic::x86_avx512_gather_qpi_mask_512:
11932         Opc = X86::VPGATHERQDZrm; break;
11933       case Intrinsic::x86_avx512_gather_qpq_mask_512:
11934         Opc = X86::VPGATHERQQZrm; break;
11935       case Intrinsic::x86_avx512_gather_dpi_mask_512:
11936         Opc = X86::VPGATHERDDZrm; break;
11937       case Intrinsic::x86_avx512_gather_dpq_mask_512:
11938         Opc = X86::VPGATHERDQZrm; break;
11939     }
11940     SDValue Chain = Op.getOperand(0);
11941     SDValue Src   = Op.getOperand(2);
11942     SDValue Mask  = Op.getOperand(3);
11943     SDValue Index = Op.getOperand(4);
11944     SDValue Base  = Op.getOperand(5);
11945     SDValue Scale = Op.getOperand(6);
11946     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
11947                           Subtarget);
11948   }
11949   //int_scatter(base, index, v1, scale);
11950   case Intrinsic::x86_avx512_scatter_qpd_512:
11951   case Intrinsic::x86_avx512_scatter_qps_512:
11952   case Intrinsic::x86_avx512_scatter_dpd_512:
11953   case Intrinsic::x86_avx512_scatter_qpi_512:
11954   case Intrinsic::x86_avx512_scatter_qpq_512:
11955   case Intrinsic::x86_avx512_scatter_dpq_512:
11956   case Intrinsic::x86_avx512_scatter_dps_512:
11957   case Intrinsic::x86_avx512_scatter_dpi_512: {
11958     unsigned Opc;
11959     switch (IntNo) {
11960       default: llvm_unreachable("Unexpected intrinsic!");
11961       case Intrinsic::x86_avx512_scatter_qpd_512:
11962         Opc = X86::VSCATTERQPDZmr; break;
11963       case Intrinsic::x86_avx512_scatter_qps_512:
11964         Opc = X86::VSCATTERQPSZmr; break;
11965       case Intrinsic::x86_avx512_scatter_dpd_512:
11966         Opc = X86::VSCATTERDPDZmr; break;
11967       case Intrinsic::x86_avx512_scatter_dps_512:
11968         Opc = X86::VSCATTERDPSZmr; break;
11969       case Intrinsic::x86_avx512_scatter_qpi_512:
11970         Opc = X86::VPSCATTERQDZmr; break;
11971       case Intrinsic::x86_avx512_scatter_qpq_512:
11972         Opc = X86::VPSCATTERQQZmr; break;
11973       case Intrinsic::x86_avx512_scatter_dpq_512:
11974         Opc = X86::VPSCATTERDQZmr; break;
11975       case Intrinsic::x86_avx512_scatter_dpi_512:
11976         Opc = X86::VPSCATTERDDZmr; break;
11977     }
11978     SDValue Chain = Op.getOperand(0);
11979     SDValue Base  = Op.getOperand(2);
11980     SDValue Index = Op.getOperand(3);
11981     SDValue Src   = Op.getOperand(4);
11982     SDValue Scale = Op.getOperand(5);
11983     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
11984   }
11985   //int_scatter_mask(base, mask, index, v1, scale);
11986   case Intrinsic::x86_avx512_scatter_qps_mask_512:
11987   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
11988   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
11989   case Intrinsic::x86_avx512_scatter_dps_mask_512:
11990   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
11991   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
11992   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
11993   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
11994     unsigned Opc;
11995     switch (IntNo) {
11996       default: llvm_unreachable("Unexpected intrinsic!");
11997       case Intrinsic::x86_avx512_scatter_qpd_mask_512:
11998         Opc = X86::VSCATTERQPDZmr; break;
11999       case Intrinsic::x86_avx512_scatter_qps_mask_512:
12000         Opc = X86::VSCATTERQPSZmr; break;
12001       case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12002         Opc = X86::VSCATTERDPDZmr; break;
12003       case Intrinsic::x86_avx512_scatter_dps_mask_512:
12004         Opc = X86::VSCATTERDPSZmr; break;
12005       case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12006         Opc = X86::VPSCATTERQDZmr; break;
12007       case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12008         Opc = X86::VPSCATTERQQZmr; break;
12009       case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12010         Opc = X86::VPSCATTERDQZmr; break;
12011       case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12012         Opc = X86::VPSCATTERDDZmr; break;
12013     }
12014     SDValue Chain = Op.getOperand(0);
12015     SDValue Base  = Op.getOperand(2);
12016     SDValue Mask  = Op.getOperand(3);
12017     SDValue Index = Op.getOperand(4);
12018     SDValue Src   = Op.getOperand(5);
12019     SDValue Scale = Op.getOperand(6);
12020     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12021   }
12022   // XTEST intrinsics.
12023   case Intrinsic::x86_xtest: {
12024     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12025     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12026     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12027                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12028                                 InTrans);
12029     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12030     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12031                        Ret, SDValue(InTrans.getNode(), 1));
12032   }
12033   }
12034 }
12035
12036 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12037                                            SelectionDAG &DAG) const {
12038   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12039   MFI->setReturnAddressIsTaken(true);
12040
12041   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12042   SDLoc dl(Op);
12043   EVT PtrVT = getPointerTy();
12044
12045   if (Depth > 0) {
12046     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12047     const X86RegisterInfo *RegInfo =
12048       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12049     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12050     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12051                        DAG.getNode(ISD::ADD, dl, PtrVT,
12052                                    FrameAddr, Offset),
12053                        MachinePointerInfo(), false, false, false, 0);
12054   }
12055
12056   // Just load the return address.
12057   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12058   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12059                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12060 }
12061
12062 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12063   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12064   MFI->setFrameAddressIsTaken(true);
12065
12066   EVT VT = Op.getValueType();
12067   SDLoc dl(Op);  // FIXME probably not meaningful
12068   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12069   const X86RegisterInfo *RegInfo =
12070     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12071   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12072   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12073           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12074          "Invalid Frame Register!");
12075   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12076   while (Depth--)
12077     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12078                             MachinePointerInfo(),
12079                             false, false, false, 0);
12080   return FrameAddr;
12081 }
12082
12083 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12084                                                      SelectionDAG &DAG) const {
12085   const X86RegisterInfo *RegInfo =
12086     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12087   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12088 }
12089
12090 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12091   SDValue Chain     = Op.getOperand(0);
12092   SDValue Offset    = Op.getOperand(1);
12093   SDValue Handler   = Op.getOperand(2);
12094   SDLoc dl      (Op);
12095
12096   EVT PtrVT = getPointerTy();
12097   const X86RegisterInfo *RegInfo =
12098     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12099   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12100   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12101           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12102          "Invalid Frame Register!");
12103   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12104   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12105
12106   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12107                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12108   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12109   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12110                        false, false, 0);
12111   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12112
12113   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12114                      DAG.getRegister(StoreAddrReg, PtrVT));
12115 }
12116
12117 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12118                                                SelectionDAG &DAG) const {
12119   SDLoc DL(Op);
12120   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12121                      DAG.getVTList(MVT::i32, MVT::Other),
12122                      Op.getOperand(0), Op.getOperand(1));
12123 }
12124
12125 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12126                                                 SelectionDAG &DAG) const {
12127   SDLoc DL(Op);
12128   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12129                      Op.getOperand(0), Op.getOperand(1));
12130 }
12131
12132 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12133   return Op.getOperand(0);
12134 }
12135
12136 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12137                                                 SelectionDAG &DAG) const {
12138   SDValue Root = Op.getOperand(0);
12139   SDValue Trmp = Op.getOperand(1); // trampoline
12140   SDValue FPtr = Op.getOperand(2); // nested function
12141   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12142   SDLoc dl (Op);
12143
12144   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12145   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12146
12147   if (Subtarget->is64Bit()) {
12148     SDValue OutChains[6];
12149
12150     // Large code-model.
12151     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12152     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12153
12154     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12155     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12156
12157     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12158
12159     // Load the pointer to the nested function into R11.
12160     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12161     SDValue Addr = Trmp;
12162     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12163                                 Addr, MachinePointerInfo(TrmpAddr),
12164                                 false, false, 0);
12165
12166     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12167                        DAG.getConstant(2, MVT::i64));
12168     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12169                                 MachinePointerInfo(TrmpAddr, 2),
12170                                 false, false, 2);
12171
12172     // Load the 'nest' parameter value into R10.
12173     // R10 is specified in X86CallingConv.td
12174     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12175     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12176                        DAG.getConstant(10, MVT::i64));
12177     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12178                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12179                                 false, false, 0);
12180
12181     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12182                        DAG.getConstant(12, MVT::i64));
12183     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12184                                 MachinePointerInfo(TrmpAddr, 12),
12185                                 false, false, 2);
12186
12187     // Jump to the nested function.
12188     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12189     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12190                        DAG.getConstant(20, MVT::i64));
12191     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12192                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12193                                 false, false, 0);
12194
12195     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12196     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12197                        DAG.getConstant(22, MVT::i64));
12198     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12199                                 MachinePointerInfo(TrmpAddr, 22),
12200                                 false, false, 0);
12201
12202     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12203   } else {
12204     const Function *Func =
12205       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12206     CallingConv::ID CC = Func->getCallingConv();
12207     unsigned NestReg;
12208
12209     switch (CC) {
12210     default:
12211       llvm_unreachable("Unsupported calling convention");
12212     case CallingConv::C:
12213     case CallingConv::X86_StdCall: {
12214       // Pass 'nest' parameter in ECX.
12215       // Must be kept in sync with X86CallingConv.td
12216       NestReg = X86::ECX;
12217
12218       // Check that ECX wasn't needed by an 'inreg' parameter.
12219       FunctionType *FTy = Func->getFunctionType();
12220       const AttributeSet &Attrs = Func->getAttributes();
12221
12222       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12223         unsigned InRegCount = 0;
12224         unsigned Idx = 1;
12225
12226         for (FunctionType::param_iterator I = FTy->param_begin(),
12227              E = FTy->param_end(); I != E; ++I, ++Idx)
12228           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12229             // FIXME: should only count parameters that are lowered to integers.
12230             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12231
12232         if (InRegCount > 2) {
12233           report_fatal_error("Nest register in use - reduce number of inreg"
12234                              " parameters!");
12235         }
12236       }
12237       break;
12238     }
12239     case CallingConv::X86_FastCall:
12240     case CallingConv::X86_ThisCall:
12241     case CallingConv::Fast:
12242       // Pass 'nest' parameter in EAX.
12243       // Must be kept in sync with X86CallingConv.td
12244       NestReg = X86::EAX;
12245       break;
12246     }
12247
12248     SDValue OutChains[4];
12249     SDValue Addr, Disp;
12250
12251     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12252                        DAG.getConstant(10, MVT::i32));
12253     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12254
12255     // This is storing the opcode for MOV32ri.
12256     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12257     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12258     OutChains[0] = DAG.getStore(Root, dl,
12259                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12260                                 Trmp, MachinePointerInfo(TrmpAddr),
12261                                 false, false, 0);
12262
12263     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12264                        DAG.getConstant(1, MVT::i32));
12265     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12266                                 MachinePointerInfo(TrmpAddr, 1),
12267                                 false, false, 1);
12268
12269     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12270     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12271                        DAG.getConstant(5, MVT::i32));
12272     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12273                                 MachinePointerInfo(TrmpAddr, 5),
12274                                 false, false, 1);
12275
12276     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12277                        DAG.getConstant(6, MVT::i32));
12278     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12279                                 MachinePointerInfo(TrmpAddr, 6),
12280                                 false, false, 1);
12281
12282     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12283   }
12284 }
12285
12286 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12287                                             SelectionDAG &DAG) const {
12288   /*
12289    The rounding mode is in bits 11:10 of FPSR, and has the following
12290    settings:
12291      00 Round to nearest
12292      01 Round to -inf
12293      10 Round to +inf
12294      11 Round to 0
12295
12296   FLT_ROUNDS, on the other hand, expects the following:
12297     -1 Undefined
12298      0 Round to 0
12299      1 Round to nearest
12300      2 Round to +inf
12301      3 Round to -inf
12302
12303   To perform the conversion, we do:
12304     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12305   */
12306
12307   MachineFunction &MF = DAG.getMachineFunction();
12308   const TargetMachine &TM = MF.getTarget();
12309   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12310   unsigned StackAlignment = TFI.getStackAlignment();
12311   EVT VT = Op.getValueType();
12312   SDLoc DL(Op);
12313
12314   // Save FP Control Word to stack slot
12315   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12316   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12317
12318   MachineMemOperand *MMO =
12319    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12320                            MachineMemOperand::MOStore, 2, 2);
12321
12322   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12323   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12324                                           DAG.getVTList(MVT::Other),
12325                                           Ops, array_lengthof(Ops), MVT::i16,
12326                                           MMO);
12327
12328   // Load FP Control Word from stack slot
12329   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12330                             MachinePointerInfo(), false, false, false, 0);
12331
12332   // Transform as necessary
12333   SDValue CWD1 =
12334     DAG.getNode(ISD::SRL, DL, MVT::i16,
12335                 DAG.getNode(ISD::AND, DL, MVT::i16,
12336                             CWD, DAG.getConstant(0x800, MVT::i16)),
12337                 DAG.getConstant(11, MVT::i8));
12338   SDValue CWD2 =
12339     DAG.getNode(ISD::SRL, DL, MVT::i16,
12340                 DAG.getNode(ISD::AND, DL, MVT::i16,
12341                             CWD, DAG.getConstant(0x400, MVT::i16)),
12342                 DAG.getConstant(9, MVT::i8));
12343
12344   SDValue RetVal =
12345     DAG.getNode(ISD::AND, DL, MVT::i16,
12346                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12347                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12348                             DAG.getConstant(1, MVT::i16)),
12349                 DAG.getConstant(3, MVT::i16));
12350
12351   return DAG.getNode((VT.getSizeInBits() < 16 ?
12352                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12353 }
12354
12355 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12356   EVT VT = Op.getValueType();
12357   EVT OpVT = VT;
12358   unsigned NumBits = VT.getSizeInBits();
12359   SDLoc dl(Op);
12360
12361   Op = Op.getOperand(0);
12362   if (VT == MVT::i8) {
12363     // Zero extend to i32 since there is not an i8 bsr.
12364     OpVT = MVT::i32;
12365     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12366   }
12367
12368   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12369   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12370   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12371
12372   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12373   SDValue Ops[] = {
12374     Op,
12375     DAG.getConstant(NumBits+NumBits-1, OpVT),
12376     DAG.getConstant(X86::COND_E, MVT::i8),
12377     Op.getValue(1)
12378   };
12379   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12380
12381   // Finally xor with NumBits-1.
12382   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12383
12384   if (VT == MVT::i8)
12385     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12386   return Op;
12387 }
12388
12389 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12390   EVT VT = Op.getValueType();
12391   EVT OpVT = VT;
12392   unsigned NumBits = VT.getSizeInBits();
12393   SDLoc dl(Op);
12394
12395   Op = Op.getOperand(0);
12396   if (VT == MVT::i8) {
12397     // Zero extend to i32 since there is not an i8 bsr.
12398     OpVT = MVT::i32;
12399     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12400   }
12401
12402   // Issue a bsr (scan bits in reverse).
12403   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12404   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12405
12406   // And xor with NumBits-1.
12407   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12408
12409   if (VT == MVT::i8)
12410     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12411   return Op;
12412 }
12413
12414 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12415   EVT VT = Op.getValueType();
12416   unsigned NumBits = VT.getSizeInBits();
12417   SDLoc dl(Op);
12418   Op = Op.getOperand(0);
12419
12420   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12421   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12422   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12423
12424   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12425   SDValue Ops[] = {
12426     Op,
12427     DAG.getConstant(NumBits, VT),
12428     DAG.getConstant(X86::COND_E, MVT::i8),
12429     Op.getValue(1)
12430   };
12431   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12432 }
12433
12434 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12435 // ones, and then concatenate the result back.
12436 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12437   EVT VT = Op.getValueType();
12438
12439   assert(VT.is256BitVector() && VT.isInteger() &&
12440          "Unsupported value type for operation");
12441
12442   unsigned NumElems = VT.getVectorNumElements();
12443   SDLoc dl(Op);
12444
12445   // Extract the LHS vectors
12446   SDValue LHS = Op.getOperand(0);
12447   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12448   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12449
12450   // Extract the RHS vectors
12451   SDValue RHS = Op.getOperand(1);
12452   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12453   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12454
12455   MVT EltVT = VT.getVectorElementType().getSimpleVT();
12456   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12457
12458   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12459                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12460                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12461 }
12462
12463 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12464   assert(Op.getValueType().is256BitVector() &&
12465          Op.getValueType().isInteger() &&
12466          "Only handle AVX 256-bit vector integer operation");
12467   return Lower256IntArith(Op, DAG);
12468 }
12469
12470 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12471   assert(Op.getValueType().is256BitVector() &&
12472          Op.getValueType().isInteger() &&
12473          "Only handle AVX 256-bit vector integer operation");
12474   return Lower256IntArith(Op, DAG);
12475 }
12476
12477 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12478                         SelectionDAG &DAG) {
12479   SDLoc dl(Op);
12480   EVT VT = Op.getValueType();
12481
12482   // Decompose 256-bit ops into smaller 128-bit ops.
12483   if (VT.is256BitVector() && !Subtarget->hasInt256())
12484     return Lower256IntArith(Op, DAG);
12485
12486   SDValue A = Op.getOperand(0);
12487   SDValue B = Op.getOperand(1);
12488
12489   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12490   if (VT == MVT::v4i32) {
12491     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12492            "Should not custom lower when pmuldq is available!");
12493
12494     // Extract the odd parts.
12495     static const int UnpackMask[] = { 1, -1, 3, -1 };
12496     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12497     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12498
12499     // Multiply the even parts.
12500     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12501     // Now multiply odd parts.
12502     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12503
12504     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12505     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12506
12507     // Merge the two vectors back together with a shuffle. This expands into 2
12508     // shuffles.
12509     static const int ShufMask[] = { 0, 4, 2, 6 };
12510     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12511   }
12512
12513   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12514          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12515
12516   //  Ahi = psrlqi(a, 32);
12517   //  Bhi = psrlqi(b, 32);
12518   //
12519   //  AloBlo = pmuludq(a, b);
12520   //  AloBhi = pmuludq(a, Bhi);
12521   //  AhiBlo = pmuludq(Ahi, b);
12522
12523   //  AloBhi = psllqi(AloBhi, 32);
12524   //  AhiBlo = psllqi(AhiBlo, 32);
12525   //  return AloBlo + AloBhi + AhiBlo;
12526
12527   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12528   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12529
12530   // Bit cast to 32-bit vectors for MULUDQ
12531   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12532                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12533   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12534   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12535   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12536   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12537
12538   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12539   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12540   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12541
12542   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12543   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12544
12545   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12546   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12547 }
12548
12549 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12550   EVT VT = Op.getValueType();
12551   EVT EltTy = VT.getVectorElementType();
12552   unsigned NumElts = VT.getVectorNumElements();
12553   SDValue N0 = Op.getOperand(0);
12554   SDLoc dl(Op);
12555
12556   // Lower sdiv X, pow2-const.
12557   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12558   if (!C)
12559     return SDValue();
12560
12561   APInt SplatValue, SplatUndef;
12562   unsigned SplatBitSize;
12563   bool HasAnyUndefs;
12564   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12565                           HasAnyUndefs) ||
12566       EltTy.getSizeInBits() < SplatBitSize)
12567     return SDValue();
12568
12569   if ((SplatValue != 0) &&
12570       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12571     unsigned Lg2 = SplatValue.countTrailingZeros();
12572     // Splat the sign bit.
12573     SmallVector<SDValue, 16> Sz(NumElts,
12574                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12575                                                 EltTy));
12576     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12577                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12578                                           NumElts));
12579     // Add (N0 < 0) ? abs2 - 1 : 0;
12580     SmallVector<SDValue, 16> Amt(NumElts,
12581                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12582                                                  EltTy));
12583     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12584                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12585                                           NumElts));
12586     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12587     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12588     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12589                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12590                                           NumElts));
12591
12592     // If we're dividing by a positive value, we're done.  Otherwise, we must
12593     // negate the result.
12594     if (SplatValue.isNonNegative())
12595       return SRA;
12596
12597     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12598     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12599     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12600   }
12601   return SDValue();
12602 }
12603
12604 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12605                                          const X86Subtarget *Subtarget) {
12606   EVT VT = Op.getValueType();
12607   SDLoc dl(Op);
12608   SDValue R = Op.getOperand(0);
12609   SDValue Amt = Op.getOperand(1);
12610
12611   // Optimize shl/srl/sra with constant shift amount.
12612   if (isSplatVector(Amt.getNode())) {
12613     SDValue SclrAmt = Amt->getOperand(0);
12614     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12615       uint64_t ShiftAmt = C->getZExtValue();
12616
12617       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12618           (Subtarget->hasInt256() &&
12619            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12620           (Subtarget->hasAVX512() &&
12621            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12622         if (Op.getOpcode() == ISD::SHL)
12623           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12624                                             DAG);
12625         if (Op.getOpcode() == ISD::SRL)
12626           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12627                                             DAG);
12628         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12629           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12630                                             DAG);
12631       }
12632
12633       if (VT == MVT::v16i8) {
12634         if (Op.getOpcode() == ISD::SHL) {
12635           // Make a large shift.
12636           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12637                                                    MVT::v8i16, R, ShiftAmt,
12638                                                    DAG);
12639           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12640           // Zero out the rightmost bits.
12641           SmallVector<SDValue, 16> V(16,
12642                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12643                                                      MVT::i8));
12644           return DAG.getNode(ISD::AND, dl, VT, SHL,
12645                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12646         }
12647         if (Op.getOpcode() == ISD::SRL) {
12648           // Make a large shift.
12649           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12650                                                    MVT::v8i16, R, ShiftAmt,
12651                                                    DAG);
12652           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12653           // Zero out the leftmost bits.
12654           SmallVector<SDValue, 16> V(16,
12655                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12656                                                      MVT::i8));
12657           return DAG.getNode(ISD::AND, dl, VT, SRL,
12658                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12659         }
12660         if (Op.getOpcode() == ISD::SRA) {
12661           if (ShiftAmt == 7) {
12662             // R s>> 7  ===  R s< 0
12663             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12664             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12665           }
12666
12667           // R s>> a === ((R u>> a) ^ m) - m
12668           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12669           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12670                                                          MVT::i8));
12671           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12672           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12673           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12674           return Res;
12675         }
12676         llvm_unreachable("Unknown shift opcode.");
12677       }
12678
12679       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12680         if (Op.getOpcode() == ISD::SHL) {
12681           // Make a large shift.
12682           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12683                                                    MVT::v16i16, R, ShiftAmt,
12684                                                    DAG);
12685           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12686           // Zero out the rightmost bits.
12687           SmallVector<SDValue, 32> V(32,
12688                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12689                                                      MVT::i8));
12690           return DAG.getNode(ISD::AND, dl, VT, SHL,
12691                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12692         }
12693         if (Op.getOpcode() == ISD::SRL) {
12694           // Make a large shift.
12695           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12696                                                    MVT::v16i16, R, ShiftAmt,
12697                                                    DAG);
12698           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12699           // Zero out the leftmost bits.
12700           SmallVector<SDValue, 32> V(32,
12701                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12702                                                      MVT::i8));
12703           return DAG.getNode(ISD::AND, dl, VT, SRL,
12704                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12705         }
12706         if (Op.getOpcode() == ISD::SRA) {
12707           if (ShiftAmt == 7) {
12708             // R s>> 7  ===  R s< 0
12709             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12710             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12711           }
12712
12713           // R s>> a === ((R u>> a) ^ m) - m
12714           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12715           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12716                                                          MVT::i8));
12717           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12718           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12719           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12720           return Res;
12721         }
12722         llvm_unreachable("Unknown shift opcode.");
12723       }
12724     }
12725   }
12726
12727   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12728   if (!Subtarget->is64Bit() &&
12729       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12730       Amt.getOpcode() == ISD::BITCAST &&
12731       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12732     Amt = Amt.getOperand(0);
12733     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12734                      VT.getVectorNumElements();
12735     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12736     uint64_t ShiftAmt = 0;
12737     for (unsigned i = 0; i != Ratio; ++i) {
12738       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12739       if (C == 0)
12740         return SDValue();
12741       // 6 == Log2(64)
12742       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12743     }
12744     // Check remaining shift amounts.
12745     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12746       uint64_t ShAmt = 0;
12747       for (unsigned j = 0; j != Ratio; ++j) {
12748         ConstantSDNode *C =
12749           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12750         if (C == 0)
12751           return SDValue();
12752         // 6 == Log2(64)
12753         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12754       }
12755       if (ShAmt != ShiftAmt)
12756         return SDValue();
12757     }
12758     switch (Op.getOpcode()) {
12759     default:
12760       llvm_unreachable("Unknown shift opcode!");
12761     case ISD::SHL:
12762       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12763                                         DAG);
12764     case ISD::SRL:
12765       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12766                                         DAG);
12767     case ISD::SRA:
12768       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12769                                         DAG);
12770     }
12771   }
12772
12773   return SDValue();
12774 }
12775
12776 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12777                                         const X86Subtarget* Subtarget) {
12778   EVT VT = Op.getValueType();
12779   SDLoc dl(Op);
12780   SDValue R = Op.getOperand(0);
12781   SDValue Amt = Op.getOperand(1);
12782
12783   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12784       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12785       (Subtarget->hasInt256() &&
12786        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12787         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12788        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12789     SDValue BaseShAmt;
12790     EVT EltVT = VT.getVectorElementType();
12791
12792     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12793       unsigned NumElts = VT.getVectorNumElements();
12794       unsigned i, j;
12795       for (i = 0; i != NumElts; ++i) {
12796         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12797           continue;
12798         break;
12799       }
12800       for (j = i; j != NumElts; ++j) {
12801         SDValue Arg = Amt.getOperand(j);
12802         if (Arg.getOpcode() == ISD::UNDEF) continue;
12803         if (Arg != Amt.getOperand(i))
12804           break;
12805       }
12806       if (i != NumElts && j == NumElts)
12807         BaseShAmt = Amt.getOperand(i);
12808     } else {
12809       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12810         Amt = Amt.getOperand(0);
12811       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12812                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12813         SDValue InVec = Amt.getOperand(0);
12814         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12815           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12816           unsigned i = 0;
12817           for (; i != NumElts; ++i) {
12818             SDValue Arg = InVec.getOperand(i);
12819             if (Arg.getOpcode() == ISD::UNDEF) continue;
12820             BaseShAmt = Arg;
12821             break;
12822           }
12823         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12824            if (ConstantSDNode *C =
12825                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12826              unsigned SplatIdx =
12827                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12828              if (C->getZExtValue() == SplatIdx)
12829                BaseShAmt = InVec.getOperand(1);
12830            }
12831         }
12832         if (BaseShAmt.getNode() == 0)
12833           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12834                                   DAG.getIntPtrConstant(0));
12835       }
12836     }
12837
12838     if (BaseShAmt.getNode()) {
12839       if (EltVT.bitsGT(MVT::i32))
12840         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12841       else if (EltVT.bitsLT(MVT::i32))
12842         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12843
12844       switch (Op.getOpcode()) {
12845       default:
12846         llvm_unreachable("Unknown shift opcode!");
12847       case ISD::SHL:
12848         switch (VT.getSimpleVT().SimpleTy) {
12849         default: return SDValue();
12850         case MVT::v2i64:
12851         case MVT::v4i32:
12852         case MVT::v8i16:
12853         case MVT::v4i64:
12854         case MVT::v8i32:
12855         case MVT::v16i16:
12856         case MVT::v16i32:
12857         case MVT::v8i64:
12858           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12859         }
12860       case ISD::SRA:
12861         switch (VT.getSimpleVT().SimpleTy) {
12862         default: return SDValue();
12863         case MVT::v4i32:
12864         case MVT::v8i16:
12865         case MVT::v8i32:
12866         case MVT::v16i16:
12867         case MVT::v16i32:
12868         case MVT::v8i64:
12869           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12870         }
12871       case ISD::SRL:
12872         switch (VT.getSimpleVT().SimpleTy) {
12873         default: return SDValue();
12874         case MVT::v2i64:
12875         case MVT::v4i32:
12876         case MVT::v8i16:
12877         case MVT::v4i64:
12878         case MVT::v8i32:
12879         case MVT::v16i16:
12880         case MVT::v16i32:
12881         case MVT::v8i64:
12882           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12883         }
12884       }
12885     }
12886   }
12887
12888   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12889   if (!Subtarget->is64Bit() &&
12890       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
12891       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
12892       Amt.getOpcode() == ISD::BITCAST &&
12893       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12894     Amt = Amt.getOperand(0);
12895     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12896                      VT.getVectorNumElements();
12897     std::vector<SDValue> Vals(Ratio);
12898     for (unsigned i = 0; i != Ratio; ++i)
12899       Vals[i] = Amt.getOperand(i);
12900     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12901       for (unsigned j = 0; j != Ratio; ++j)
12902         if (Vals[j] != Amt.getOperand(i + j))
12903           return SDValue();
12904     }
12905     switch (Op.getOpcode()) {
12906     default:
12907       llvm_unreachable("Unknown shift opcode!");
12908     case ISD::SHL:
12909       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12910     case ISD::SRL:
12911       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12912     case ISD::SRA:
12913       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12914     }
12915   }
12916
12917   return SDValue();
12918 }
12919
12920 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
12921                           SelectionDAG &DAG) {
12922
12923   EVT VT = Op.getValueType();
12924   SDLoc dl(Op);
12925   SDValue R = Op.getOperand(0);
12926   SDValue Amt = Op.getOperand(1);
12927   SDValue V;
12928
12929   if (!Subtarget->hasSSE2())
12930     return SDValue();
12931
12932   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12933   if (V.getNode())
12934     return V;
12935
12936   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12937   if (V.getNode())
12938       return V;
12939
12940   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
12941     return Op;
12942   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12943   if (Subtarget->hasInt256()) {
12944     if (Op.getOpcode() == ISD::SRL &&
12945         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12946          VT == MVT::v4i64 || VT == MVT::v8i32))
12947       return Op;
12948     if (Op.getOpcode() == ISD::SHL &&
12949         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12950          VT == MVT::v4i64 || VT == MVT::v8i32))
12951       return Op;
12952     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12953       return Op;
12954   }
12955
12956   // Lower SHL with variable shift amount.
12957   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12958     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12959
12960     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12961     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12962     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12963     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12964   }
12965   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12966     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12967
12968     // a = a << 5;
12969     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12970     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12971
12972     // Turn 'a' into a mask suitable for VSELECT
12973     SDValue VSelM = DAG.getConstant(0x80, VT);
12974     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12975     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12976
12977     SDValue CM1 = DAG.getConstant(0x0f, VT);
12978     SDValue CM2 = DAG.getConstant(0x3f, VT);
12979
12980     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12981     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12982     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
12983     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12984     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12985
12986     // a += a
12987     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12988     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12989     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12990
12991     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12992     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12993     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
12994     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12995     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12996
12997     // a += a
12998     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12999     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13000     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13001
13002     // return VSELECT(r, r+r, a);
13003     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13004                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13005     return R;
13006   }
13007
13008   // Decompose 256-bit shifts into smaller 128-bit shifts.
13009   if (VT.is256BitVector()) {
13010     unsigned NumElems = VT.getVectorNumElements();
13011     MVT EltVT = VT.getVectorElementType().getSimpleVT();
13012     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13013
13014     // Extract the two vectors
13015     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13016     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13017
13018     // Recreate the shift amount vectors
13019     SDValue Amt1, Amt2;
13020     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13021       // Constant shift amount
13022       SmallVector<SDValue, 4> Amt1Csts;
13023       SmallVector<SDValue, 4> Amt2Csts;
13024       for (unsigned i = 0; i != NumElems/2; ++i)
13025         Amt1Csts.push_back(Amt->getOperand(i));
13026       for (unsigned i = NumElems/2; i != NumElems; ++i)
13027         Amt2Csts.push_back(Amt->getOperand(i));
13028
13029       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13030                                  &Amt1Csts[0], NumElems/2);
13031       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13032                                  &Amt2Csts[0], NumElems/2);
13033     } else {
13034       // Variable shift amount
13035       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13036       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13037     }
13038
13039     // Issue new vector shifts for the smaller types
13040     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13041     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13042
13043     // Concatenate the result back
13044     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13045   }
13046
13047   return SDValue();
13048 }
13049
13050 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13051   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13052   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13053   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13054   // has only one use.
13055   SDNode *N = Op.getNode();
13056   SDValue LHS = N->getOperand(0);
13057   SDValue RHS = N->getOperand(1);
13058   unsigned BaseOp = 0;
13059   unsigned Cond = 0;
13060   SDLoc DL(Op);
13061   switch (Op.getOpcode()) {
13062   default: llvm_unreachable("Unknown ovf instruction!");
13063   case ISD::SADDO:
13064     // A subtract of one will be selected as a INC. Note that INC doesn't
13065     // set CF, so we can't do this for UADDO.
13066     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13067       if (C->isOne()) {
13068         BaseOp = X86ISD::INC;
13069         Cond = X86::COND_O;
13070         break;
13071       }
13072     BaseOp = X86ISD::ADD;
13073     Cond = X86::COND_O;
13074     break;
13075   case ISD::UADDO:
13076     BaseOp = X86ISD::ADD;
13077     Cond = X86::COND_B;
13078     break;
13079   case ISD::SSUBO:
13080     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13081     // set CF, so we can't do this for USUBO.
13082     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13083       if (C->isOne()) {
13084         BaseOp = X86ISD::DEC;
13085         Cond = X86::COND_O;
13086         break;
13087       }
13088     BaseOp = X86ISD::SUB;
13089     Cond = X86::COND_O;
13090     break;
13091   case ISD::USUBO:
13092     BaseOp = X86ISD::SUB;
13093     Cond = X86::COND_B;
13094     break;
13095   case ISD::SMULO:
13096     BaseOp = X86ISD::SMUL;
13097     Cond = X86::COND_O;
13098     break;
13099   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13100     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13101                                  MVT::i32);
13102     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13103
13104     SDValue SetCC =
13105       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13106                   DAG.getConstant(X86::COND_O, MVT::i32),
13107                   SDValue(Sum.getNode(), 2));
13108
13109     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13110   }
13111   }
13112
13113   // Also sets EFLAGS.
13114   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13115   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13116
13117   SDValue SetCC =
13118     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13119                 DAG.getConstant(Cond, MVT::i32),
13120                 SDValue(Sum.getNode(), 1));
13121
13122   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13123 }
13124
13125 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13126                                                   SelectionDAG &DAG) const {
13127   SDLoc dl(Op);
13128   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13129   EVT VT = Op.getValueType();
13130
13131   if (!Subtarget->hasSSE2() || !VT.isVector())
13132     return SDValue();
13133
13134   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13135                       ExtraVT.getScalarType().getSizeInBits();
13136
13137   switch (VT.getSimpleVT().SimpleTy) {
13138     default: return SDValue();
13139     case MVT::v8i32:
13140     case MVT::v16i16:
13141       if (!Subtarget->hasFp256())
13142         return SDValue();
13143       if (!Subtarget->hasInt256()) {
13144         // needs to be split
13145         unsigned NumElems = VT.getVectorNumElements();
13146
13147         // Extract the LHS vectors
13148         SDValue LHS = Op.getOperand(0);
13149         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13150         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13151
13152         MVT EltVT = VT.getVectorElementType().getSimpleVT();
13153         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13154
13155         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13156         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13157         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13158                                    ExtraNumElems/2);
13159         SDValue Extra = DAG.getValueType(ExtraVT);
13160
13161         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13162         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13163
13164         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13165       }
13166       // fall through
13167     case MVT::v4i32:
13168     case MVT::v8i16: {
13169       // (sext (vzext x)) -> (vsext x)
13170       SDValue Op0 = Op.getOperand(0);
13171       SDValue Op00 = Op0.getOperand(0);
13172       SDValue Tmp1;
13173       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13174       if (Op0.getOpcode() == ISD::BITCAST &&
13175           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
13176         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13177       if (Tmp1.getNode()) {
13178         SDValue Tmp1Op0 = Tmp1.getOperand(0);
13179         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13180                "This optimization is invalid without a VZEXT.");
13181         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13182       }
13183
13184       // If the above didn't work, then just use Shift-Left + Shift-Right.
13185       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13186                                         DAG);
13187       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13188                                         DAG);
13189     }
13190   }
13191 }
13192
13193 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13194                                  SelectionDAG &DAG) {
13195   SDLoc dl(Op);
13196   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13197     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13198   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13199     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13200
13201   // The only fence that needs an instruction is a sequentially-consistent
13202   // cross-thread fence.
13203   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13204     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13205     // no-sse2). There isn't any reason to disable it if the target processor
13206     // supports it.
13207     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13208       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13209
13210     SDValue Chain = Op.getOperand(0);
13211     SDValue Zero = DAG.getConstant(0, MVT::i32);
13212     SDValue Ops[] = {
13213       DAG.getRegister(X86::ESP, MVT::i32), // Base
13214       DAG.getTargetConstant(1, MVT::i8),   // Scale
13215       DAG.getRegister(0, MVT::i32),        // Index
13216       DAG.getTargetConstant(0, MVT::i32),  // Disp
13217       DAG.getRegister(0, MVT::i32),        // Segment.
13218       Zero,
13219       Chain
13220     };
13221     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13222     return SDValue(Res, 0);
13223   }
13224
13225   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13226   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13227 }
13228
13229 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13230                              SelectionDAG &DAG) {
13231   EVT T = Op.getValueType();
13232   SDLoc DL(Op);
13233   unsigned Reg = 0;
13234   unsigned size = 0;
13235   switch(T.getSimpleVT().SimpleTy) {
13236   default: llvm_unreachable("Invalid value type!");
13237   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13238   case MVT::i16: Reg = X86::AX;  size = 2; break;
13239   case MVT::i32: Reg = X86::EAX; size = 4; break;
13240   case MVT::i64:
13241     assert(Subtarget->is64Bit() && "Node not type legal!");
13242     Reg = X86::RAX; size = 8;
13243     break;
13244   }
13245   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13246                                     Op.getOperand(2), SDValue());
13247   SDValue Ops[] = { cpIn.getValue(0),
13248                     Op.getOperand(1),
13249                     Op.getOperand(3),
13250                     DAG.getTargetConstant(size, MVT::i8),
13251                     cpIn.getValue(1) };
13252   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13253   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13254   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13255                                            Ops, array_lengthof(Ops), T, MMO);
13256   SDValue cpOut =
13257     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13258   return cpOut;
13259 }
13260
13261 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13262                                      SelectionDAG &DAG) {
13263   assert(Subtarget->is64Bit() && "Result not type legalized?");
13264   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13265   SDValue TheChain = Op.getOperand(0);
13266   SDLoc dl(Op);
13267   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13268   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13269   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13270                                    rax.getValue(2));
13271   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13272                             DAG.getConstant(32, MVT::i8));
13273   SDValue Ops[] = {
13274     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13275     rdx.getValue(1)
13276   };
13277   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13278 }
13279
13280 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13281                             SelectionDAG &DAG) {
13282   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13283   MVT DstVT = Op.getSimpleValueType();
13284   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13285          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13286   assert((DstVT == MVT::i64 ||
13287           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13288          "Unexpected custom BITCAST");
13289   // i64 <=> MMX conversions are Legal.
13290   if (SrcVT==MVT::i64 && DstVT.isVector())
13291     return Op;
13292   if (DstVT==MVT::i64 && SrcVT.isVector())
13293     return Op;
13294   // MMX <=> MMX conversions are Legal.
13295   if (SrcVT.isVector() && DstVT.isVector())
13296     return Op;
13297   // All other conversions need to be expanded.
13298   return SDValue();
13299 }
13300
13301 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13302   SDNode *Node = Op.getNode();
13303   SDLoc dl(Node);
13304   EVT T = Node->getValueType(0);
13305   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13306                               DAG.getConstant(0, T), Node->getOperand(2));
13307   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13308                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13309                        Node->getOperand(0),
13310                        Node->getOperand(1), negOp,
13311                        cast<AtomicSDNode>(Node)->getSrcValue(),
13312                        cast<AtomicSDNode>(Node)->getAlignment(),
13313                        cast<AtomicSDNode>(Node)->getOrdering(),
13314                        cast<AtomicSDNode>(Node)->getSynchScope());
13315 }
13316
13317 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13318   SDNode *Node = Op.getNode();
13319   SDLoc dl(Node);
13320   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13321
13322   // Convert seq_cst store -> xchg
13323   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13324   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13325   //        (The only way to get a 16-byte store is cmpxchg16b)
13326   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13327   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13328       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13329     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13330                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13331                                  Node->getOperand(0),
13332                                  Node->getOperand(1), Node->getOperand(2),
13333                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13334                                  cast<AtomicSDNode>(Node)->getOrdering(),
13335                                  cast<AtomicSDNode>(Node)->getSynchScope());
13336     return Swap.getValue(1);
13337   }
13338   // Other atomic stores have a simple pattern.
13339   return Op;
13340 }
13341
13342 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13343   EVT VT = Op.getNode()->getValueType(0);
13344
13345   // Let legalize expand this if it isn't a legal type yet.
13346   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13347     return SDValue();
13348
13349   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13350
13351   unsigned Opc;
13352   bool ExtraOp = false;
13353   switch (Op.getOpcode()) {
13354   default: llvm_unreachable("Invalid code");
13355   case ISD::ADDC: Opc = X86ISD::ADD; break;
13356   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13357   case ISD::SUBC: Opc = X86ISD::SUB; break;
13358   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13359   }
13360
13361   if (!ExtraOp)
13362     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13363                        Op.getOperand(1));
13364   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13365                      Op.getOperand(1), Op.getOperand(2));
13366 }
13367
13368 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13369                             SelectionDAG &DAG) {
13370   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13371
13372   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13373   // which returns the values as { float, float } (in XMM0) or
13374   // { double, double } (which is returned in XMM0, XMM1).
13375   SDLoc dl(Op);
13376   SDValue Arg = Op.getOperand(0);
13377   EVT ArgVT = Arg.getValueType();
13378   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13379
13380   TargetLowering::ArgListTy Args;
13381   TargetLowering::ArgListEntry Entry;
13382
13383   Entry.Node = Arg;
13384   Entry.Ty = ArgTy;
13385   Entry.isSExt = false;
13386   Entry.isZExt = false;
13387   Args.push_back(Entry);
13388
13389   bool isF64 = ArgVT == MVT::f64;
13390   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13391   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13392   // the results are returned via SRet in memory.
13393   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13395   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13396
13397   Type *RetTy = isF64
13398     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13399     : (Type*)VectorType::get(ArgTy, 4);
13400   TargetLowering::
13401     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13402                          false, false, false, false, 0,
13403                          CallingConv::C, /*isTaillCall=*/false,
13404                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13405                          Callee, Args, DAG, dl);
13406   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13407
13408   if (isF64)
13409     // Returned in xmm0 and xmm1.
13410     return CallResult.first;
13411
13412   // Returned in bits 0:31 and 32:64 xmm0.
13413   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13414                                CallResult.first, DAG.getIntPtrConstant(0));
13415   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13416                                CallResult.first, DAG.getIntPtrConstant(1));
13417   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13418   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13419 }
13420
13421 /// LowerOperation - Provide custom lowering hooks for some operations.
13422 ///
13423 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13424   switch (Op.getOpcode()) {
13425   default: llvm_unreachable("Should not custom lower this!");
13426   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13427   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13428   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13429   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13430   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13431   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13432   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13433   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13434   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13435   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13436   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13437   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13438   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13439   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13440   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13441   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13442   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13443   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13444   case ISD::SHL_PARTS:
13445   case ISD::SRA_PARTS:
13446   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13447   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13448   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13449   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13450   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13451   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13452   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13453   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13454   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13455   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13456   case ISD::FABS:               return LowerFABS(Op, DAG);
13457   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13458   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13459   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13460   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13461   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13462   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13463   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13464   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13465   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13466   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13467   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13468   case ISD::INTRINSIC_VOID:
13469   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13470   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13471   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13472   case ISD::FRAME_TO_ARGS_OFFSET:
13473                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13474   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13475   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13476   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13477   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13478   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13479   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13480   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13481   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13482   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13483   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13484   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13485   case ISD::SRA:
13486   case ISD::SRL:
13487   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13488   case ISD::SADDO:
13489   case ISD::UADDO:
13490   case ISD::SSUBO:
13491   case ISD::USUBO:
13492   case ISD::SMULO:
13493   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13494   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13495   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13496   case ISD::ADDC:
13497   case ISD::ADDE:
13498   case ISD::SUBC:
13499   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13500   case ISD::ADD:                return LowerADD(Op, DAG);
13501   case ISD::SUB:                return LowerSUB(Op, DAG);
13502   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13503   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13504   }
13505 }
13506
13507 static void ReplaceATOMIC_LOAD(SDNode *Node,
13508                                   SmallVectorImpl<SDValue> &Results,
13509                                   SelectionDAG &DAG) {
13510   SDLoc dl(Node);
13511   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13512
13513   // Convert wide load -> cmpxchg8b/cmpxchg16b
13514   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13515   //        (The only way to get a 16-byte load is cmpxchg16b)
13516   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13517   SDValue Zero = DAG.getConstant(0, VT);
13518   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13519                                Node->getOperand(0),
13520                                Node->getOperand(1), Zero, Zero,
13521                                cast<AtomicSDNode>(Node)->getMemOperand(),
13522                                cast<AtomicSDNode>(Node)->getOrdering(),
13523                                cast<AtomicSDNode>(Node)->getSynchScope());
13524   Results.push_back(Swap.getValue(0));
13525   Results.push_back(Swap.getValue(1));
13526 }
13527
13528 static void
13529 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13530                         SelectionDAG &DAG, unsigned NewOp) {
13531   SDLoc dl(Node);
13532   assert (Node->getValueType(0) == MVT::i64 &&
13533           "Only know how to expand i64 atomics");
13534
13535   SDValue Chain = Node->getOperand(0);
13536   SDValue In1 = Node->getOperand(1);
13537   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13538                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13539   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13540                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13541   SDValue Ops[] = { Chain, In1, In2L, In2H };
13542   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13543   SDValue Result =
13544     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13545                             cast<MemSDNode>(Node)->getMemOperand());
13546   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13547   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13548   Results.push_back(Result.getValue(2));
13549 }
13550
13551 /// ReplaceNodeResults - Replace a node with an illegal result type
13552 /// with a new node built out of custom code.
13553 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13554                                            SmallVectorImpl<SDValue>&Results,
13555                                            SelectionDAG &DAG) const {
13556   SDLoc dl(N);
13557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13558   switch (N->getOpcode()) {
13559   default:
13560     llvm_unreachable("Do not know how to custom type legalize this operation!");
13561   case ISD::SIGN_EXTEND_INREG:
13562   case ISD::ADDC:
13563   case ISD::ADDE:
13564   case ISD::SUBC:
13565   case ISD::SUBE:
13566     // We don't want to expand or promote these.
13567     return;
13568   case ISD::FP_TO_SINT:
13569   case ISD::FP_TO_UINT: {
13570     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13571
13572     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13573       return;
13574
13575     std::pair<SDValue,SDValue> Vals =
13576         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13577     SDValue FIST = Vals.first, StackSlot = Vals.second;
13578     if (FIST.getNode() != 0) {
13579       EVT VT = N->getValueType(0);
13580       // Return a load from the stack slot.
13581       if (StackSlot.getNode() != 0)
13582         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13583                                       MachinePointerInfo(),
13584                                       false, false, false, 0));
13585       else
13586         Results.push_back(FIST);
13587     }
13588     return;
13589   }
13590   case ISD::UINT_TO_FP: {
13591     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13592     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13593         N->getValueType(0) != MVT::v2f32)
13594       return;
13595     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13596                                  N->getOperand(0));
13597     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13598                                      MVT::f64);
13599     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13600     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13601                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13602     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13603     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13604     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13605     return;
13606   }
13607   case ISD::FP_ROUND: {
13608     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13609         return;
13610     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13611     Results.push_back(V);
13612     return;
13613   }
13614   case ISD::READCYCLECOUNTER: {
13615     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13616     SDValue TheChain = N->getOperand(0);
13617     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13618     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13619                                      rd.getValue(1));
13620     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13621                                      eax.getValue(2));
13622     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13623     SDValue Ops[] = { eax, edx };
13624     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13625                                   array_lengthof(Ops)));
13626     Results.push_back(edx.getValue(1));
13627     return;
13628   }
13629   case ISD::ATOMIC_CMP_SWAP: {
13630     EVT T = N->getValueType(0);
13631     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13632     bool Regs64bit = T == MVT::i128;
13633     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13634     SDValue cpInL, cpInH;
13635     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13636                         DAG.getConstant(0, HalfT));
13637     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13638                         DAG.getConstant(1, HalfT));
13639     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13640                              Regs64bit ? X86::RAX : X86::EAX,
13641                              cpInL, SDValue());
13642     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13643                              Regs64bit ? X86::RDX : X86::EDX,
13644                              cpInH, cpInL.getValue(1));
13645     SDValue swapInL, swapInH;
13646     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13647                           DAG.getConstant(0, HalfT));
13648     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13649                           DAG.getConstant(1, HalfT));
13650     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13651                                Regs64bit ? X86::RBX : X86::EBX,
13652                                swapInL, cpInH.getValue(1));
13653     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13654                                Regs64bit ? X86::RCX : X86::ECX,
13655                                swapInH, swapInL.getValue(1));
13656     SDValue Ops[] = { swapInH.getValue(0),
13657                       N->getOperand(1),
13658                       swapInH.getValue(1) };
13659     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13660     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13661     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13662                                   X86ISD::LCMPXCHG8_DAG;
13663     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13664                                              Ops, array_lengthof(Ops), T, MMO);
13665     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13666                                         Regs64bit ? X86::RAX : X86::EAX,
13667                                         HalfT, Result.getValue(1));
13668     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13669                                         Regs64bit ? X86::RDX : X86::EDX,
13670                                         HalfT, cpOutL.getValue(2));
13671     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13672     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13673     Results.push_back(cpOutH.getValue(1));
13674     return;
13675   }
13676   case ISD::ATOMIC_LOAD_ADD:
13677   case ISD::ATOMIC_LOAD_AND:
13678   case ISD::ATOMIC_LOAD_NAND:
13679   case ISD::ATOMIC_LOAD_OR:
13680   case ISD::ATOMIC_LOAD_SUB:
13681   case ISD::ATOMIC_LOAD_XOR:
13682   case ISD::ATOMIC_LOAD_MAX:
13683   case ISD::ATOMIC_LOAD_MIN:
13684   case ISD::ATOMIC_LOAD_UMAX:
13685   case ISD::ATOMIC_LOAD_UMIN:
13686   case ISD::ATOMIC_SWAP: {
13687     unsigned Opc;
13688     switch (N->getOpcode()) {
13689     default: llvm_unreachable("Unexpected opcode");
13690     case ISD::ATOMIC_LOAD_ADD:
13691       Opc = X86ISD::ATOMADD64_DAG;
13692       break;
13693     case ISD::ATOMIC_LOAD_AND:
13694       Opc = X86ISD::ATOMAND64_DAG;
13695       break;
13696     case ISD::ATOMIC_LOAD_NAND:
13697       Opc = X86ISD::ATOMNAND64_DAG;
13698       break;
13699     case ISD::ATOMIC_LOAD_OR:
13700       Opc = X86ISD::ATOMOR64_DAG;
13701       break;
13702     case ISD::ATOMIC_LOAD_SUB:
13703       Opc = X86ISD::ATOMSUB64_DAG;
13704       break;
13705     case ISD::ATOMIC_LOAD_XOR:
13706       Opc = X86ISD::ATOMXOR64_DAG;
13707       break;
13708     case ISD::ATOMIC_LOAD_MAX:
13709       Opc = X86ISD::ATOMMAX64_DAG;
13710       break;
13711     case ISD::ATOMIC_LOAD_MIN:
13712       Opc = X86ISD::ATOMMIN64_DAG;
13713       break;
13714     case ISD::ATOMIC_LOAD_UMAX:
13715       Opc = X86ISD::ATOMUMAX64_DAG;
13716       break;
13717     case ISD::ATOMIC_LOAD_UMIN:
13718       Opc = X86ISD::ATOMUMIN64_DAG;
13719       break;
13720     case ISD::ATOMIC_SWAP:
13721       Opc = X86ISD::ATOMSWAP64_DAG;
13722       break;
13723     }
13724     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13725     return;
13726   }
13727   case ISD::ATOMIC_LOAD:
13728     ReplaceATOMIC_LOAD(N, Results, DAG);
13729   }
13730 }
13731
13732 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13733   switch (Opcode) {
13734   default: return NULL;
13735   case X86ISD::BSF:                return "X86ISD::BSF";
13736   case X86ISD::BSR:                return "X86ISD::BSR";
13737   case X86ISD::SHLD:               return "X86ISD::SHLD";
13738   case X86ISD::SHRD:               return "X86ISD::SHRD";
13739   case X86ISD::FAND:               return "X86ISD::FAND";
13740   case X86ISD::FANDN:              return "X86ISD::FANDN";
13741   case X86ISD::FOR:                return "X86ISD::FOR";
13742   case X86ISD::FXOR:               return "X86ISD::FXOR";
13743   case X86ISD::FSRL:               return "X86ISD::FSRL";
13744   case X86ISD::FILD:               return "X86ISD::FILD";
13745   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13746   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13747   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13748   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13749   case X86ISD::FLD:                return "X86ISD::FLD";
13750   case X86ISD::FST:                return "X86ISD::FST";
13751   case X86ISD::CALL:               return "X86ISD::CALL";
13752   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13753   case X86ISD::BT:                 return "X86ISD::BT";
13754   case X86ISD::CMP:                return "X86ISD::CMP";
13755   case X86ISD::COMI:               return "X86ISD::COMI";
13756   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13757   case X86ISD::CMPM:               return "X86ISD::CMPM";
13758   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13759   case X86ISD::SETCC:              return "X86ISD::SETCC";
13760   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13761   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13762   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13763   case X86ISD::CMOV:               return "X86ISD::CMOV";
13764   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13765   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13766   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13767   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13768   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13769   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13770   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13771   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13772   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13773   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13774   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13775   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13776   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13777   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13778   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13779   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13780   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13781   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13782   case X86ISD::HADD:               return "X86ISD::HADD";
13783   case X86ISD::HSUB:               return "X86ISD::HSUB";
13784   case X86ISD::FHADD:              return "X86ISD::FHADD";
13785   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13786   case X86ISD::UMAX:               return "X86ISD::UMAX";
13787   case X86ISD::UMIN:               return "X86ISD::UMIN";
13788   case X86ISD::SMAX:               return "X86ISD::SMAX";
13789   case X86ISD::SMIN:               return "X86ISD::SMIN";
13790   case X86ISD::FMAX:               return "X86ISD::FMAX";
13791   case X86ISD::FMIN:               return "X86ISD::FMIN";
13792   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13793   case X86ISD::FMINC:              return "X86ISD::FMINC";
13794   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13795   case X86ISD::FRCP:               return "X86ISD::FRCP";
13796   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13797   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13798   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13799   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13800   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13801   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13802   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13803   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13804   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13805   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13806   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13807   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13808   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13809   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13810   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13811   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13812   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13813   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13814   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13815   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13816   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13817   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13818   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
13819   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
13820   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
13821   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13822   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13823   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13824   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13825   case X86ISD::VSHL:               return "X86ISD::VSHL";
13826   case X86ISD::VSRL:               return "X86ISD::VSRL";
13827   case X86ISD::VSRA:               return "X86ISD::VSRA";
13828   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13829   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13830   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13831   case X86ISD::CMPP:               return "X86ISD::CMPP";
13832   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13833   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13834   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13835   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13836   case X86ISD::ADD:                return "X86ISD::ADD";
13837   case X86ISD::SUB:                return "X86ISD::SUB";
13838   case X86ISD::ADC:                return "X86ISD::ADC";
13839   case X86ISD::SBB:                return "X86ISD::SBB";
13840   case X86ISD::SMUL:               return "X86ISD::SMUL";
13841   case X86ISD::UMUL:               return "X86ISD::UMUL";
13842   case X86ISD::INC:                return "X86ISD::INC";
13843   case X86ISD::DEC:                return "X86ISD::DEC";
13844   case X86ISD::OR:                 return "X86ISD::OR";
13845   case X86ISD::XOR:                return "X86ISD::XOR";
13846   case X86ISD::AND:                return "X86ISD::AND";
13847   case X86ISD::BLSI:               return "X86ISD::BLSI";
13848   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13849   case X86ISD::BLSR:               return "X86ISD::BLSR";
13850   case X86ISD::BZHI:               return "X86ISD::BZHI";
13851   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
13852   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13853   case X86ISD::PTEST:              return "X86ISD::PTEST";
13854   case X86ISD::TESTP:              return "X86ISD::TESTP";
13855   case X86ISD::TESTM:              return "X86ISD::TESTM";
13856   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
13857   case X86ISD::KTEST:              return "X86ISD::KTEST";
13858   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13859   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13860   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13861   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13862   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13863   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13864   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13865   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13866   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13867   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13868   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13869   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13870   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13871   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13872   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13873   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13874   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13875   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13876   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
13877   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13878   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13879   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13880   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
13881   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13882   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13883   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13884   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13885   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13886   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13887   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13888   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13889   case X86ISD::SAHF:               return "X86ISD::SAHF";
13890   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13891   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13892   case X86ISD::FMADD:              return "X86ISD::FMADD";
13893   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13894   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13895   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13896   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13897   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13898   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13899   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13900   case X86ISD::XTEST:              return "X86ISD::XTEST";
13901   }
13902 }
13903
13904 // isLegalAddressingMode - Return true if the addressing mode represented
13905 // by AM is legal for this target, for a load/store of the specified type.
13906 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13907                                               Type *Ty) const {
13908   // X86 supports extremely general addressing modes.
13909   CodeModel::Model M = getTargetMachine().getCodeModel();
13910   Reloc::Model R = getTargetMachine().getRelocationModel();
13911
13912   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13913   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13914     return false;
13915
13916   if (AM.BaseGV) {
13917     unsigned GVFlags =
13918       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13919
13920     // If a reference to this global requires an extra load, we can't fold it.
13921     if (isGlobalStubReference(GVFlags))
13922       return false;
13923
13924     // If BaseGV requires a register for the PIC base, we cannot also have a
13925     // BaseReg specified.
13926     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13927       return false;
13928
13929     // If lower 4G is not available, then we must use rip-relative addressing.
13930     if ((M != CodeModel::Small || R != Reloc::Static) &&
13931         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13932       return false;
13933   }
13934
13935   switch (AM.Scale) {
13936   case 0:
13937   case 1:
13938   case 2:
13939   case 4:
13940   case 8:
13941     // These scales always work.
13942     break;
13943   case 3:
13944   case 5:
13945   case 9:
13946     // These scales are formed with basereg+scalereg.  Only accept if there is
13947     // no basereg yet.
13948     if (AM.HasBaseReg)
13949       return false;
13950     break;
13951   default:  // Other stuff never works.
13952     return false;
13953   }
13954
13955   return true;
13956 }
13957
13958 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13959   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13960     return false;
13961   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13962   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13963   return NumBits1 > NumBits2;
13964 }
13965
13966 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13967   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13968     return false;
13969
13970   if (!isTypeLegal(EVT::getEVT(Ty1)))
13971     return false;
13972
13973   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13974
13975   // Assuming the caller doesn't have a zeroext or signext return parameter,
13976   // truncation all the way down to i1 is valid.
13977   return true;
13978 }
13979
13980 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13981   return isInt<32>(Imm);
13982 }
13983
13984 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13985   // Can also use sub to handle negated immediates.
13986   return isInt<32>(Imm);
13987 }
13988
13989 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13990   if (!VT1.isInteger() || !VT2.isInteger())
13991     return false;
13992   unsigned NumBits1 = VT1.getSizeInBits();
13993   unsigned NumBits2 = VT2.getSizeInBits();
13994   return NumBits1 > NumBits2;
13995 }
13996
13997 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13998   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13999   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14000 }
14001
14002 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14003   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14004   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14005 }
14006
14007 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14008   EVT VT1 = Val.getValueType();
14009   if (isZExtFree(VT1, VT2))
14010     return true;
14011
14012   if (Val.getOpcode() != ISD::LOAD)
14013     return false;
14014
14015   if (!VT1.isSimple() || !VT1.isInteger() ||
14016       !VT2.isSimple() || !VT2.isInteger())
14017     return false;
14018
14019   switch (VT1.getSimpleVT().SimpleTy) {
14020   default: break;
14021   case MVT::i8:
14022   case MVT::i16:
14023   case MVT::i32:
14024     // X86 has 8, 16, and 32-bit zero-extending loads.
14025     return true;
14026   }
14027
14028   return false;
14029 }
14030
14031 bool
14032 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14033   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14034     return false;
14035
14036   VT = VT.getScalarType();
14037
14038   if (!VT.isSimple())
14039     return false;
14040
14041   switch (VT.getSimpleVT().SimpleTy) {
14042   case MVT::f32:
14043   case MVT::f64:
14044     return true;
14045   default:
14046     break;
14047   }
14048
14049   return false;
14050 }
14051
14052 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14053   // i16 instructions are longer (0x66 prefix) and potentially slower.
14054   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14055 }
14056
14057 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14058 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14059 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14060 /// are assumed to be legal.
14061 bool
14062 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14063                                       EVT VT) const {
14064   if (!VT.isSimple())
14065     return false;
14066
14067   MVT SVT = VT.getSimpleVT();
14068
14069   // Very little shuffling can be done for 64-bit vectors right now.
14070   if (VT.getSizeInBits() == 64)
14071     return false;
14072
14073   // FIXME: pshufb, blends, shifts.
14074   return (SVT.getVectorNumElements() == 2 ||
14075           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14076           isMOVLMask(M, SVT) ||
14077           isSHUFPMask(M, SVT) ||
14078           isPSHUFDMask(M, SVT) ||
14079           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14080           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14081           isPALIGNRMask(M, SVT, Subtarget) ||
14082           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14083           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14084           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14085           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14086 }
14087
14088 bool
14089 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14090                                           EVT VT) const {
14091   if (!VT.isSimple())
14092     return false;
14093
14094   MVT SVT = VT.getSimpleVT();
14095   unsigned NumElts = SVT.getVectorNumElements();
14096   // FIXME: This collection of masks seems suspect.
14097   if (NumElts == 2)
14098     return true;
14099   if (NumElts == 4 && SVT.is128BitVector()) {
14100     return (isMOVLMask(Mask, SVT)  ||
14101             isCommutedMOVLMask(Mask, SVT, true) ||
14102             isSHUFPMask(Mask, SVT) ||
14103             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14104   }
14105   return false;
14106 }
14107
14108 //===----------------------------------------------------------------------===//
14109 //                           X86 Scheduler Hooks
14110 //===----------------------------------------------------------------------===//
14111
14112 /// Utility function to emit xbegin specifying the start of an RTM region.
14113 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14114                                      const TargetInstrInfo *TII) {
14115   DebugLoc DL = MI->getDebugLoc();
14116
14117   const BasicBlock *BB = MBB->getBasicBlock();
14118   MachineFunction::iterator I = MBB;
14119   ++I;
14120
14121   // For the v = xbegin(), we generate
14122   //
14123   // thisMBB:
14124   //  xbegin sinkMBB
14125   //
14126   // mainMBB:
14127   //  eax = -1
14128   //
14129   // sinkMBB:
14130   //  v = eax
14131
14132   MachineBasicBlock *thisMBB = MBB;
14133   MachineFunction *MF = MBB->getParent();
14134   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14135   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14136   MF->insert(I, mainMBB);
14137   MF->insert(I, sinkMBB);
14138
14139   // Transfer the remainder of BB and its successor edges to sinkMBB.
14140   sinkMBB->splice(sinkMBB->begin(), MBB,
14141                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14142   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14143
14144   // thisMBB:
14145   //  xbegin sinkMBB
14146   //  # fallthrough to mainMBB
14147   //  # abortion to sinkMBB
14148   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14149   thisMBB->addSuccessor(mainMBB);
14150   thisMBB->addSuccessor(sinkMBB);
14151
14152   // mainMBB:
14153   //  EAX = -1
14154   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14155   mainMBB->addSuccessor(sinkMBB);
14156
14157   // sinkMBB:
14158   // EAX is live into the sinkMBB
14159   sinkMBB->addLiveIn(X86::EAX);
14160   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14161           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14162     .addReg(X86::EAX);
14163
14164   MI->eraseFromParent();
14165   return sinkMBB;
14166 }
14167
14168 // Get CMPXCHG opcode for the specified data type.
14169 static unsigned getCmpXChgOpcode(EVT VT) {
14170   switch (VT.getSimpleVT().SimpleTy) {
14171   case MVT::i8:  return X86::LCMPXCHG8;
14172   case MVT::i16: return X86::LCMPXCHG16;
14173   case MVT::i32: return X86::LCMPXCHG32;
14174   case MVT::i64: return X86::LCMPXCHG64;
14175   default:
14176     break;
14177   }
14178   llvm_unreachable("Invalid operand size!");
14179 }
14180
14181 // Get LOAD opcode for the specified data type.
14182 static unsigned getLoadOpcode(EVT VT) {
14183   switch (VT.getSimpleVT().SimpleTy) {
14184   case MVT::i8:  return X86::MOV8rm;
14185   case MVT::i16: return X86::MOV16rm;
14186   case MVT::i32: return X86::MOV32rm;
14187   case MVT::i64: return X86::MOV64rm;
14188   default:
14189     break;
14190   }
14191   llvm_unreachable("Invalid operand size!");
14192 }
14193
14194 // Get opcode of the non-atomic one from the specified atomic instruction.
14195 static unsigned getNonAtomicOpcode(unsigned Opc) {
14196   switch (Opc) {
14197   case X86::ATOMAND8:  return X86::AND8rr;
14198   case X86::ATOMAND16: return X86::AND16rr;
14199   case X86::ATOMAND32: return X86::AND32rr;
14200   case X86::ATOMAND64: return X86::AND64rr;
14201   case X86::ATOMOR8:   return X86::OR8rr;
14202   case X86::ATOMOR16:  return X86::OR16rr;
14203   case X86::ATOMOR32:  return X86::OR32rr;
14204   case X86::ATOMOR64:  return X86::OR64rr;
14205   case X86::ATOMXOR8:  return X86::XOR8rr;
14206   case X86::ATOMXOR16: return X86::XOR16rr;
14207   case X86::ATOMXOR32: return X86::XOR32rr;
14208   case X86::ATOMXOR64: return X86::XOR64rr;
14209   }
14210   llvm_unreachable("Unhandled atomic-load-op opcode!");
14211 }
14212
14213 // Get opcode of the non-atomic one from the specified atomic instruction with
14214 // extra opcode.
14215 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14216                                                unsigned &ExtraOpc) {
14217   switch (Opc) {
14218   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14219   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14220   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14221   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14222   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14223   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14224   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14225   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14226   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14227   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14228   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14229   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14230   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14231   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14232   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14233   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14234   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14235   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14236   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14237   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14238   }
14239   llvm_unreachable("Unhandled atomic-load-op opcode!");
14240 }
14241
14242 // Get opcode of the non-atomic one from the specified atomic instruction for
14243 // 64-bit data type on 32-bit target.
14244 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14245   switch (Opc) {
14246   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14247   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14248   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14249   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14250   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14251   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14252   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14253   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14254   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14255   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14256   }
14257   llvm_unreachable("Unhandled atomic-load-op opcode!");
14258 }
14259
14260 // Get opcode of the non-atomic one from the specified atomic instruction for
14261 // 64-bit data type on 32-bit target with extra opcode.
14262 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14263                                                    unsigned &HiOpc,
14264                                                    unsigned &ExtraOpc) {
14265   switch (Opc) {
14266   case X86::ATOMNAND6432:
14267     ExtraOpc = X86::NOT32r;
14268     HiOpc = X86::AND32rr;
14269     return X86::AND32rr;
14270   }
14271   llvm_unreachable("Unhandled atomic-load-op opcode!");
14272 }
14273
14274 // Get pseudo CMOV opcode from the specified data type.
14275 static unsigned getPseudoCMOVOpc(EVT VT) {
14276   switch (VT.getSimpleVT().SimpleTy) {
14277   case MVT::i8:  return X86::CMOV_GR8;
14278   case MVT::i16: return X86::CMOV_GR16;
14279   case MVT::i32: return X86::CMOV_GR32;
14280   default:
14281     break;
14282   }
14283   llvm_unreachable("Unknown CMOV opcode!");
14284 }
14285
14286 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14287 // They will be translated into a spin-loop or compare-exchange loop from
14288 //
14289 //    ...
14290 //    dst = atomic-fetch-op MI.addr, MI.val
14291 //    ...
14292 //
14293 // to
14294 //
14295 //    ...
14296 //    t1 = LOAD MI.addr
14297 // loop:
14298 //    t4 = phi(t1, t3 / loop)
14299 //    t2 = OP MI.val, t4
14300 //    EAX = t4
14301 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14302 //    t3 = EAX
14303 //    JNE loop
14304 // sink:
14305 //    dst = t3
14306 //    ...
14307 MachineBasicBlock *
14308 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14309                                        MachineBasicBlock *MBB) const {
14310   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14311   DebugLoc DL = MI->getDebugLoc();
14312
14313   MachineFunction *MF = MBB->getParent();
14314   MachineRegisterInfo &MRI = MF->getRegInfo();
14315
14316   const BasicBlock *BB = MBB->getBasicBlock();
14317   MachineFunction::iterator I = MBB;
14318   ++I;
14319
14320   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14321          "Unexpected number of operands");
14322
14323   assert(MI->hasOneMemOperand() &&
14324          "Expected atomic-load-op to have one memoperand");
14325
14326   // Memory Reference
14327   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14328   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14329
14330   unsigned DstReg, SrcReg;
14331   unsigned MemOpndSlot;
14332
14333   unsigned CurOp = 0;
14334
14335   DstReg = MI->getOperand(CurOp++).getReg();
14336   MemOpndSlot = CurOp;
14337   CurOp += X86::AddrNumOperands;
14338   SrcReg = MI->getOperand(CurOp++).getReg();
14339
14340   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14341   MVT::SimpleValueType VT = *RC->vt_begin();
14342   unsigned t1 = MRI.createVirtualRegister(RC);
14343   unsigned t2 = MRI.createVirtualRegister(RC);
14344   unsigned t3 = MRI.createVirtualRegister(RC);
14345   unsigned t4 = MRI.createVirtualRegister(RC);
14346   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14347
14348   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14349   unsigned LOADOpc = getLoadOpcode(VT);
14350
14351   // For the atomic load-arith operator, we generate
14352   //
14353   //  thisMBB:
14354   //    t1 = LOAD [MI.addr]
14355   //  mainMBB:
14356   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14357   //    t1 = OP MI.val, EAX
14358   //    EAX = t4
14359   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14360   //    t3 = EAX
14361   //    JNE mainMBB
14362   //  sinkMBB:
14363   //    dst = t3
14364
14365   MachineBasicBlock *thisMBB = MBB;
14366   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14367   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14368   MF->insert(I, mainMBB);
14369   MF->insert(I, sinkMBB);
14370
14371   MachineInstrBuilder MIB;
14372
14373   // Transfer the remainder of BB and its successor edges to sinkMBB.
14374   sinkMBB->splice(sinkMBB->begin(), MBB,
14375                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14376   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14377
14378   // thisMBB:
14379   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14380   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14381     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14382     if (NewMO.isReg())
14383       NewMO.setIsKill(false);
14384     MIB.addOperand(NewMO);
14385   }
14386   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14387     unsigned flags = (*MMOI)->getFlags();
14388     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14389     MachineMemOperand *MMO =
14390       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14391                                (*MMOI)->getSize(),
14392                                (*MMOI)->getBaseAlignment(),
14393                                (*MMOI)->getTBAAInfo(),
14394                                (*MMOI)->getRanges());
14395     MIB.addMemOperand(MMO);
14396   }
14397
14398   thisMBB->addSuccessor(mainMBB);
14399
14400   // mainMBB:
14401   MachineBasicBlock *origMainMBB = mainMBB;
14402
14403   // Add a PHI.
14404   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14405                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14406
14407   unsigned Opc = MI->getOpcode();
14408   switch (Opc) {
14409   default:
14410     llvm_unreachable("Unhandled atomic-load-op opcode!");
14411   case X86::ATOMAND8:
14412   case X86::ATOMAND16:
14413   case X86::ATOMAND32:
14414   case X86::ATOMAND64:
14415   case X86::ATOMOR8:
14416   case X86::ATOMOR16:
14417   case X86::ATOMOR32:
14418   case X86::ATOMOR64:
14419   case X86::ATOMXOR8:
14420   case X86::ATOMXOR16:
14421   case X86::ATOMXOR32:
14422   case X86::ATOMXOR64: {
14423     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14424     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14425       .addReg(t4);
14426     break;
14427   }
14428   case X86::ATOMNAND8:
14429   case X86::ATOMNAND16:
14430   case X86::ATOMNAND32:
14431   case X86::ATOMNAND64: {
14432     unsigned Tmp = MRI.createVirtualRegister(RC);
14433     unsigned NOTOpc;
14434     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14435     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14436       .addReg(t4);
14437     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14438     break;
14439   }
14440   case X86::ATOMMAX8:
14441   case X86::ATOMMAX16:
14442   case X86::ATOMMAX32:
14443   case X86::ATOMMAX64:
14444   case X86::ATOMMIN8:
14445   case X86::ATOMMIN16:
14446   case X86::ATOMMIN32:
14447   case X86::ATOMMIN64:
14448   case X86::ATOMUMAX8:
14449   case X86::ATOMUMAX16:
14450   case X86::ATOMUMAX32:
14451   case X86::ATOMUMAX64:
14452   case X86::ATOMUMIN8:
14453   case X86::ATOMUMIN16:
14454   case X86::ATOMUMIN32:
14455   case X86::ATOMUMIN64: {
14456     unsigned CMPOpc;
14457     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14458
14459     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14460       .addReg(SrcReg)
14461       .addReg(t4);
14462
14463     if (Subtarget->hasCMov()) {
14464       if (VT != MVT::i8) {
14465         // Native support
14466         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14467           .addReg(SrcReg)
14468           .addReg(t4);
14469       } else {
14470         // Promote i8 to i32 to use CMOV32
14471         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14472         const TargetRegisterClass *RC32 =
14473           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14474         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14475         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14476         unsigned Tmp = MRI.createVirtualRegister(RC32);
14477
14478         unsigned Undef = MRI.createVirtualRegister(RC32);
14479         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14480
14481         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14482           .addReg(Undef)
14483           .addReg(SrcReg)
14484           .addImm(X86::sub_8bit);
14485         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14486           .addReg(Undef)
14487           .addReg(t4)
14488           .addImm(X86::sub_8bit);
14489
14490         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14491           .addReg(SrcReg32)
14492           .addReg(AccReg32);
14493
14494         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14495           .addReg(Tmp, 0, X86::sub_8bit);
14496       }
14497     } else {
14498       // Use pseudo select and lower them.
14499       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14500              "Invalid atomic-load-op transformation!");
14501       unsigned SelOpc = getPseudoCMOVOpc(VT);
14502       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14503       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14504       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14505               .addReg(SrcReg).addReg(t4)
14506               .addImm(CC);
14507       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14508       // Replace the original PHI node as mainMBB is changed after CMOV
14509       // lowering.
14510       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14511         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14512       Phi->eraseFromParent();
14513     }
14514     break;
14515   }
14516   }
14517
14518   // Copy PhyReg back from virtual register.
14519   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14520     .addReg(t4);
14521
14522   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14523   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14524     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14525     if (NewMO.isReg())
14526       NewMO.setIsKill(false);
14527     MIB.addOperand(NewMO);
14528   }
14529   MIB.addReg(t2);
14530   MIB.setMemRefs(MMOBegin, MMOEnd);
14531
14532   // Copy PhyReg back to virtual register.
14533   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14534     .addReg(PhyReg);
14535
14536   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14537
14538   mainMBB->addSuccessor(origMainMBB);
14539   mainMBB->addSuccessor(sinkMBB);
14540
14541   // sinkMBB:
14542   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14543           TII->get(TargetOpcode::COPY), DstReg)
14544     .addReg(t3);
14545
14546   MI->eraseFromParent();
14547   return sinkMBB;
14548 }
14549
14550 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14551 // instructions. They will be translated into a spin-loop or compare-exchange
14552 // loop from
14553 //
14554 //    ...
14555 //    dst = atomic-fetch-op MI.addr, MI.val
14556 //    ...
14557 //
14558 // to
14559 //
14560 //    ...
14561 //    t1L = LOAD [MI.addr + 0]
14562 //    t1H = LOAD [MI.addr + 4]
14563 // loop:
14564 //    t4L = phi(t1L, t3L / loop)
14565 //    t4H = phi(t1H, t3H / loop)
14566 //    t2L = OP MI.val.lo, t4L
14567 //    t2H = OP MI.val.hi, t4H
14568 //    EAX = t4L
14569 //    EDX = t4H
14570 //    EBX = t2L
14571 //    ECX = t2H
14572 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14573 //    t3L = EAX
14574 //    t3H = EDX
14575 //    JNE loop
14576 // sink:
14577 //    dstL = t3L
14578 //    dstH = t3H
14579 //    ...
14580 MachineBasicBlock *
14581 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14582                                            MachineBasicBlock *MBB) const {
14583   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14584   DebugLoc DL = MI->getDebugLoc();
14585
14586   MachineFunction *MF = MBB->getParent();
14587   MachineRegisterInfo &MRI = MF->getRegInfo();
14588
14589   const BasicBlock *BB = MBB->getBasicBlock();
14590   MachineFunction::iterator I = MBB;
14591   ++I;
14592
14593   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14594          "Unexpected number of operands");
14595
14596   assert(MI->hasOneMemOperand() &&
14597          "Expected atomic-load-op32 to have one memoperand");
14598
14599   // Memory Reference
14600   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14601   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14602
14603   unsigned DstLoReg, DstHiReg;
14604   unsigned SrcLoReg, SrcHiReg;
14605   unsigned MemOpndSlot;
14606
14607   unsigned CurOp = 0;
14608
14609   DstLoReg = MI->getOperand(CurOp++).getReg();
14610   DstHiReg = MI->getOperand(CurOp++).getReg();
14611   MemOpndSlot = CurOp;
14612   CurOp += X86::AddrNumOperands;
14613   SrcLoReg = MI->getOperand(CurOp++).getReg();
14614   SrcHiReg = MI->getOperand(CurOp++).getReg();
14615
14616   const TargetRegisterClass *RC = &X86::GR32RegClass;
14617   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14618
14619   unsigned t1L = MRI.createVirtualRegister(RC);
14620   unsigned t1H = MRI.createVirtualRegister(RC);
14621   unsigned t2L = MRI.createVirtualRegister(RC);
14622   unsigned t2H = MRI.createVirtualRegister(RC);
14623   unsigned t3L = MRI.createVirtualRegister(RC);
14624   unsigned t3H = MRI.createVirtualRegister(RC);
14625   unsigned t4L = MRI.createVirtualRegister(RC);
14626   unsigned t4H = MRI.createVirtualRegister(RC);
14627
14628   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14629   unsigned LOADOpc = X86::MOV32rm;
14630
14631   // For the atomic load-arith operator, we generate
14632   //
14633   //  thisMBB:
14634   //    t1L = LOAD [MI.addr + 0]
14635   //    t1H = LOAD [MI.addr + 4]
14636   //  mainMBB:
14637   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14638   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14639   //    t2L = OP MI.val.lo, t4L
14640   //    t2H = OP MI.val.hi, t4H
14641   //    EBX = t2L
14642   //    ECX = t2H
14643   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14644   //    t3L = EAX
14645   //    t3H = EDX
14646   //    JNE loop
14647   //  sinkMBB:
14648   //    dstL = t3L
14649   //    dstH = t3H
14650
14651   MachineBasicBlock *thisMBB = MBB;
14652   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14653   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14654   MF->insert(I, mainMBB);
14655   MF->insert(I, sinkMBB);
14656
14657   MachineInstrBuilder MIB;
14658
14659   // Transfer the remainder of BB and its successor edges to sinkMBB.
14660   sinkMBB->splice(sinkMBB->begin(), MBB,
14661                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14662   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14663
14664   // thisMBB:
14665   // Lo
14666   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14667   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14668     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14669     if (NewMO.isReg())
14670       NewMO.setIsKill(false);
14671     MIB.addOperand(NewMO);
14672   }
14673   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14674     unsigned flags = (*MMOI)->getFlags();
14675     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14676     MachineMemOperand *MMO =
14677       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14678                                (*MMOI)->getSize(),
14679                                (*MMOI)->getBaseAlignment(),
14680                                (*MMOI)->getTBAAInfo(),
14681                                (*MMOI)->getRanges());
14682     MIB.addMemOperand(MMO);
14683   };
14684   MachineInstr *LowMI = MIB;
14685
14686   // Hi
14687   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14688   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14689     if (i == X86::AddrDisp) {
14690       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14691     } else {
14692       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14693       if (NewMO.isReg())
14694         NewMO.setIsKill(false);
14695       MIB.addOperand(NewMO);
14696     }
14697   }
14698   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14699
14700   thisMBB->addSuccessor(mainMBB);
14701
14702   // mainMBB:
14703   MachineBasicBlock *origMainMBB = mainMBB;
14704
14705   // Add PHIs.
14706   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14707                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14708   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14709                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14710
14711   unsigned Opc = MI->getOpcode();
14712   switch (Opc) {
14713   default:
14714     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14715   case X86::ATOMAND6432:
14716   case X86::ATOMOR6432:
14717   case X86::ATOMXOR6432:
14718   case X86::ATOMADD6432:
14719   case X86::ATOMSUB6432: {
14720     unsigned HiOpc;
14721     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14722     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14723       .addReg(SrcLoReg);
14724     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14725       .addReg(SrcHiReg);
14726     break;
14727   }
14728   case X86::ATOMNAND6432: {
14729     unsigned HiOpc, NOTOpc;
14730     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14731     unsigned TmpL = MRI.createVirtualRegister(RC);
14732     unsigned TmpH = MRI.createVirtualRegister(RC);
14733     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14734       .addReg(t4L);
14735     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14736       .addReg(t4H);
14737     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14738     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14739     break;
14740   }
14741   case X86::ATOMMAX6432:
14742   case X86::ATOMMIN6432:
14743   case X86::ATOMUMAX6432:
14744   case X86::ATOMUMIN6432: {
14745     unsigned HiOpc;
14746     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14747     unsigned cL = MRI.createVirtualRegister(RC8);
14748     unsigned cH = MRI.createVirtualRegister(RC8);
14749     unsigned cL32 = MRI.createVirtualRegister(RC);
14750     unsigned cH32 = MRI.createVirtualRegister(RC);
14751     unsigned cc = MRI.createVirtualRegister(RC);
14752     // cl := cmp src_lo, lo
14753     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14754       .addReg(SrcLoReg).addReg(t4L);
14755     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14756     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14757     // ch := cmp src_hi, hi
14758     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14759       .addReg(SrcHiReg).addReg(t4H);
14760     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14761     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14762     // cc := if (src_hi == hi) ? cl : ch;
14763     if (Subtarget->hasCMov()) {
14764       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14765         .addReg(cH32).addReg(cL32);
14766     } else {
14767       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14768               .addReg(cH32).addReg(cL32)
14769               .addImm(X86::COND_E);
14770       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14771     }
14772     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14773     if (Subtarget->hasCMov()) {
14774       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14775         .addReg(SrcLoReg).addReg(t4L);
14776       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14777         .addReg(SrcHiReg).addReg(t4H);
14778     } else {
14779       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14780               .addReg(SrcLoReg).addReg(t4L)
14781               .addImm(X86::COND_NE);
14782       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14783       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14784       // 2nd CMOV lowering.
14785       mainMBB->addLiveIn(X86::EFLAGS);
14786       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14787               .addReg(SrcHiReg).addReg(t4H)
14788               .addImm(X86::COND_NE);
14789       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14790       // Replace the original PHI node as mainMBB is changed after CMOV
14791       // lowering.
14792       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14793         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14794       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14795         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14796       PhiL->eraseFromParent();
14797       PhiH->eraseFromParent();
14798     }
14799     break;
14800   }
14801   case X86::ATOMSWAP6432: {
14802     unsigned HiOpc;
14803     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14804     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14805     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14806     break;
14807   }
14808   }
14809
14810   // Copy EDX:EAX back from HiReg:LoReg
14811   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14812   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14813   // Copy ECX:EBX from t1H:t1L
14814   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14815   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14816
14817   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14818   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14819     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14820     if (NewMO.isReg())
14821       NewMO.setIsKill(false);
14822     MIB.addOperand(NewMO);
14823   }
14824   MIB.setMemRefs(MMOBegin, MMOEnd);
14825
14826   // Copy EDX:EAX back to t3H:t3L
14827   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14828   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14829
14830   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14831
14832   mainMBB->addSuccessor(origMainMBB);
14833   mainMBB->addSuccessor(sinkMBB);
14834
14835   // sinkMBB:
14836   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14837           TII->get(TargetOpcode::COPY), DstLoReg)
14838     .addReg(t3L);
14839   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14840           TII->get(TargetOpcode::COPY), DstHiReg)
14841     .addReg(t3H);
14842
14843   MI->eraseFromParent();
14844   return sinkMBB;
14845 }
14846
14847 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14848 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14849 // in the .td file.
14850 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14851                                        const TargetInstrInfo *TII) {
14852   unsigned Opc;
14853   switch (MI->getOpcode()) {
14854   default: llvm_unreachable("illegal opcode!");
14855   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14856   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14857   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14858   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14859   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14860   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14861   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14862   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14863   }
14864
14865   DebugLoc dl = MI->getDebugLoc();
14866   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14867
14868   unsigned NumArgs = MI->getNumOperands();
14869   for (unsigned i = 1; i < NumArgs; ++i) {
14870     MachineOperand &Op = MI->getOperand(i);
14871     if (!(Op.isReg() && Op.isImplicit()))
14872       MIB.addOperand(Op);
14873   }
14874   if (MI->hasOneMemOperand())
14875     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14876
14877   BuildMI(*BB, MI, dl,
14878     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14879     .addReg(X86::XMM0);
14880
14881   MI->eraseFromParent();
14882   return BB;
14883 }
14884
14885 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14886 // defs in an instruction pattern
14887 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14888                                        const TargetInstrInfo *TII) {
14889   unsigned Opc;
14890   switch (MI->getOpcode()) {
14891   default: llvm_unreachable("illegal opcode!");
14892   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14893   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14894   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14895   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14896   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14897   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14898   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14899   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14900   }
14901
14902   DebugLoc dl = MI->getDebugLoc();
14903   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14904
14905   unsigned NumArgs = MI->getNumOperands(); // remove the results
14906   for (unsigned i = 1; i < NumArgs; ++i) {
14907     MachineOperand &Op = MI->getOperand(i);
14908     if (!(Op.isReg() && Op.isImplicit()))
14909       MIB.addOperand(Op);
14910   }
14911   if (MI->hasOneMemOperand())
14912     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14913
14914   BuildMI(*BB, MI, dl,
14915     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14916     .addReg(X86::ECX);
14917
14918   MI->eraseFromParent();
14919   return BB;
14920 }
14921
14922 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14923                                        const TargetInstrInfo *TII,
14924                                        const X86Subtarget* Subtarget) {
14925   DebugLoc dl = MI->getDebugLoc();
14926
14927   // Address into RAX/EAX, other two args into ECX, EDX.
14928   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14929   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14930   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14931   for (int i = 0; i < X86::AddrNumOperands; ++i)
14932     MIB.addOperand(MI->getOperand(i));
14933
14934   unsigned ValOps = X86::AddrNumOperands;
14935   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14936     .addReg(MI->getOperand(ValOps).getReg());
14937   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14938     .addReg(MI->getOperand(ValOps+1).getReg());
14939
14940   // The instruction doesn't actually take any operands though.
14941   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14942
14943   MI->eraseFromParent(); // The pseudo is gone now.
14944   return BB;
14945 }
14946
14947 MachineBasicBlock *
14948 X86TargetLowering::EmitVAARG64WithCustomInserter(
14949                    MachineInstr *MI,
14950                    MachineBasicBlock *MBB) const {
14951   // Emit va_arg instruction on X86-64.
14952
14953   // Operands to this pseudo-instruction:
14954   // 0  ) Output        : destination address (reg)
14955   // 1-5) Input         : va_list address (addr, i64mem)
14956   // 6  ) ArgSize       : Size (in bytes) of vararg type
14957   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14958   // 8  ) Align         : Alignment of type
14959   // 9  ) EFLAGS (implicit-def)
14960
14961   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14962   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14963
14964   unsigned DestReg = MI->getOperand(0).getReg();
14965   MachineOperand &Base = MI->getOperand(1);
14966   MachineOperand &Scale = MI->getOperand(2);
14967   MachineOperand &Index = MI->getOperand(3);
14968   MachineOperand &Disp = MI->getOperand(4);
14969   MachineOperand &Segment = MI->getOperand(5);
14970   unsigned ArgSize = MI->getOperand(6).getImm();
14971   unsigned ArgMode = MI->getOperand(7).getImm();
14972   unsigned Align = MI->getOperand(8).getImm();
14973
14974   // Memory Reference
14975   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14976   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14977   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14978
14979   // Machine Information
14980   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14981   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14982   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14983   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14984   DebugLoc DL = MI->getDebugLoc();
14985
14986   // struct va_list {
14987   //   i32   gp_offset
14988   //   i32   fp_offset
14989   //   i64   overflow_area (address)
14990   //   i64   reg_save_area (address)
14991   // }
14992   // sizeof(va_list) = 24
14993   // alignment(va_list) = 8
14994
14995   unsigned TotalNumIntRegs = 6;
14996   unsigned TotalNumXMMRegs = 8;
14997   bool UseGPOffset = (ArgMode == 1);
14998   bool UseFPOffset = (ArgMode == 2);
14999   unsigned MaxOffset = TotalNumIntRegs * 8 +
15000                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15001
15002   /* Align ArgSize to a multiple of 8 */
15003   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15004   bool NeedsAlign = (Align > 8);
15005
15006   MachineBasicBlock *thisMBB = MBB;
15007   MachineBasicBlock *overflowMBB;
15008   MachineBasicBlock *offsetMBB;
15009   MachineBasicBlock *endMBB;
15010
15011   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15012   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15013   unsigned OffsetReg = 0;
15014
15015   if (!UseGPOffset && !UseFPOffset) {
15016     // If we only pull from the overflow region, we don't create a branch.
15017     // We don't need to alter control flow.
15018     OffsetDestReg = 0; // unused
15019     OverflowDestReg = DestReg;
15020
15021     offsetMBB = NULL;
15022     overflowMBB = thisMBB;
15023     endMBB = thisMBB;
15024   } else {
15025     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15026     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15027     // If not, pull from overflow_area. (branch to overflowMBB)
15028     //
15029     //       thisMBB
15030     //         |     .
15031     //         |        .
15032     //     offsetMBB   overflowMBB
15033     //         |        .
15034     //         |     .
15035     //        endMBB
15036
15037     // Registers for the PHI in endMBB
15038     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15039     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15040
15041     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15042     MachineFunction *MF = MBB->getParent();
15043     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15044     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15045     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15046
15047     MachineFunction::iterator MBBIter = MBB;
15048     ++MBBIter;
15049
15050     // Insert the new basic blocks
15051     MF->insert(MBBIter, offsetMBB);
15052     MF->insert(MBBIter, overflowMBB);
15053     MF->insert(MBBIter, endMBB);
15054
15055     // Transfer the remainder of MBB and its successor edges to endMBB.
15056     endMBB->splice(endMBB->begin(), thisMBB,
15057                     llvm::next(MachineBasicBlock::iterator(MI)),
15058                     thisMBB->end());
15059     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15060
15061     // Make offsetMBB and overflowMBB successors of thisMBB
15062     thisMBB->addSuccessor(offsetMBB);
15063     thisMBB->addSuccessor(overflowMBB);
15064
15065     // endMBB is a successor of both offsetMBB and overflowMBB
15066     offsetMBB->addSuccessor(endMBB);
15067     overflowMBB->addSuccessor(endMBB);
15068
15069     // Load the offset value into a register
15070     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15071     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15072       .addOperand(Base)
15073       .addOperand(Scale)
15074       .addOperand(Index)
15075       .addDisp(Disp, UseFPOffset ? 4 : 0)
15076       .addOperand(Segment)
15077       .setMemRefs(MMOBegin, MMOEnd);
15078
15079     // Check if there is enough room left to pull this argument.
15080     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15081       .addReg(OffsetReg)
15082       .addImm(MaxOffset + 8 - ArgSizeA8);
15083
15084     // Branch to "overflowMBB" if offset >= max
15085     // Fall through to "offsetMBB" otherwise
15086     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15087       .addMBB(overflowMBB);
15088   }
15089
15090   // In offsetMBB, emit code to use the reg_save_area.
15091   if (offsetMBB) {
15092     assert(OffsetReg != 0);
15093
15094     // Read the reg_save_area address.
15095     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15096     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15097       .addOperand(Base)
15098       .addOperand(Scale)
15099       .addOperand(Index)
15100       .addDisp(Disp, 16)
15101       .addOperand(Segment)
15102       .setMemRefs(MMOBegin, MMOEnd);
15103
15104     // Zero-extend the offset
15105     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15106       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15107         .addImm(0)
15108         .addReg(OffsetReg)
15109         .addImm(X86::sub_32bit);
15110
15111     // Add the offset to the reg_save_area to get the final address.
15112     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15113       .addReg(OffsetReg64)
15114       .addReg(RegSaveReg);
15115
15116     // Compute the offset for the next argument
15117     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15118     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15119       .addReg(OffsetReg)
15120       .addImm(UseFPOffset ? 16 : 8);
15121
15122     // Store it back into the va_list.
15123     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15124       .addOperand(Base)
15125       .addOperand(Scale)
15126       .addOperand(Index)
15127       .addDisp(Disp, UseFPOffset ? 4 : 0)
15128       .addOperand(Segment)
15129       .addReg(NextOffsetReg)
15130       .setMemRefs(MMOBegin, MMOEnd);
15131
15132     // Jump to endMBB
15133     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15134       .addMBB(endMBB);
15135   }
15136
15137   //
15138   // Emit code to use overflow area
15139   //
15140
15141   // Load the overflow_area address into a register.
15142   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15143   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15144     .addOperand(Base)
15145     .addOperand(Scale)
15146     .addOperand(Index)
15147     .addDisp(Disp, 8)
15148     .addOperand(Segment)
15149     .setMemRefs(MMOBegin, MMOEnd);
15150
15151   // If we need to align it, do so. Otherwise, just copy the address
15152   // to OverflowDestReg.
15153   if (NeedsAlign) {
15154     // Align the overflow address
15155     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15156     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15157
15158     // aligned_addr = (addr + (align-1)) & ~(align-1)
15159     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15160       .addReg(OverflowAddrReg)
15161       .addImm(Align-1);
15162
15163     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15164       .addReg(TmpReg)
15165       .addImm(~(uint64_t)(Align-1));
15166   } else {
15167     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15168       .addReg(OverflowAddrReg);
15169   }
15170
15171   // Compute the next overflow address after this argument.
15172   // (the overflow address should be kept 8-byte aligned)
15173   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15174   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15175     .addReg(OverflowDestReg)
15176     .addImm(ArgSizeA8);
15177
15178   // Store the new overflow address.
15179   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15180     .addOperand(Base)
15181     .addOperand(Scale)
15182     .addOperand(Index)
15183     .addDisp(Disp, 8)
15184     .addOperand(Segment)
15185     .addReg(NextAddrReg)
15186     .setMemRefs(MMOBegin, MMOEnd);
15187
15188   // If we branched, emit the PHI to the front of endMBB.
15189   if (offsetMBB) {
15190     BuildMI(*endMBB, endMBB->begin(), DL,
15191             TII->get(X86::PHI), DestReg)
15192       .addReg(OffsetDestReg).addMBB(offsetMBB)
15193       .addReg(OverflowDestReg).addMBB(overflowMBB);
15194   }
15195
15196   // Erase the pseudo instruction
15197   MI->eraseFromParent();
15198
15199   return endMBB;
15200 }
15201
15202 MachineBasicBlock *
15203 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15204                                                  MachineInstr *MI,
15205                                                  MachineBasicBlock *MBB) const {
15206   // Emit code to save XMM registers to the stack. The ABI says that the
15207   // number of registers to save is given in %al, so it's theoretically
15208   // possible to do an indirect jump trick to avoid saving all of them,
15209   // however this code takes a simpler approach and just executes all
15210   // of the stores if %al is non-zero. It's less code, and it's probably
15211   // easier on the hardware branch predictor, and stores aren't all that
15212   // expensive anyway.
15213
15214   // Create the new basic blocks. One block contains all the XMM stores,
15215   // and one block is the final destination regardless of whether any
15216   // stores were performed.
15217   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15218   MachineFunction *F = MBB->getParent();
15219   MachineFunction::iterator MBBIter = MBB;
15220   ++MBBIter;
15221   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15222   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15223   F->insert(MBBIter, XMMSaveMBB);
15224   F->insert(MBBIter, EndMBB);
15225
15226   // Transfer the remainder of MBB and its successor edges to EndMBB.
15227   EndMBB->splice(EndMBB->begin(), MBB,
15228                  llvm::next(MachineBasicBlock::iterator(MI)),
15229                  MBB->end());
15230   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15231
15232   // The original block will now fall through to the XMM save block.
15233   MBB->addSuccessor(XMMSaveMBB);
15234   // The XMMSaveMBB will fall through to the end block.
15235   XMMSaveMBB->addSuccessor(EndMBB);
15236
15237   // Now add the instructions.
15238   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15239   DebugLoc DL = MI->getDebugLoc();
15240
15241   unsigned CountReg = MI->getOperand(0).getReg();
15242   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15243   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15244
15245   if (!Subtarget->isTargetWin64()) {
15246     // If %al is 0, branch around the XMM save block.
15247     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15248     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15249     MBB->addSuccessor(EndMBB);
15250   }
15251
15252   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15253   // In the XMM save block, save all the XMM argument registers.
15254   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
15255     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15256     MachineMemOperand *MMO =
15257       F->getMachineMemOperand(
15258           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15259         MachineMemOperand::MOStore,
15260         /*Size=*/16, /*Align=*/16);
15261     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15262       .addFrameIndex(RegSaveFrameIndex)
15263       .addImm(/*Scale=*/1)
15264       .addReg(/*IndexReg=*/0)
15265       .addImm(/*Disp=*/Offset)
15266       .addReg(/*Segment=*/0)
15267       .addReg(MI->getOperand(i).getReg())
15268       .addMemOperand(MMO);
15269   }
15270
15271   MI->eraseFromParent();   // The pseudo instruction is gone now.
15272
15273   return EndMBB;
15274 }
15275
15276 // The EFLAGS operand of SelectItr might be missing a kill marker
15277 // because there were multiple uses of EFLAGS, and ISel didn't know
15278 // which to mark. Figure out whether SelectItr should have had a
15279 // kill marker, and set it if it should. Returns the correct kill
15280 // marker value.
15281 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15282                                      MachineBasicBlock* BB,
15283                                      const TargetRegisterInfo* TRI) {
15284   // Scan forward through BB for a use/def of EFLAGS.
15285   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15286   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15287     const MachineInstr& mi = *miI;
15288     if (mi.readsRegister(X86::EFLAGS))
15289       return false;
15290     if (mi.definesRegister(X86::EFLAGS))
15291       break; // Should have kill-flag - update below.
15292   }
15293
15294   // If we hit the end of the block, check whether EFLAGS is live into a
15295   // successor.
15296   if (miI == BB->end()) {
15297     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15298                                           sEnd = BB->succ_end();
15299          sItr != sEnd; ++sItr) {
15300       MachineBasicBlock* succ = *sItr;
15301       if (succ->isLiveIn(X86::EFLAGS))
15302         return false;
15303     }
15304   }
15305
15306   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15307   // out. SelectMI should have a kill flag on EFLAGS.
15308   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15309   return true;
15310 }
15311
15312 MachineBasicBlock *
15313 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15314                                      MachineBasicBlock *BB) const {
15315   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15316   DebugLoc DL = MI->getDebugLoc();
15317
15318   // To "insert" a SELECT_CC instruction, we actually have to insert the
15319   // diamond control-flow pattern.  The incoming instruction knows the
15320   // destination vreg to set, the condition code register to branch on, the
15321   // true/false values to select between, and a branch opcode to use.
15322   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15323   MachineFunction::iterator It = BB;
15324   ++It;
15325
15326   //  thisMBB:
15327   //  ...
15328   //   TrueVal = ...
15329   //   cmpTY ccX, r1, r2
15330   //   bCC copy1MBB
15331   //   fallthrough --> copy0MBB
15332   MachineBasicBlock *thisMBB = BB;
15333   MachineFunction *F = BB->getParent();
15334   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15335   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15336   F->insert(It, copy0MBB);
15337   F->insert(It, sinkMBB);
15338
15339   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15340   // live into the sink and copy blocks.
15341   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15342   if (!MI->killsRegister(X86::EFLAGS) &&
15343       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15344     copy0MBB->addLiveIn(X86::EFLAGS);
15345     sinkMBB->addLiveIn(X86::EFLAGS);
15346   }
15347
15348   // Transfer the remainder of BB and its successor edges to sinkMBB.
15349   sinkMBB->splice(sinkMBB->begin(), BB,
15350                   llvm::next(MachineBasicBlock::iterator(MI)),
15351                   BB->end());
15352   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15353
15354   // Add the true and fallthrough blocks as its successors.
15355   BB->addSuccessor(copy0MBB);
15356   BB->addSuccessor(sinkMBB);
15357
15358   // Create the conditional branch instruction.
15359   unsigned Opc =
15360     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15361   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15362
15363   //  copy0MBB:
15364   //   %FalseValue = ...
15365   //   # fallthrough to sinkMBB
15366   copy0MBB->addSuccessor(sinkMBB);
15367
15368   //  sinkMBB:
15369   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15370   //  ...
15371   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15372           TII->get(X86::PHI), MI->getOperand(0).getReg())
15373     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15374     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15375
15376   MI->eraseFromParent();   // The pseudo instruction is gone now.
15377   return sinkMBB;
15378 }
15379
15380 MachineBasicBlock *
15381 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15382                                         bool Is64Bit) const {
15383   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15384   DebugLoc DL = MI->getDebugLoc();
15385   MachineFunction *MF = BB->getParent();
15386   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15387
15388   assert(getTargetMachine().Options.EnableSegmentedStacks);
15389
15390   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15391   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15392
15393   // BB:
15394   //  ... [Till the alloca]
15395   // If stacklet is not large enough, jump to mallocMBB
15396   //
15397   // bumpMBB:
15398   //  Allocate by subtracting from RSP
15399   //  Jump to continueMBB
15400   //
15401   // mallocMBB:
15402   //  Allocate by call to runtime
15403   //
15404   // continueMBB:
15405   //  ...
15406   //  [rest of original BB]
15407   //
15408
15409   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15410   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15411   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15412
15413   MachineRegisterInfo &MRI = MF->getRegInfo();
15414   const TargetRegisterClass *AddrRegClass =
15415     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15416
15417   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15418     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15419     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15420     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15421     sizeVReg = MI->getOperand(1).getReg(),
15422     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15423
15424   MachineFunction::iterator MBBIter = BB;
15425   ++MBBIter;
15426
15427   MF->insert(MBBIter, bumpMBB);
15428   MF->insert(MBBIter, mallocMBB);
15429   MF->insert(MBBIter, continueMBB);
15430
15431   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15432                       (MachineBasicBlock::iterator(MI)), BB->end());
15433   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15434
15435   // Add code to the main basic block to check if the stack limit has been hit,
15436   // and if so, jump to mallocMBB otherwise to bumpMBB.
15437   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15438   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15439     .addReg(tmpSPVReg).addReg(sizeVReg);
15440   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15441     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15442     .addReg(SPLimitVReg);
15443   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15444
15445   // bumpMBB simply decreases the stack pointer, since we know the current
15446   // stacklet has enough space.
15447   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15448     .addReg(SPLimitVReg);
15449   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15450     .addReg(SPLimitVReg);
15451   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15452
15453   // Calls into a routine in libgcc to allocate more space from the heap.
15454   const uint32_t *RegMask =
15455     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15456   if (Is64Bit) {
15457     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15458       .addReg(sizeVReg);
15459     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15460       .addExternalSymbol("__morestack_allocate_stack_space")
15461       .addRegMask(RegMask)
15462       .addReg(X86::RDI, RegState::Implicit)
15463       .addReg(X86::RAX, RegState::ImplicitDefine);
15464   } else {
15465     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15466       .addImm(12);
15467     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15468     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15469       .addExternalSymbol("__morestack_allocate_stack_space")
15470       .addRegMask(RegMask)
15471       .addReg(X86::EAX, RegState::ImplicitDefine);
15472   }
15473
15474   if (!Is64Bit)
15475     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15476       .addImm(16);
15477
15478   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15479     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15480   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15481
15482   // Set up the CFG correctly.
15483   BB->addSuccessor(bumpMBB);
15484   BB->addSuccessor(mallocMBB);
15485   mallocMBB->addSuccessor(continueMBB);
15486   bumpMBB->addSuccessor(continueMBB);
15487
15488   // Take care of the PHI nodes.
15489   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15490           MI->getOperand(0).getReg())
15491     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15492     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15493
15494   // Delete the original pseudo instruction.
15495   MI->eraseFromParent();
15496
15497   // And we're done.
15498   return continueMBB;
15499 }
15500
15501 MachineBasicBlock *
15502 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15503                                           MachineBasicBlock *BB) const {
15504   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15505   DebugLoc DL = MI->getDebugLoc();
15506
15507   assert(!Subtarget->isTargetEnvMacho());
15508
15509   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15510   // non-trivial part is impdef of ESP.
15511
15512   if (Subtarget->isTargetWin64()) {
15513     if (Subtarget->isTargetCygMing()) {
15514       // ___chkstk(Mingw64):
15515       // Clobbers R10, R11, RAX and EFLAGS.
15516       // Updates RSP.
15517       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15518         .addExternalSymbol("___chkstk")
15519         .addReg(X86::RAX, RegState::Implicit)
15520         .addReg(X86::RSP, RegState::Implicit)
15521         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15522         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15523         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15524     } else {
15525       // __chkstk(MSVCRT): does not update stack pointer.
15526       // Clobbers R10, R11 and EFLAGS.
15527       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15528         .addExternalSymbol("__chkstk")
15529         .addReg(X86::RAX, RegState::Implicit)
15530         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15531       // RAX has the offset to be subtracted from RSP.
15532       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15533         .addReg(X86::RSP)
15534         .addReg(X86::RAX);
15535     }
15536   } else {
15537     const char *StackProbeSymbol =
15538       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15539
15540     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15541       .addExternalSymbol(StackProbeSymbol)
15542       .addReg(X86::EAX, RegState::Implicit)
15543       .addReg(X86::ESP, RegState::Implicit)
15544       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15545       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15546       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15547   }
15548
15549   MI->eraseFromParent();   // The pseudo instruction is gone now.
15550   return BB;
15551 }
15552
15553 MachineBasicBlock *
15554 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15555                                       MachineBasicBlock *BB) const {
15556   // This is pretty easy.  We're taking the value that we received from
15557   // our load from the relocation, sticking it in either RDI (x86-64)
15558   // or EAX and doing an indirect call.  The return value will then
15559   // be in the normal return register.
15560   const X86InstrInfo *TII
15561     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15562   DebugLoc DL = MI->getDebugLoc();
15563   MachineFunction *F = BB->getParent();
15564
15565   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15566   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15567
15568   // Get a register mask for the lowered call.
15569   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15570   // proper register mask.
15571   const uint32_t *RegMask =
15572     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15573   if (Subtarget->is64Bit()) {
15574     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15575                                       TII->get(X86::MOV64rm), X86::RDI)
15576     .addReg(X86::RIP)
15577     .addImm(0).addReg(0)
15578     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15579                       MI->getOperand(3).getTargetFlags())
15580     .addReg(0);
15581     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15582     addDirectMem(MIB, X86::RDI);
15583     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15584   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15585     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15586                                       TII->get(X86::MOV32rm), X86::EAX)
15587     .addReg(0)
15588     .addImm(0).addReg(0)
15589     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15590                       MI->getOperand(3).getTargetFlags())
15591     .addReg(0);
15592     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15593     addDirectMem(MIB, X86::EAX);
15594     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15595   } else {
15596     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15597                                       TII->get(X86::MOV32rm), X86::EAX)
15598     .addReg(TII->getGlobalBaseReg(F))
15599     .addImm(0).addReg(0)
15600     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15601                       MI->getOperand(3).getTargetFlags())
15602     .addReg(0);
15603     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15604     addDirectMem(MIB, X86::EAX);
15605     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15606   }
15607
15608   MI->eraseFromParent(); // The pseudo instruction is gone now.
15609   return BB;
15610 }
15611
15612 MachineBasicBlock *
15613 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15614                                     MachineBasicBlock *MBB) const {
15615   DebugLoc DL = MI->getDebugLoc();
15616   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15617
15618   MachineFunction *MF = MBB->getParent();
15619   MachineRegisterInfo &MRI = MF->getRegInfo();
15620
15621   const BasicBlock *BB = MBB->getBasicBlock();
15622   MachineFunction::iterator I = MBB;
15623   ++I;
15624
15625   // Memory Reference
15626   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15627   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15628
15629   unsigned DstReg;
15630   unsigned MemOpndSlot = 0;
15631
15632   unsigned CurOp = 0;
15633
15634   DstReg = MI->getOperand(CurOp++).getReg();
15635   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15636   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15637   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15638   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15639
15640   MemOpndSlot = CurOp;
15641
15642   MVT PVT = getPointerTy();
15643   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15644          "Invalid Pointer Size!");
15645
15646   // For v = setjmp(buf), we generate
15647   //
15648   // thisMBB:
15649   //  buf[LabelOffset] = restoreMBB
15650   //  SjLjSetup restoreMBB
15651   //
15652   // mainMBB:
15653   //  v_main = 0
15654   //
15655   // sinkMBB:
15656   //  v = phi(main, restore)
15657   //
15658   // restoreMBB:
15659   //  v_restore = 1
15660
15661   MachineBasicBlock *thisMBB = MBB;
15662   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15663   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15664   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15665   MF->insert(I, mainMBB);
15666   MF->insert(I, sinkMBB);
15667   MF->push_back(restoreMBB);
15668
15669   MachineInstrBuilder MIB;
15670
15671   // Transfer the remainder of BB and its successor edges to sinkMBB.
15672   sinkMBB->splice(sinkMBB->begin(), MBB,
15673                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15674   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15675
15676   // thisMBB:
15677   unsigned PtrStoreOpc = 0;
15678   unsigned LabelReg = 0;
15679   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15680   Reloc::Model RM = getTargetMachine().getRelocationModel();
15681   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15682                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15683
15684   // Prepare IP either in reg or imm.
15685   if (!UseImmLabel) {
15686     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15687     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15688     LabelReg = MRI.createVirtualRegister(PtrRC);
15689     if (Subtarget->is64Bit()) {
15690       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15691               .addReg(X86::RIP)
15692               .addImm(0)
15693               .addReg(0)
15694               .addMBB(restoreMBB)
15695               .addReg(0);
15696     } else {
15697       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15698       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15699               .addReg(XII->getGlobalBaseReg(MF))
15700               .addImm(0)
15701               .addReg(0)
15702               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15703               .addReg(0);
15704     }
15705   } else
15706     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15707   // Store IP
15708   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15709   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15710     if (i == X86::AddrDisp)
15711       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15712     else
15713       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15714   }
15715   if (!UseImmLabel)
15716     MIB.addReg(LabelReg);
15717   else
15718     MIB.addMBB(restoreMBB);
15719   MIB.setMemRefs(MMOBegin, MMOEnd);
15720   // Setup
15721   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15722           .addMBB(restoreMBB);
15723
15724   const X86RegisterInfo *RegInfo =
15725     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15726   MIB.addRegMask(RegInfo->getNoPreservedMask());
15727   thisMBB->addSuccessor(mainMBB);
15728   thisMBB->addSuccessor(restoreMBB);
15729
15730   // mainMBB:
15731   //  EAX = 0
15732   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15733   mainMBB->addSuccessor(sinkMBB);
15734
15735   // sinkMBB:
15736   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15737           TII->get(X86::PHI), DstReg)
15738     .addReg(mainDstReg).addMBB(mainMBB)
15739     .addReg(restoreDstReg).addMBB(restoreMBB);
15740
15741   // restoreMBB:
15742   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15743   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15744   restoreMBB->addSuccessor(sinkMBB);
15745
15746   MI->eraseFromParent();
15747   return sinkMBB;
15748 }
15749
15750 MachineBasicBlock *
15751 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15752                                      MachineBasicBlock *MBB) const {
15753   DebugLoc DL = MI->getDebugLoc();
15754   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15755
15756   MachineFunction *MF = MBB->getParent();
15757   MachineRegisterInfo &MRI = MF->getRegInfo();
15758
15759   // Memory Reference
15760   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15761   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15762
15763   MVT PVT = getPointerTy();
15764   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15765          "Invalid Pointer Size!");
15766
15767   const TargetRegisterClass *RC =
15768     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15769   unsigned Tmp = MRI.createVirtualRegister(RC);
15770   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15771   const X86RegisterInfo *RegInfo =
15772     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15773   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15774   unsigned SP = RegInfo->getStackRegister();
15775
15776   MachineInstrBuilder MIB;
15777
15778   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15779   const int64_t SPOffset = 2 * PVT.getStoreSize();
15780
15781   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15782   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15783
15784   // Reload FP
15785   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15786   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15787     MIB.addOperand(MI->getOperand(i));
15788   MIB.setMemRefs(MMOBegin, MMOEnd);
15789   // Reload IP
15790   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15791   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15792     if (i == X86::AddrDisp)
15793       MIB.addDisp(MI->getOperand(i), LabelOffset);
15794     else
15795       MIB.addOperand(MI->getOperand(i));
15796   }
15797   MIB.setMemRefs(MMOBegin, MMOEnd);
15798   // Reload SP
15799   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15800   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15801     if (i == X86::AddrDisp)
15802       MIB.addDisp(MI->getOperand(i), SPOffset);
15803     else
15804       MIB.addOperand(MI->getOperand(i));
15805   }
15806   MIB.setMemRefs(MMOBegin, MMOEnd);
15807   // Jump
15808   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15809
15810   MI->eraseFromParent();
15811   return MBB;
15812 }
15813
15814 MachineBasicBlock *
15815 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15816                                                MachineBasicBlock *BB) const {
15817   switch (MI->getOpcode()) {
15818   default: llvm_unreachable("Unexpected instr type to insert");
15819   case X86::TAILJMPd64:
15820   case X86::TAILJMPr64:
15821   case X86::TAILJMPm64:
15822     llvm_unreachable("TAILJMP64 would not be touched here.");
15823   case X86::TCRETURNdi64:
15824   case X86::TCRETURNri64:
15825   case X86::TCRETURNmi64:
15826     return BB;
15827   case X86::WIN_ALLOCA:
15828     return EmitLoweredWinAlloca(MI, BB);
15829   case X86::SEG_ALLOCA_32:
15830     return EmitLoweredSegAlloca(MI, BB, false);
15831   case X86::SEG_ALLOCA_64:
15832     return EmitLoweredSegAlloca(MI, BB, true);
15833   case X86::TLSCall_32:
15834   case X86::TLSCall_64:
15835     return EmitLoweredTLSCall(MI, BB);
15836   case X86::CMOV_GR8:
15837   case X86::CMOV_FR32:
15838   case X86::CMOV_FR64:
15839   case X86::CMOV_V4F32:
15840   case X86::CMOV_V2F64:
15841   case X86::CMOV_V2I64:
15842   case X86::CMOV_V8F32:
15843   case X86::CMOV_V4F64:
15844   case X86::CMOV_V4I64:
15845   case X86::CMOV_V16F32:
15846   case X86::CMOV_V8F64:
15847   case X86::CMOV_V8I64:
15848   case X86::CMOV_GR16:
15849   case X86::CMOV_GR32:
15850   case X86::CMOV_RFP32:
15851   case X86::CMOV_RFP64:
15852   case X86::CMOV_RFP80:
15853     return EmitLoweredSelect(MI, BB);
15854
15855   case X86::FP32_TO_INT16_IN_MEM:
15856   case X86::FP32_TO_INT32_IN_MEM:
15857   case X86::FP32_TO_INT64_IN_MEM:
15858   case X86::FP64_TO_INT16_IN_MEM:
15859   case X86::FP64_TO_INT32_IN_MEM:
15860   case X86::FP64_TO_INT64_IN_MEM:
15861   case X86::FP80_TO_INT16_IN_MEM:
15862   case X86::FP80_TO_INT32_IN_MEM:
15863   case X86::FP80_TO_INT64_IN_MEM: {
15864     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15865     DebugLoc DL = MI->getDebugLoc();
15866
15867     // Change the floating point control register to use "round towards zero"
15868     // mode when truncating to an integer value.
15869     MachineFunction *F = BB->getParent();
15870     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15871     addFrameReference(BuildMI(*BB, MI, DL,
15872                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15873
15874     // Load the old value of the high byte of the control word...
15875     unsigned OldCW =
15876       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15877     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15878                       CWFrameIdx);
15879
15880     // Set the high part to be round to zero...
15881     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15882       .addImm(0xC7F);
15883
15884     // Reload the modified control word now...
15885     addFrameReference(BuildMI(*BB, MI, DL,
15886                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15887
15888     // Restore the memory image of control word to original value
15889     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15890       .addReg(OldCW);
15891
15892     // Get the X86 opcode to use.
15893     unsigned Opc;
15894     switch (MI->getOpcode()) {
15895     default: llvm_unreachable("illegal opcode!");
15896     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15897     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15898     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15899     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15900     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15901     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15902     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15903     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15904     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15905     }
15906
15907     X86AddressMode AM;
15908     MachineOperand &Op = MI->getOperand(0);
15909     if (Op.isReg()) {
15910       AM.BaseType = X86AddressMode::RegBase;
15911       AM.Base.Reg = Op.getReg();
15912     } else {
15913       AM.BaseType = X86AddressMode::FrameIndexBase;
15914       AM.Base.FrameIndex = Op.getIndex();
15915     }
15916     Op = MI->getOperand(1);
15917     if (Op.isImm())
15918       AM.Scale = Op.getImm();
15919     Op = MI->getOperand(2);
15920     if (Op.isImm())
15921       AM.IndexReg = Op.getImm();
15922     Op = MI->getOperand(3);
15923     if (Op.isGlobal()) {
15924       AM.GV = Op.getGlobal();
15925     } else {
15926       AM.Disp = Op.getImm();
15927     }
15928     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15929                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15930
15931     // Reload the original control word now.
15932     addFrameReference(BuildMI(*BB, MI, DL,
15933                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15934
15935     MI->eraseFromParent();   // The pseudo instruction is gone now.
15936     return BB;
15937   }
15938     // String/text processing lowering.
15939   case X86::PCMPISTRM128REG:
15940   case X86::VPCMPISTRM128REG:
15941   case X86::PCMPISTRM128MEM:
15942   case X86::VPCMPISTRM128MEM:
15943   case X86::PCMPESTRM128REG:
15944   case X86::VPCMPESTRM128REG:
15945   case X86::PCMPESTRM128MEM:
15946   case X86::VPCMPESTRM128MEM:
15947     assert(Subtarget->hasSSE42() &&
15948            "Target must have SSE4.2 or AVX features enabled");
15949     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15950
15951   // String/text processing lowering.
15952   case X86::PCMPISTRIREG:
15953   case X86::VPCMPISTRIREG:
15954   case X86::PCMPISTRIMEM:
15955   case X86::VPCMPISTRIMEM:
15956   case X86::PCMPESTRIREG:
15957   case X86::VPCMPESTRIREG:
15958   case X86::PCMPESTRIMEM:
15959   case X86::VPCMPESTRIMEM:
15960     assert(Subtarget->hasSSE42() &&
15961            "Target must have SSE4.2 or AVX features enabled");
15962     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15963
15964   // Thread synchronization.
15965   case X86::MONITOR:
15966     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15967
15968   // xbegin
15969   case X86::XBEGIN:
15970     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15971
15972   // Atomic Lowering.
15973   case X86::ATOMAND8:
15974   case X86::ATOMAND16:
15975   case X86::ATOMAND32:
15976   case X86::ATOMAND64:
15977     // Fall through
15978   case X86::ATOMOR8:
15979   case X86::ATOMOR16:
15980   case X86::ATOMOR32:
15981   case X86::ATOMOR64:
15982     // Fall through
15983   case X86::ATOMXOR16:
15984   case X86::ATOMXOR8:
15985   case X86::ATOMXOR32:
15986   case X86::ATOMXOR64:
15987     // Fall through
15988   case X86::ATOMNAND8:
15989   case X86::ATOMNAND16:
15990   case X86::ATOMNAND32:
15991   case X86::ATOMNAND64:
15992     // Fall through
15993   case X86::ATOMMAX8:
15994   case X86::ATOMMAX16:
15995   case X86::ATOMMAX32:
15996   case X86::ATOMMAX64:
15997     // Fall through
15998   case X86::ATOMMIN8:
15999   case X86::ATOMMIN16:
16000   case X86::ATOMMIN32:
16001   case X86::ATOMMIN64:
16002     // Fall through
16003   case X86::ATOMUMAX8:
16004   case X86::ATOMUMAX16:
16005   case X86::ATOMUMAX32:
16006   case X86::ATOMUMAX64:
16007     // Fall through
16008   case X86::ATOMUMIN8:
16009   case X86::ATOMUMIN16:
16010   case X86::ATOMUMIN32:
16011   case X86::ATOMUMIN64:
16012     return EmitAtomicLoadArith(MI, BB);
16013
16014   // This group does 64-bit operations on a 32-bit host.
16015   case X86::ATOMAND6432:
16016   case X86::ATOMOR6432:
16017   case X86::ATOMXOR6432:
16018   case X86::ATOMNAND6432:
16019   case X86::ATOMADD6432:
16020   case X86::ATOMSUB6432:
16021   case X86::ATOMMAX6432:
16022   case X86::ATOMMIN6432:
16023   case X86::ATOMUMAX6432:
16024   case X86::ATOMUMIN6432:
16025   case X86::ATOMSWAP6432:
16026     return EmitAtomicLoadArith6432(MI, BB);
16027
16028   case X86::VASTART_SAVE_XMM_REGS:
16029     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16030
16031   case X86::VAARG_64:
16032     return EmitVAARG64WithCustomInserter(MI, BB);
16033
16034   case X86::EH_SjLj_SetJmp32:
16035   case X86::EH_SjLj_SetJmp64:
16036     return emitEHSjLjSetJmp(MI, BB);
16037
16038   case X86::EH_SjLj_LongJmp32:
16039   case X86::EH_SjLj_LongJmp64:
16040     return emitEHSjLjLongJmp(MI, BB);
16041   }
16042 }
16043
16044 //===----------------------------------------------------------------------===//
16045 //                           X86 Optimization Hooks
16046 //===----------------------------------------------------------------------===//
16047
16048 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16049                                                        APInt &KnownZero,
16050                                                        APInt &KnownOne,
16051                                                        const SelectionDAG &DAG,
16052                                                        unsigned Depth) const {
16053   unsigned BitWidth = KnownZero.getBitWidth();
16054   unsigned Opc = Op.getOpcode();
16055   assert((Opc >= ISD::BUILTIN_OP_END ||
16056           Opc == ISD::INTRINSIC_WO_CHAIN ||
16057           Opc == ISD::INTRINSIC_W_CHAIN ||
16058           Opc == ISD::INTRINSIC_VOID) &&
16059          "Should use MaskedValueIsZero if you don't know whether Op"
16060          " is a target node!");
16061
16062   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16063   switch (Opc) {
16064   default: break;
16065   case X86ISD::ADD:
16066   case X86ISD::SUB:
16067   case X86ISD::ADC:
16068   case X86ISD::SBB:
16069   case X86ISD::SMUL:
16070   case X86ISD::UMUL:
16071   case X86ISD::INC:
16072   case X86ISD::DEC:
16073   case X86ISD::OR:
16074   case X86ISD::XOR:
16075   case X86ISD::AND:
16076     // These nodes' second result is a boolean.
16077     if (Op.getResNo() == 0)
16078       break;
16079     // Fallthrough
16080   case X86ISD::SETCC:
16081     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16082     break;
16083   case ISD::INTRINSIC_WO_CHAIN: {
16084     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16085     unsigned NumLoBits = 0;
16086     switch (IntId) {
16087     default: break;
16088     case Intrinsic::x86_sse_movmsk_ps:
16089     case Intrinsic::x86_avx_movmsk_ps_256:
16090     case Intrinsic::x86_sse2_movmsk_pd:
16091     case Intrinsic::x86_avx_movmsk_pd_256:
16092     case Intrinsic::x86_mmx_pmovmskb:
16093     case Intrinsic::x86_sse2_pmovmskb_128:
16094     case Intrinsic::x86_avx2_pmovmskb: {
16095       // High bits of movmskp{s|d}, pmovmskb are known zero.
16096       switch (IntId) {
16097         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16098         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16099         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16100         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16101         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16102         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16103         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16104         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16105       }
16106       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16107       break;
16108     }
16109     }
16110     break;
16111   }
16112   }
16113 }
16114
16115 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16116                                                          unsigned Depth) const {
16117   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16118   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16119     return Op.getValueType().getScalarType().getSizeInBits();
16120
16121   // Fallback case.
16122   return 1;
16123 }
16124
16125 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16126 /// node is a GlobalAddress + offset.
16127 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16128                                        const GlobalValue* &GA,
16129                                        int64_t &Offset) const {
16130   if (N->getOpcode() == X86ISD::Wrapper) {
16131     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16132       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16133       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16134       return true;
16135     }
16136   }
16137   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16138 }
16139
16140 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16141 /// same as extracting the high 128-bit part of 256-bit vector and then
16142 /// inserting the result into the low part of a new 256-bit vector
16143 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16144   EVT VT = SVOp->getValueType(0);
16145   unsigned NumElems = VT.getVectorNumElements();
16146
16147   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16148   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16149     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16150         SVOp->getMaskElt(j) >= 0)
16151       return false;
16152
16153   return true;
16154 }
16155
16156 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16157 /// same as extracting the low 128-bit part of 256-bit vector and then
16158 /// inserting the result into the high part of a new 256-bit vector
16159 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16160   EVT VT = SVOp->getValueType(0);
16161   unsigned NumElems = VT.getVectorNumElements();
16162
16163   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16164   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16165     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16166         SVOp->getMaskElt(j) >= 0)
16167       return false;
16168
16169   return true;
16170 }
16171
16172 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16173 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16174                                         TargetLowering::DAGCombinerInfo &DCI,
16175                                         const X86Subtarget* Subtarget) {
16176   SDLoc dl(N);
16177   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16178   SDValue V1 = SVOp->getOperand(0);
16179   SDValue V2 = SVOp->getOperand(1);
16180   EVT VT = SVOp->getValueType(0);
16181   unsigned NumElems = VT.getVectorNumElements();
16182
16183   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16184       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16185     //
16186     //                   0,0,0,...
16187     //                      |
16188     //    V      UNDEF    BUILD_VECTOR    UNDEF
16189     //     \      /           \           /
16190     //  CONCAT_VECTOR         CONCAT_VECTOR
16191     //         \                  /
16192     //          \                /
16193     //          RESULT: V + zero extended
16194     //
16195     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16196         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16197         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16198       return SDValue();
16199
16200     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16201       return SDValue();
16202
16203     // To match the shuffle mask, the first half of the mask should
16204     // be exactly the first vector, and all the rest a splat with the
16205     // first element of the second one.
16206     for (unsigned i = 0; i != NumElems/2; ++i)
16207       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16208           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16209         return SDValue();
16210
16211     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16212     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16213       if (Ld->hasNUsesOfValue(1, 0)) {
16214         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16215         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16216         SDValue ResNode =
16217           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16218                                   array_lengthof(Ops),
16219                                   Ld->getMemoryVT(),
16220                                   Ld->getPointerInfo(),
16221                                   Ld->getAlignment(),
16222                                   false/*isVolatile*/, true/*ReadMem*/,
16223                                   false/*WriteMem*/);
16224
16225         // Make sure the newly-created LOAD is in the same position as Ld in
16226         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16227         // and update uses of Ld's output chain to use the TokenFactor.
16228         if (Ld->hasAnyUseOfValue(1)) {
16229           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16230                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16231           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16232           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16233                                  SDValue(ResNode.getNode(), 1));
16234         }
16235
16236         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16237       }
16238     }
16239
16240     // Emit a zeroed vector and insert the desired subvector on its
16241     // first half.
16242     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16243     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16244     return DCI.CombineTo(N, InsV);
16245   }
16246
16247   //===--------------------------------------------------------------------===//
16248   // Combine some shuffles into subvector extracts and inserts:
16249   //
16250
16251   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16252   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16253     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16254     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16255     return DCI.CombineTo(N, InsV);
16256   }
16257
16258   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16259   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16260     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16261     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16262     return DCI.CombineTo(N, InsV);
16263   }
16264
16265   return SDValue();
16266 }
16267
16268 /// PerformShuffleCombine - Performs several different shuffle combines.
16269 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16270                                      TargetLowering::DAGCombinerInfo &DCI,
16271                                      const X86Subtarget *Subtarget) {
16272   SDLoc dl(N);
16273   EVT VT = N->getValueType(0);
16274
16275   // Don't create instructions with illegal types after legalize types has run.
16276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16277   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16278     return SDValue();
16279
16280   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16281   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16282       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16283     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16284
16285   // Only handle 128 wide vector from here on.
16286   if (!VT.is128BitVector())
16287     return SDValue();
16288
16289   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16290   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16291   // consecutive, non-overlapping, and in the right order.
16292   SmallVector<SDValue, 16> Elts;
16293   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16294     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16295
16296   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
16297 }
16298
16299 /// PerformTruncateCombine - Converts truncate operation to
16300 /// a sequence of vector shuffle operations.
16301 /// It is possible when we truncate 256-bit vector to 128-bit vector
16302 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16303                                       TargetLowering::DAGCombinerInfo &DCI,
16304                                       const X86Subtarget *Subtarget)  {
16305   return SDValue();
16306 }
16307
16308 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16309 /// specific shuffle of a load can be folded into a single element load.
16310 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16311 /// shuffles have been customed lowered so we need to handle those here.
16312 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16313                                          TargetLowering::DAGCombinerInfo &DCI) {
16314   if (DCI.isBeforeLegalizeOps())
16315     return SDValue();
16316
16317   SDValue InVec = N->getOperand(0);
16318   SDValue EltNo = N->getOperand(1);
16319
16320   if (!isa<ConstantSDNode>(EltNo))
16321     return SDValue();
16322
16323   EVT VT = InVec.getValueType();
16324
16325   bool HasShuffleIntoBitcast = false;
16326   if (InVec.getOpcode() == ISD::BITCAST) {
16327     // Don't duplicate a load with other uses.
16328     if (!InVec.hasOneUse())
16329       return SDValue();
16330     EVT BCVT = InVec.getOperand(0).getValueType();
16331     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16332       return SDValue();
16333     InVec = InVec.getOperand(0);
16334     HasShuffleIntoBitcast = true;
16335   }
16336
16337   if (!isTargetShuffle(InVec.getOpcode()))
16338     return SDValue();
16339
16340   // Don't duplicate a load with other uses.
16341   if (!InVec.hasOneUse())
16342     return SDValue();
16343
16344   SmallVector<int, 16> ShuffleMask;
16345   bool UnaryShuffle;
16346   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16347                             UnaryShuffle))
16348     return SDValue();
16349
16350   // Select the input vector, guarding against out of range extract vector.
16351   unsigned NumElems = VT.getVectorNumElements();
16352   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16353   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16354   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16355                                          : InVec.getOperand(1);
16356
16357   // If inputs to shuffle are the same for both ops, then allow 2 uses
16358   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16359
16360   if (LdNode.getOpcode() == ISD::BITCAST) {
16361     // Don't duplicate a load with other uses.
16362     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16363       return SDValue();
16364
16365     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16366     LdNode = LdNode.getOperand(0);
16367   }
16368
16369   if (!ISD::isNormalLoad(LdNode.getNode()))
16370     return SDValue();
16371
16372   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16373
16374   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16375     return SDValue();
16376
16377   if (HasShuffleIntoBitcast) {
16378     // If there's a bitcast before the shuffle, check if the load type and
16379     // alignment is valid.
16380     unsigned Align = LN0->getAlignment();
16381     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16382     unsigned NewAlign = TLI.getDataLayout()->
16383       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16384
16385     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16386       return SDValue();
16387   }
16388
16389   // All checks match so transform back to vector_shuffle so that DAG combiner
16390   // can finish the job
16391   SDLoc dl(N);
16392
16393   // Create shuffle node taking into account the case that its a unary shuffle
16394   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16395   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16396                                  InVec.getOperand(0), Shuffle,
16397                                  &ShuffleMask[0]);
16398   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16399   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16400                      EltNo);
16401 }
16402
16403 /// Extract one bit from mask vector, like v16i1 or v8i1.
16404 /// AVX-512 feature.
16405 static SDValue ExtractBitFromMaskVector(SDNode *N, SelectionDAG &DAG) {
16406   SDValue Vec = N->getOperand(0);
16407   SDLoc dl(Vec);
16408   MVT VecVT = Vec.getSimpleValueType();
16409   SDValue Idx = N->getOperand(1);
16410   MVT EltVT = N->getSimpleValueType(0);
16411
16412   assert((VecVT.getVectorElementType() == MVT::i1 && EltVT == MVT::i8) ||
16413          "Unexpected operands in ExtractBitFromMaskVector");
16414
16415   // variable index
16416   if (!isa<ConstantSDNode>(Idx)) {
16417     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
16418     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
16419     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16420                               ExtVT.getVectorElementType(), Ext);
16421     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
16422   }
16423
16424   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
16425
16426   MVT ScalarVT = MVT::getIntegerVT(VecVT.getSizeInBits());
16427   unsigned MaxShift = VecVT.getSizeInBits() - 1;
16428   Vec = DAG.getNode(ISD::BITCAST, dl, ScalarVT, Vec);
16429   Vec = DAG.getNode(ISD::SHL, dl, ScalarVT, Vec,
16430               DAG.getConstant(MaxShift - IdxVal, ScalarVT));
16431   Vec = DAG.getNode(ISD::SRL, dl, ScalarVT, Vec,
16432     DAG.getConstant(MaxShift, ScalarVT));
16433
16434   if (VecVT == MVT::v16i1) {
16435     Vec = DAG.getNode(ISD::BITCAST, dl, MVT::i16, Vec);
16436     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Vec);
16437   }
16438   return DAG.getNode(ISD::BITCAST, dl, MVT::i8, Vec);
16439 }
16440
16441 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16442 /// generation and convert it from being a bunch of shuffles and extracts
16443 /// to a simple store and scalar loads to extract the elements.
16444 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16445                                          TargetLowering::DAGCombinerInfo &DCI) {
16446   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16447   if (NewOp.getNode())
16448     return NewOp;
16449
16450   SDValue InputVector = N->getOperand(0);
16451
16452   if (InputVector.getValueType().getVectorElementType() == MVT::i1 &&
16453       !DCI.isBeforeLegalize())
16454     return ExtractBitFromMaskVector(N, DAG);
16455
16456   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16457   // from mmx to v2i32 has a single usage.
16458   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16459       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16460       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16461     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16462                        N->getValueType(0),
16463                        InputVector.getNode()->getOperand(0));
16464
16465   // Only operate on vectors of 4 elements, where the alternative shuffling
16466   // gets to be more expensive.
16467   if (InputVector.getValueType() != MVT::v4i32)
16468     return SDValue();
16469
16470   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16471   // single use which is a sign-extend or zero-extend, and all elements are
16472   // used.
16473   SmallVector<SDNode *, 4> Uses;
16474   unsigned ExtractedElements = 0;
16475   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16476        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16477     if (UI.getUse().getResNo() != InputVector.getResNo())
16478       return SDValue();
16479
16480     SDNode *Extract = *UI;
16481     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16482       return SDValue();
16483
16484     if (Extract->getValueType(0) != MVT::i32)
16485       return SDValue();
16486     if (!Extract->hasOneUse())
16487       return SDValue();
16488     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16489         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16490       return SDValue();
16491     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16492       return SDValue();
16493
16494     // Record which element was extracted.
16495     ExtractedElements |=
16496       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16497
16498     Uses.push_back(Extract);
16499   }
16500
16501   // If not all the elements were used, this may not be worthwhile.
16502   if (ExtractedElements != 15)
16503     return SDValue();
16504
16505   // Ok, we've now decided to do the transformation.
16506   SDLoc dl(InputVector);
16507
16508   // Store the value to a temporary stack slot.
16509   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16510   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16511                             MachinePointerInfo(), false, false, 0);
16512
16513   // Replace each use (extract) with a load of the appropriate element.
16514   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16515        UE = Uses.end(); UI != UE; ++UI) {
16516     SDNode *Extract = *UI;
16517
16518     // cOMpute the element's address.
16519     SDValue Idx = Extract->getOperand(1);
16520     unsigned EltSize =
16521         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16522     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16523     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16524     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16525
16526     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16527                                      StackPtr, OffsetVal);
16528
16529     // Load the scalar.
16530     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16531                                      ScalarAddr, MachinePointerInfo(),
16532                                      false, false, false, 0);
16533
16534     // Replace the exact with the load.
16535     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16536   }
16537
16538   // The replacement was made in place; don't return anything.
16539   return SDValue();
16540 }
16541
16542 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16543 static std::pair<unsigned, bool>
16544 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16545                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16546   if (!VT.isVector())
16547     return std::make_pair(0, false);
16548
16549   bool NeedSplit = false;
16550   switch (VT.getSimpleVT().SimpleTy) {
16551   default: return std::make_pair(0, false);
16552   case MVT::v32i8:
16553   case MVT::v16i16:
16554   case MVT::v8i32:
16555     if (!Subtarget->hasAVX2())
16556       NeedSplit = true;
16557     if (!Subtarget->hasAVX())
16558       return std::make_pair(0, false);
16559     break;
16560   case MVT::v16i8:
16561   case MVT::v8i16:
16562   case MVT::v4i32:
16563     if (!Subtarget->hasSSE2())
16564       return std::make_pair(0, false);
16565   }
16566
16567   // SSE2 has only a small subset of the operations.
16568   bool hasUnsigned = Subtarget->hasSSE41() ||
16569                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16570   bool hasSigned = Subtarget->hasSSE41() ||
16571                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16572
16573   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16574
16575   unsigned Opc = 0;
16576   // Check for x CC y ? x : y.
16577   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16578       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16579     switch (CC) {
16580     default: break;
16581     case ISD::SETULT:
16582     case ISD::SETULE:
16583       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16584     case ISD::SETUGT:
16585     case ISD::SETUGE:
16586       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16587     case ISD::SETLT:
16588     case ISD::SETLE:
16589       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16590     case ISD::SETGT:
16591     case ISD::SETGE:
16592       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16593     }
16594   // Check for x CC y ? y : x -- a min/max with reversed arms.
16595   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16596              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16597     switch (CC) {
16598     default: break;
16599     case ISD::SETULT:
16600     case ISD::SETULE:
16601       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16602     case ISD::SETUGT:
16603     case ISD::SETUGE:
16604       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16605     case ISD::SETLT:
16606     case ISD::SETLE:
16607       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16608     case ISD::SETGT:
16609     case ISD::SETGE:
16610       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16611     }
16612   }
16613
16614   return std::make_pair(Opc, NeedSplit);
16615 }
16616
16617 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16618 /// nodes.
16619 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16620                                     TargetLowering::DAGCombinerInfo &DCI,
16621                                     const X86Subtarget *Subtarget) {
16622   SDLoc DL(N);
16623   SDValue Cond = N->getOperand(0);
16624   // Get the LHS/RHS of the select.
16625   SDValue LHS = N->getOperand(1);
16626   SDValue RHS = N->getOperand(2);
16627   EVT VT = LHS.getValueType();
16628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16629
16630   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16631   // instructions match the semantics of the common C idiom x<y?x:y but not
16632   // x<=y?x:y, because of how they handle negative zero (which can be
16633   // ignored in unsafe-math mode).
16634   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16635       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16636       (Subtarget->hasSSE2() ||
16637        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16638     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16639
16640     unsigned Opcode = 0;
16641     // Check for x CC y ? x : y.
16642     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16643         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16644       switch (CC) {
16645       default: break;
16646       case ISD::SETULT:
16647         // Converting this to a min would handle NaNs incorrectly, and swapping
16648         // the operands would cause it to handle comparisons between positive
16649         // and negative zero incorrectly.
16650         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16651           if (!DAG.getTarget().Options.UnsafeFPMath &&
16652               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16653             break;
16654           std::swap(LHS, RHS);
16655         }
16656         Opcode = X86ISD::FMIN;
16657         break;
16658       case ISD::SETOLE:
16659         // Converting this to a min would handle comparisons between positive
16660         // and negative zero incorrectly.
16661         if (!DAG.getTarget().Options.UnsafeFPMath &&
16662             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16663           break;
16664         Opcode = X86ISD::FMIN;
16665         break;
16666       case ISD::SETULE:
16667         // Converting this to a min would handle both negative zeros and NaNs
16668         // incorrectly, but we can swap the operands to fix both.
16669         std::swap(LHS, RHS);
16670       case ISD::SETOLT:
16671       case ISD::SETLT:
16672       case ISD::SETLE:
16673         Opcode = X86ISD::FMIN;
16674         break;
16675
16676       case ISD::SETOGE:
16677         // Converting this to a max would handle comparisons between positive
16678         // and negative zero incorrectly.
16679         if (!DAG.getTarget().Options.UnsafeFPMath &&
16680             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16681           break;
16682         Opcode = X86ISD::FMAX;
16683         break;
16684       case ISD::SETUGT:
16685         // Converting this to a max would handle NaNs incorrectly, and swapping
16686         // the operands would cause it to handle comparisons between positive
16687         // and negative zero incorrectly.
16688         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16689           if (!DAG.getTarget().Options.UnsafeFPMath &&
16690               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16691             break;
16692           std::swap(LHS, RHS);
16693         }
16694         Opcode = X86ISD::FMAX;
16695         break;
16696       case ISD::SETUGE:
16697         // Converting this to a max would handle both negative zeros and NaNs
16698         // incorrectly, but we can swap the operands to fix both.
16699         std::swap(LHS, RHS);
16700       case ISD::SETOGT:
16701       case ISD::SETGT:
16702       case ISD::SETGE:
16703         Opcode = X86ISD::FMAX;
16704         break;
16705       }
16706     // Check for x CC y ? y : x -- a min/max with reversed arms.
16707     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16708                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16709       switch (CC) {
16710       default: break;
16711       case ISD::SETOGE:
16712         // Converting this to a min would handle comparisons between positive
16713         // and negative zero incorrectly, and swapping the operands would
16714         // cause it to handle NaNs incorrectly.
16715         if (!DAG.getTarget().Options.UnsafeFPMath &&
16716             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16717           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16718             break;
16719           std::swap(LHS, RHS);
16720         }
16721         Opcode = X86ISD::FMIN;
16722         break;
16723       case ISD::SETUGT:
16724         // Converting this to a min would handle NaNs incorrectly.
16725         if (!DAG.getTarget().Options.UnsafeFPMath &&
16726             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16727           break;
16728         Opcode = X86ISD::FMIN;
16729         break;
16730       case ISD::SETUGE:
16731         // Converting this to a min would handle both negative zeros and NaNs
16732         // incorrectly, but we can swap the operands to fix both.
16733         std::swap(LHS, RHS);
16734       case ISD::SETOGT:
16735       case ISD::SETGT:
16736       case ISD::SETGE:
16737         Opcode = X86ISD::FMIN;
16738         break;
16739
16740       case ISD::SETULT:
16741         // Converting this to a max would handle NaNs incorrectly.
16742         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16743           break;
16744         Opcode = X86ISD::FMAX;
16745         break;
16746       case ISD::SETOLE:
16747         // Converting this to a max would handle comparisons between positive
16748         // and negative zero incorrectly, and swapping the operands would
16749         // cause it to handle NaNs incorrectly.
16750         if (!DAG.getTarget().Options.UnsafeFPMath &&
16751             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16752           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16753             break;
16754           std::swap(LHS, RHS);
16755         }
16756         Opcode = X86ISD::FMAX;
16757         break;
16758       case ISD::SETULE:
16759         // Converting this to a max would handle both negative zeros and NaNs
16760         // incorrectly, but we can swap the operands to fix both.
16761         std::swap(LHS, RHS);
16762       case ISD::SETOLT:
16763       case ISD::SETLT:
16764       case ISD::SETLE:
16765         Opcode = X86ISD::FMAX;
16766         break;
16767       }
16768     }
16769
16770     if (Opcode)
16771       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16772   }
16773
16774   EVT CondVT = Cond.getValueType();
16775   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
16776       CondVT.getVectorElementType() == MVT::i1) {
16777     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16778     // lowering on AVX-512. In this case we convert it to
16779     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16780     // The same situation for all 128 and 256-bit vectors of i8 and i16
16781     EVT OpVT = LHS.getValueType();
16782     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16783         (OpVT.getVectorElementType() == MVT::i8 ||
16784          OpVT.getVectorElementType() == MVT::i16)) {
16785       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16786       DCI.AddToWorklist(Cond.getNode());
16787       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16788     }
16789   }
16790   // If this is a select between two integer constants, try to do some
16791   // optimizations.
16792   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16793     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16794       // Don't do this for crazy integer types.
16795       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16796         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16797         // so that TrueC (the true value) is larger than FalseC.
16798         bool NeedsCondInvert = false;
16799
16800         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16801             // Efficiently invertible.
16802             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16803              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16804               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16805           NeedsCondInvert = true;
16806           std::swap(TrueC, FalseC);
16807         }
16808
16809         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16810         if (FalseC->getAPIntValue() == 0 &&
16811             TrueC->getAPIntValue().isPowerOf2()) {
16812           if (NeedsCondInvert) // Invert the condition if needed.
16813             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16814                                DAG.getConstant(1, Cond.getValueType()));
16815
16816           // Zero extend the condition if needed.
16817           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16818
16819           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16820           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16821                              DAG.getConstant(ShAmt, MVT::i8));
16822         }
16823
16824         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16825         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16826           if (NeedsCondInvert) // Invert the condition if needed.
16827             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16828                                DAG.getConstant(1, Cond.getValueType()));
16829
16830           // Zero extend the condition if needed.
16831           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16832                              FalseC->getValueType(0), Cond);
16833           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16834                              SDValue(FalseC, 0));
16835         }
16836
16837         // Optimize cases that will turn into an LEA instruction.  This requires
16838         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16839         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16840           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16841           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16842
16843           bool isFastMultiplier = false;
16844           if (Diff < 10) {
16845             switch ((unsigned char)Diff) {
16846               default: break;
16847               case 1:  // result = add base, cond
16848               case 2:  // result = lea base(    , cond*2)
16849               case 3:  // result = lea base(cond, cond*2)
16850               case 4:  // result = lea base(    , cond*4)
16851               case 5:  // result = lea base(cond, cond*4)
16852               case 8:  // result = lea base(    , cond*8)
16853               case 9:  // result = lea base(cond, cond*8)
16854                 isFastMultiplier = true;
16855                 break;
16856             }
16857           }
16858
16859           if (isFastMultiplier) {
16860             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16861             if (NeedsCondInvert) // Invert the condition if needed.
16862               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16863                                  DAG.getConstant(1, Cond.getValueType()));
16864
16865             // Zero extend the condition if needed.
16866             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16867                                Cond);
16868             // Scale the condition by the difference.
16869             if (Diff != 1)
16870               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16871                                  DAG.getConstant(Diff, Cond.getValueType()));
16872
16873             // Add the base if non-zero.
16874             if (FalseC->getAPIntValue() != 0)
16875               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16876                                  SDValue(FalseC, 0));
16877             return Cond;
16878           }
16879         }
16880       }
16881   }
16882
16883   // Canonicalize max and min:
16884   // (x > y) ? x : y -> (x >= y) ? x : y
16885   // (x < y) ? x : y -> (x <= y) ? x : y
16886   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16887   // the need for an extra compare
16888   // against zero. e.g.
16889   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16890   // subl   %esi, %edi
16891   // testl  %edi, %edi
16892   // movl   $0, %eax
16893   // cmovgl %edi, %eax
16894   // =>
16895   // xorl   %eax, %eax
16896   // subl   %esi, $edi
16897   // cmovsl %eax, %edi
16898   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16899       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16900       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16901     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16902     switch (CC) {
16903     default: break;
16904     case ISD::SETLT:
16905     case ISD::SETGT: {
16906       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16907       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16908                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16909       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16910     }
16911     }
16912   }
16913
16914   // Early exit check
16915   if (!TLI.isTypeLegal(VT))
16916     return SDValue();
16917
16918   // Match VSELECTs into subs with unsigned saturation.
16919   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16920       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16921       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16922        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16923     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16924
16925     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16926     // left side invert the predicate to simplify logic below.
16927     SDValue Other;
16928     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16929       Other = RHS;
16930       CC = ISD::getSetCCInverse(CC, true);
16931     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16932       Other = LHS;
16933     }
16934
16935     if (Other.getNode() && Other->getNumOperands() == 2 &&
16936         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16937       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16938       SDValue CondRHS = Cond->getOperand(1);
16939
16940       // Look for a general sub with unsigned saturation first.
16941       // x >= y ? x-y : 0 --> subus x, y
16942       // x >  y ? x-y : 0 --> subus x, y
16943       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16944           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16945         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16946
16947       // If the RHS is a constant we have to reverse the const canonicalization.
16948       // x > C-1 ? x+-C : 0 --> subus x, C
16949       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16950           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16951         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16952         if (CondRHS.getConstantOperandVal(0) == -A-1)
16953           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16954                              DAG.getConstant(-A, VT));
16955       }
16956
16957       // Another special case: If C was a sign bit, the sub has been
16958       // canonicalized into a xor.
16959       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16960       //        it's safe to decanonicalize the xor?
16961       // x s< 0 ? x^C : 0 --> subus x, C
16962       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16963           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16964           isSplatVector(OpRHS.getNode())) {
16965         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16966         if (A.isSignBit())
16967           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16968       }
16969     }
16970   }
16971
16972   // Try to match a min/max vector operation.
16973   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
16974     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
16975     unsigned Opc = ret.first;
16976     bool NeedSplit = ret.second;
16977
16978     if (Opc && NeedSplit) {
16979       unsigned NumElems = VT.getVectorNumElements();
16980       // Extract the LHS vectors
16981       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
16982       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
16983
16984       // Extract the RHS vectors
16985       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
16986       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
16987
16988       // Create min/max for each subvector
16989       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
16990       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
16991
16992       // Merge the result
16993       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
16994     } else if (Opc)
16995       return DAG.getNode(Opc, DL, VT, LHS, RHS);
16996   }
16997
16998   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16999   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17000       // Check if SETCC has already been promoted
17001       TLI.getSetCCResultType(*DAG.getContext(), VT) == Cond.getValueType()) {
17002
17003     assert(Cond.getValueType().isVector() &&
17004            "vector select expects a vector selector!");
17005
17006     EVT IntVT = Cond.getValueType();
17007     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17008     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17009
17010     if (!TValIsAllOnes && !FValIsAllZeros) {
17011       // Try invert the condition if true value is not all 1s and false value
17012       // is not all 0s.
17013       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17014       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17015
17016       if (TValIsAllZeros || FValIsAllOnes) {
17017         SDValue CC = Cond.getOperand(2);
17018         ISD::CondCode NewCC =
17019           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17020                                Cond.getOperand(0).getValueType().isInteger());
17021         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17022         std::swap(LHS, RHS);
17023         TValIsAllOnes = FValIsAllOnes;
17024         FValIsAllZeros = TValIsAllZeros;
17025       }
17026     }
17027
17028     if (TValIsAllOnes || FValIsAllZeros) {
17029       SDValue Ret;
17030
17031       if (TValIsAllOnes && FValIsAllZeros)
17032         Ret = Cond;
17033       else if (TValIsAllOnes)
17034         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
17035                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
17036       else if (FValIsAllZeros)
17037         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
17038                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
17039
17040       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17041     }
17042   }
17043
17044   // If we know that this node is legal then we know that it is going to be
17045   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17046   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17047   // to simplify previous instructions.
17048   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17049       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17050     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17051
17052     // Don't optimize vector selects that map to mask-registers.
17053     if (BitWidth == 1)
17054       return SDValue();
17055
17056     // Check all uses of that condition operand to check whether it will be
17057     // consumed by non-BLEND instructions, which may depend on all bits are set
17058     // properly.
17059     for (SDNode::use_iterator I = Cond->use_begin(),
17060                               E = Cond->use_end(); I != E; ++I)
17061       if (I->getOpcode() != ISD::VSELECT)
17062         // TODO: Add other opcodes eventually lowered into BLEND.
17063         return SDValue();
17064
17065     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17066     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17067
17068     APInt KnownZero, KnownOne;
17069     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17070                                           DCI.isBeforeLegalizeOps());
17071     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17072         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17073       DCI.CommitTargetLoweringOpt(TLO);
17074   }
17075
17076   return SDValue();
17077 }
17078
17079 // Check whether a boolean test is testing a boolean value generated by
17080 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17081 // code.
17082 //
17083 // Simplify the following patterns:
17084 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17085 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17086 // to (Op EFLAGS Cond)
17087 //
17088 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17089 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17090 // to (Op EFLAGS !Cond)
17091 //
17092 // where Op could be BRCOND or CMOV.
17093 //
17094 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17095   // Quit if not CMP and SUB with its value result used.
17096   if (Cmp.getOpcode() != X86ISD::CMP &&
17097       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17098       return SDValue();
17099
17100   // Quit if not used as a boolean value.
17101   if (CC != X86::COND_E && CC != X86::COND_NE)
17102     return SDValue();
17103
17104   // Check CMP operands. One of them should be 0 or 1 and the other should be
17105   // an SetCC or extended from it.
17106   SDValue Op1 = Cmp.getOperand(0);
17107   SDValue Op2 = Cmp.getOperand(1);
17108
17109   SDValue SetCC;
17110   const ConstantSDNode* C = 0;
17111   bool needOppositeCond = (CC == X86::COND_E);
17112   bool checkAgainstTrue = false; // Is it a comparison against 1?
17113
17114   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17115     SetCC = Op2;
17116   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17117     SetCC = Op1;
17118   else // Quit if all operands are not constants.
17119     return SDValue();
17120
17121   if (C->getZExtValue() == 1) {
17122     needOppositeCond = !needOppositeCond;
17123     checkAgainstTrue = true;
17124   } else if (C->getZExtValue() != 0)
17125     // Quit if the constant is neither 0 or 1.
17126     return SDValue();
17127
17128   bool truncatedToBoolWithAnd = false;
17129   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17130   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17131          SetCC.getOpcode() == ISD::TRUNCATE ||
17132          SetCC.getOpcode() == ISD::AND) {
17133     if (SetCC.getOpcode() == ISD::AND) {
17134       int OpIdx = -1;
17135       ConstantSDNode *CS;
17136       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17137           CS->getZExtValue() == 1)
17138         OpIdx = 1;
17139       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17140           CS->getZExtValue() == 1)
17141         OpIdx = 0;
17142       if (OpIdx == -1)
17143         break;
17144       SetCC = SetCC.getOperand(OpIdx);
17145       truncatedToBoolWithAnd = true;
17146     } else
17147       SetCC = SetCC.getOperand(0);
17148   }
17149
17150   switch (SetCC.getOpcode()) {
17151   case X86ISD::SETCC_CARRY:
17152     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17153     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17154     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17155     // truncated to i1 using 'and'.
17156     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17157       break;
17158     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17159            "Invalid use of SETCC_CARRY!");
17160     // FALL THROUGH
17161   case X86ISD::SETCC:
17162     // Set the condition code or opposite one if necessary.
17163     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17164     if (needOppositeCond)
17165       CC = X86::GetOppositeBranchCondition(CC);
17166     return SetCC.getOperand(1);
17167   case X86ISD::CMOV: {
17168     // Check whether false/true value has canonical one, i.e. 0 or 1.
17169     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17170     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17171     // Quit if true value is not a constant.
17172     if (!TVal)
17173       return SDValue();
17174     // Quit if false value is not a constant.
17175     if (!FVal) {
17176       SDValue Op = SetCC.getOperand(0);
17177       // Skip 'zext' or 'trunc' node.
17178       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17179           Op.getOpcode() == ISD::TRUNCATE)
17180         Op = Op.getOperand(0);
17181       // A special case for rdrand/rdseed, where 0 is set if false cond is
17182       // found.
17183       if ((Op.getOpcode() != X86ISD::RDRAND &&
17184            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17185         return SDValue();
17186     }
17187     // Quit if false value is not the constant 0 or 1.
17188     bool FValIsFalse = true;
17189     if (FVal && FVal->getZExtValue() != 0) {
17190       if (FVal->getZExtValue() != 1)
17191         return SDValue();
17192       // If FVal is 1, opposite cond is needed.
17193       needOppositeCond = !needOppositeCond;
17194       FValIsFalse = false;
17195     }
17196     // Quit if TVal is not the constant opposite of FVal.
17197     if (FValIsFalse && TVal->getZExtValue() != 1)
17198       return SDValue();
17199     if (!FValIsFalse && TVal->getZExtValue() != 0)
17200       return SDValue();
17201     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17202     if (needOppositeCond)
17203       CC = X86::GetOppositeBranchCondition(CC);
17204     return SetCC.getOperand(3);
17205   }
17206   }
17207
17208   return SDValue();
17209 }
17210
17211 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17212 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17213                                   TargetLowering::DAGCombinerInfo &DCI,
17214                                   const X86Subtarget *Subtarget) {
17215   SDLoc DL(N);
17216
17217   // If the flag operand isn't dead, don't touch this CMOV.
17218   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17219     return SDValue();
17220
17221   SDValue FalseOp = N->getOperand(0);
17222   SDValue TrueOp = N->getOperand(1);
17223   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17224   SDValue Cond = N->getOperand(3);
17225
17226   if (CC == X86::COND_E || CC == X86::COND_NE) {
17227     switch (Cond.getOpcode()) {
17228     default: break;
17229     case X86ISD::BSR:
17230     case X86ISD::BSF:
17231       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17232       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17233         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17234     }
17235   }
17236
17237   SDValue Flags;
17238
17239   Flags = checkBoolTestSetCCCombine(Cond, CC);
17240   if (Flags.getNode() &&
17241       // Extra check as FCMOV only supports a subset of X86 cond.
17242       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17243     SDValue Ops[] = { FalseOp, TrueOp,
17244                       DAG.getConstant(CC, MVT::i8), Flags };
17245     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17246                        Ops, array_lengthof(Ops));
17247   }
17248
17249   // If this is a select between two integer constants, try to do some
17250   // optimizations.  Note that the operands are ordered the opposite of SELECT
17251   // operands.
17252   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17253     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17254       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17255       // larger than FalseC (the false value).
17256       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17257         CC = X86::GetOppositeBranchCondition(CC);
17258         std::swap(TrueC, FalseC);
17259         std::swap(TrueOp, FalseOp);
17260       }
17261
17262       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17263       // This is efficient for any integer data type (including i8/i16) and
17264       // shift amount.
17265       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17266         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17267                            DAG.getConstant(CC, MVT::i8), Cond);
17268
17269         // Zero extend the condition if needed.
17270         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17271
17272         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17273         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17274                            DAG.getConstant(ShAmt, MVT::i8));
17275         if (N->getNumValues() == 2)  // Dead flag value?
17276           return DCI.CombineTo(N, Cond, SDValue());
17277         return Cond;
17278       }
17279
17280       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17281       // for any integer data type, including i8/i16.
17282       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17283         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17284                            DAG.getConstant(CC, MVT::i8), Cond);
17285
17286         // Zero extend the condition if needed.
17287         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17288                            FalseC->getValueType(0), Cond);
17289         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17290                            SDValue(FalseC, 0));
17291
17292         if (N->getNumValues() == 2)  // Dead flag value?
17293           return DCI.CombineTo(N, Cond, SDValue());
17294         return Cond;
17295       }
17296
17297       // Optimize cases that will turn into an LEA instruction.  This requires
17298       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17299       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17300         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17301         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17302
17303         bool isFastMultiplier = false;
17304         if (Diff < 10) {
17305           switch ((unsigned char)Diff) {
17306           default: break;
17307           case 1:  // result = add base, cond
17308           case 2:  // result = lea base(    , cond*2)
17309           case 3:  // result = lea base(cond, cond*2)
17310           case 4:  // result = lea base(    , cond*4)
17311           case 5:  // result = lea base(cond, cond*4)
17312           case 8:  // result = lea base(    , cond*8)
17313           case 9:  // result = lea base(cond, cond*8)
17314             isFastMultiplier = true;
17315             break;
17316           }
17317         }
17318
17319         if (isFastMultiplier) {
17320           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17321           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17322                              DAG.getConstant(CC, MVT::i8), Cond);
17323           // Zero extend the condition if needed.
17324           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17325                              Cond);
17326           // Scale the condition by the difference.
17327           if (Diff != 1)
17328             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17329                                DAG.getConstant(Diff, Cond.getValueType()));
17330
17331           // Add the base if non-zero.
17332           if (FalseC->getAPIntValue() != 0)
17333             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17334                                SDValue(FalseC, 0));
17335           if (N->getNumValues() == 2)  // Dead flag value?
17336             return DCI.CombineTo(N, Cond, SDValue());
17337           return Cond;
17338         }
17339       }
17340     }
17341   }
17342
17343   // Handle these cases:
17344   //   (select (x != c), e, c) -> select (x != c), e, x),
17345   //   (select (x == c), c, e) -> select (x == c), x, e)
17346   // where the c is an integer constant, and the "select" is the combination
17347   // of CMOV and CMP.
17348   //
17349   // The rationale for this change is that the conditional-move from a constant
17350   // needs two instructions, however, conditional-move from a register needs
17351   // only one instruction.
17352   //
17353   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17354   //  some instruction-combining opportunities. This opt needs to be
17355   //  postponed as late as possible.
17356   //
17357   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17358     // the DCI.xxxx conditions are provided to postpone the optimization as
17359     // late as possible.
17360
17361     ConstantSDNode *CmpAgainst = 0;
17362     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17363         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17364         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17365
17366       if (CC == X86::COND_NE &&
17367           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17368         CC = X86::GetOppositeBranchCondition(CC);
17369         std::swap(TrueOp, FalseOp);
17370       }
17371
17372       if (CC == X86::COND_E &&
17373           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17374         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17375                           DAG.getConstant(CC, MVT::i8), Cond };
17376         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17377                            array_lengthof(Ops));
17378       }
17379     }
17380   }
17381
17382   return SDValue();
17383 }
17384
17385 /// PerformMulCombine - Optimize a single multiply with constant into two
17386 /// in order to implement it with two cheaper instructions, e.g.
17387 /// LEA + SHL, LEA + LEA.
17388 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17389                                  TargetLowering::DAGCombinerInfo &DCI) {
17390   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17391     return SDValue();
17392
17393   EVT VT = N->getValueType(0);
17394   if (VT != MVT::i64)
17395     return SDValue();
17396
17397   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17398   if (!C)
17399     return SDValue();
17400   uint64_t MulAmt = C->getZExtValue();
17401   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17402     return SDValue();
17403
17404   uint64_t MulAmt1 = 0;
17405   uint64_t MulAmt2 = 0;
17406   if ((MulAmt % 9) == 0) {
17407     MulAmt1 = 9;
17408     MulAmt2 = MulAmt / 9;
17409   } else if ((MulAmt % 5) == 0) {
17410     MulAmt1 = 5;
17411     MulAmt2 = MulAmt / 5;
17412   } else if ((MulAmt % 3) == 0) {
17413     MulAmt1 = 3;
17414     MulAmt2 = MulAmt / 3;
17415   }
17416   if (MulAmt2 &&
17417       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17418     SDLoc DL(N);
17419
17420     if (isPowerOf2_64(MulAmt2) &&
17421         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17422       // If second multiplifer is pow2, issue it first. We want the multiply by
17423       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17424       // is an add.
17425       std::swap(MulAmt1, MulAmt2);
17426
17427     SDValue NewMul;
17428     if (isPowerOf2_64(MulAmt1))
17429       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17430                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17431     else
17432       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17433                            DAG.getConstant(MulAmt1, VT));
17434
17435     if (isPowerOf2_64(MulAmt2))
17436       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17437                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17438     else
17439       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17440                            DAG.getConstant(MulAmt2, VT));
17441
17442     // Do not add new nodes to DAG combiner worklist.
17443     DCI.CombineTo(N, NewMul, false);
17444   }
17445   return SDValue();
17446 }
17447
17448 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17449   SDValue N0 = N->getOperand(0);
17450   SDValue N1 = N->getOperand(1);
17451   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17452   EVT VT = N0.getValueType();
17453
17454   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17455   // since the result of setcc_c is all zero's or all ones.
17456   if (VT.isInteger() && !VT.isVector() &&
17457       N1C && N0.getOpcode() == ISD::AND &&
17458       N0.getOperand(1).getOpcode() == ISD::Constant) {
17459     SDValue N00 = N0.getOperand(0);
17460     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17461         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17462           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17463          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17464       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17465       APInt ShAmt = N1C->getAPIntValue();
17466       Mask = Mask.shl(ShAmt);
17467       if (Mask != 0)
17468         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17469                            N00, DAG.getConstant(Mask, VT));
17470     }
17471   }
17472
17473   // Hardware support for vector shifts is sparse which makes us scalarize the
17474   // vector operations in many cases. Also, on sandybridge ADD is faster than
17475   // shl.
17476   // (shl V, 1) -> add V,V
17477   if (isSplatVector(N1.getNode())) {
17478     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17479     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17480     // We shift all of the values by one. In many cases we do not have
17481     // hardware support for this operation. This is better expressed as an ADD
17482     // of two values.
17483     if (N1C && (1 == N1C->getZExtValue())) {
17484       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17485     }
17486   }
17487
17488   return SDValue();
17489 }
17490
17491 /// \brief Returns a vector of 0s if the node in input is a vector logical
17492 /// shift by a constant amount which is known to be bigger than or equal
17493 /// to the vector element size in bits.
17494 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17495                                       const X86Subtarget *Subtarget) {
17496   EVT VT = N->getValueType(0);
17497
17498   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17499       (!Subtarget->hasInt256() ||
17500        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17501     return SDValue();
17502
17503   SDValue Amt = N->getOperand(1);
17504   SDLoc DL(N);
17505   if (isSplatVector(Amt.getNode())) {
17506     SDValue SclrAmt = Amt->getOperand(0);
17507     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17508       APInt ShiftAmt = C->getAPIntValue();
17509       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17510
17511       // SSE2/AVX2 logical shifts always return a vector of 0s
17512       // if the shift amount is bigger than or equal to
17513       // the element size. The constant shift amount will be
17514       // encoded as a 8-bit immediate.
17515       if (ShiftAmt.trunc(8).uge(MaxAmount))
17516         return getZeroVector(VT, Subtarget, DAG, DL);
17517     }
17518   }
17519
17520   return SDValue();
17521 }
17522
17523 /// PerformShiftCombine - Combine shifts.
17524 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17525                                    TargetLowering::DAGCombinerInfo &DCI,
17526                                    const X86Subtarget *Subtarget) {
17527   if (N->getOpcode() == ISD::SHL) {
17528     SDValue V = PerformSHLCombine(N, DAG);
17529     if (V.getNode()) return V;
17530   }
17531
17532   if (N->getOpcode() != ISD::SRA) {
17533     // Try to fold this logical shift into a zero vector.
17534     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17535     if (V.getNode()) return V;
17536   }
17537
17538   return SDValue();
17539 }
17540
17541 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17542 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17543 // and friends.  Likewise for OR -> CMPNEQSS.
17544 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17545                             TargetLowering::DAGCombinerInfo &DCI,
17546                             const X86Subtarget *Subtarget) {
17547   unsigned opcode;
17548
17549   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17550   // we're requiring SSE2 for both.
17551   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17552     SDValue N0 = N->getOperand(0);
17553     SDValue N1 = N->getOperand(1);
17554     SDValue CMP0 = N0->getOperand(1);
17555     SDValue CMP1 = N1->getOperand(1);
17556     SDLoc DL(N);
17557
17558     // The SETCCs should both refer to the same CMP.
17559     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17560       return SDValue();
17561
17562     SDValue CMP00 = CMP0->getOperand(0);
17563     SDValue CMP01 = CMP0->getOperand(1);
17564     EVT     VT    = CMP00.getValueType();
17565
17566     if (VT == MVT::f32 || VT == MVT::f64) {
17567       bool ExpectingFlags = false;
17568       // Check for any users that want flags:
17569       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17570            !ExpectingFlags && UI != UE; ++UI)
17571         switch (UI->getOpcode()) {
17572         default:
17573         case ISD::BR_CC:
17574         case ISD::BRCOND:
17575         case ISD::SELECT:
17576           ExpectingFlags = true;
17577           break;
17578         case ISD::CopyToReg:
17579         case ISD::SIGN_EXTEND:
17580         case ISD::ZERO_EXTEND:
17581         case ISD::ANY_EXTEND:
17582           break;
17583         }
17584
17585       if (!ExpectingFlags) {
17586         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17587         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17588
17589         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17590           X86::CondCode tmp = cc0;
17591           cc0 = cc1;
17592           cc1 = tmp;
17593         }
17594
17595         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17596             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17597           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17598           X86ISD::NodeType NTOperator = is64BitFP ?
17599             X86ISD::FSETCCsd : X86ISD::FSETCCss;
17600           // FIXME: need symbolic constants for these magic numbers.
17601           // See X86ATTInstPrinter.cpp:printSSECC().
17602           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17603           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
17604                                               DAG.getConstant(x86cc, MVT::i8));
17605           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
17606                                               OnesOrZeroesF);
17607           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
17608                                       DAG.getConstant(1, MVT::i32));
17609           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17610           return OneBitOfTruth;
17611         }
17612       }
17613     }
17614   }
17615   return SDValue();
17616 }
17617
17618 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17619 /// so it can be folded inside ANDNP.
17620 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17621   EVT VT = N->getValueType(0);
17622
17623   // Match direct AllOnes for 128 and 256-bit vectors
17624   if (ISD::isBuildVectorAllOnes(N))
17625     return true;
17626
17627   // Look through a bit convert.
17628   if (N->getOpcode() == ISD::BITCAST)
17629     N = N->getOperand(0).getNode();
17630
17631   // Sometimes the operand may come from a insert_subvector building a 256-bit
17632   // allones vector
17633   if (VT.is256BitVector() &&
17634       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17635     SDValue V1 = N->getOperand(0);
17636     SDValue V2 = N->getOperand(1);
17637
17638     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17639         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17640         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17641         ISD::isBuildVectorAllOnes(V2.getNode()))
17642       return true;
17643   }
17644
17645   return false;
17646 }
17647
17648 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17649 // register. In most cases we actually compare or select YMM-sized registers
17650 // and mixing the two types creates horrible code. This method optimizes
17651 // some of the transition sequences.
17652 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17653                                  TargetLowering::DAGCombinerInfo &DCI,
17654                                  const X86Subtarget *Subtarget) {
17655   EVT VT = N->getValueType(0);
17656   if (!VT.is256BitVector())
17657     return SDValue();
17658
17659   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17660           N->getOpcode() == ISD::ZERO_EXTEND ||
17661           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17662
17663   SDValue Narrow = N->getOperand(0);
17664   EVT NarrowVT = Narrow->getValueType(0);
17665   if (!NarrowVT.is128BitVector())
17666     return SDValue();
17667
17668   if (Narrow->getOpcode() != ISD::XOR &&
17669       Narrow->getOpcode() != ISD::AND &&
17670       Narrow->getOpcode() != ISD::OR)
17671     return SDValue();
17672
17673   SDValue N0  = Narrow->getOperand(0);
17674   SDValue N1  = Narrow->getOperand(1);
17675   SDLoc DL(Narrow);
17676
17677   // The Left side has to be a trunc.
17678   if (N0.getOpcode() != ISD::TRUNCATE)
17679     return SDValue();
17680
17681   // The type of the truncated inputs.
17682   EVT WideVT = N0->getOperand(0)->getValueType(0);
17683   if (WideVT != VT)
17684     return SDValue();
17685
17686   // The right side has to be a 'trunc' or a constant vector.
17687   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17688   bool RHSConst = (isSplatVector(N1.getNode()) &&
17689                    isa<ConstantSDNode>(N1->getOperand(0)));
17690   if (!RHSTrunc && !RHSConst)
17691     return SDValue();
17692
17693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17694
17695   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17696     return SDValue();
17697
17698   // Set N0 and N1 to hold the inputs to the new wide operation.
17699   N0 = N0->getOperand(0);
17700   if (RHSConst) {
17701     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17702                      N1->getOperand(0));
17703     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17704     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17705   } else if (RHSTrunc) {
17706     N1 = N1->getOperand(0);
17707   }
17708
17709   // Generate the wide operation.
17710   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17711   unsigned Opcode = N->getOpcode();
17712   switch (Opcode) {
17713   case ISD::ANY_EXTEND:
17714     return Op;
17715   case ISD::ZERO_EXTEND: {
17716     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17717     APInt Mask = APInt::getAllOnesValue(InBits);
17718     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17719     return DAG.getNode(ISD::AND, DL, VT,
17720                        Op, DAG.getConstant(Mask, VT));
17721   }
17722   case ISD::SIGN_EXTEND:
17723     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17724                        Op, DAG.getValueType(NarrowVT));
17725   default:
17726     llvm_unreachable("Unexpected opcode");
17727   }
17728 }
17729
17730 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17731                                  TargetLowering::DAGCombinerInfo &DCI,
17732                                  const X86Subtarget *Subtarget) {
17733   EVT VT = N->getValueType(0);
17734   if (DCI.isBeforeLegalizeOps())
17735     return SDValue();
17736
17737   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17738   if (R.getNode())
17739     return R;
17740
17741   // Create BLSI, BLSR, and BZHI instructions
17742   // BLSI is X & (-X)
17743   // BLSR is X & (X-1)
17744   // BZHI is X & ((1 << Y) - 1)
17745   // BEXTR is ((X >> imm) & (2**size-1))
17746   if (VT == MVT::i32 || VT == MVT::i64) {
17747     SDValue N0 = N->getOperand(0);
17748     SDValue N1 = N->getOperand(1);
17749     SDLoc DL(N);
17750
17751     if (Subtarget->hasBMI()) {
17752       // Check LHS for neg
17753       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17754           isZero(N0.getOperand(0)))
17755         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17756
17757       // Check RHS for neg
17758       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17759           isZero(N1.getOperand(0)))
17760         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17761
17762       // Check LHS for X-1
17763       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17764           isAllOnes(N0.getOperand(1)))
17765         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17766
17767       // Check RHS for X-1
17768       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17769           isAllOnes(N1.getOperand(1)))
17770         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17771     }
17772
17773     if (Subtarget->hasBMI2()) {
17774       // Check for (and (add (shl 1, Y), -1), X)
17775       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17776         SDValue N00 = N0.getOperand(0);
17777         if (N00.getOpcode() == ISD::SHL) {
17778           SDValue N001 = N00.getOperand(1);
17779           assert(N001.getValueType() == MVT::i8 && "unexpected type");
17780           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17781           if (C && C->getZExtValue() == 1)
17782             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17783         }
17784       }
17785
17786       // Check for (and X, (add (shl 1, Y), -1))
17787       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17788         SDValue N10 = N1.getOperand(0);
17789         if (N10.getOpcode() == ISD::SHL) {
17790           SDValue N101 = N10.getOperand(1);
17791           assert(N101.getValueType() == MVT::i8 && "unexpected type");
17792           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17793           if (C && C->getZExtValue() == 1)
17794             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17795         }
17796       }
17797     }
17798
17799     // Check for BEXTR.
17800     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
17801         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
17802       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17803       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17804       if (MaskNode && ShiftNode) {
17805         uint64_t Mask = MaskNode->getZExtValue();
17806         uint64_t Shift = ShiftNode->getZExtValue();
17807         if (isMask_64(Mask)) {
17808           uint64_t MaskSize = CountPopulation_64(Mask);
17809           if (Shift + MaskSize <= VT.getSizeInBits())
17810             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17811                                DAG.getConstant(Shift | (MaskSize << 8), VT));
17812         }
17813       }
17814     } // BEXTR
17815
17816     return SDValue();
17817   }
17818
17819   // Want to form ANDNP nodes:
17820   // 1) In the hopes of then easily combining them with OR and AND nodes
17821   //    to form PBLEND/PSIGN.
17822   // 2) To match ANDN packed intrinsics
17823   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17824     return SDValue();
17825
17826   SDValue N0 = N->getOperand(0);
17827   SDValue N1 = N->getOperand(1);
17828   SDLoc DL(N);
17829
17830   // Check LHS for vnot
17831   if (N0.getOpcode() == ISD::XOR &&
17832       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17833       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17834     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17835
17836   // Check RHS for vnot
17837   if (N1.getOpcode() == ISD::XOR &&
17838       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17839       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17840     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17841
17842   return SDValue();
17843 }
17844
17845 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17846                                 TargetLowering::DAGCombinerInfo &DCI,
17847                                 const X86Subtarget *Subtarget) {
17848   EVT VT = N->getValueType(0);
17849   if (DCI.isBeforeLegalizeOps())
17850     return SDValue();
17851
17852   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17853   if (R.getNode())
17854     return R;
17855
17856   SDValue N0 = N->getOperand(0);
17857   SDValue N1 = N->getOperand(1);
17858
17859   // look for psign/blend
17860   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17861     if (!Subtarget->hasSSSE3() ||
17862         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17863       return SDValue();
17864
17865     // Canonicalize pandn to RHS
17866     if (N0.getOpcode() == X86ISD::ANDNP)
17867       std::swap(N0, N1);
17868     // or (and (m, y), (pandn m, x))
17869     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17870       SDValue Mask = N1.getOperand(0);
17871       SDValue X    = N1.getOperand(1);
17872       SDValue Y;
17873       if (N0.getOperand(0) == Mask)
17874         Y = N0.getOperand(1);
17875       if (N0.getOperand(1) == Mask)
17876         Y = N0.getOperand(0);
17877
17878       // Check to see if the mask appeared in both the AND and ANDNP and
17879       if (!Y.getNode())
17880         return SDValue();
17881
17882       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17883       // Look through mask bitcast.
17884       if (Mask.getOpcode() == ISD::BITCAST)
17885         Mask = Mask.getOperand(0);
17886       if (X.getOpcode() == ISD::BITCAST)
17887         X = X.getOperand(0);
17888       if (Y.getOpcode() == ISD::BITCAST)
17889         Y = Y.getOperand(0);
17890
17891       EVT MaskVT = Mask.getValueType();
17892
17893       // Validate that the Mask operand is a vector sra node.
17894       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17895       // there is no psrai.b
17896       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17897       unsigned SraAmt = ~0;
17898       if (Mask.getOpcode() == ISD::SRA) {
17899         SDValue Amt = Mask.getOperand(1);
17900         if (isSplatVector(Amt.getNode())) {
17901           SDValue SclrAmt = Amt->getOperand(0);
17902           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17903             SraAmt = C->getZExtValue();
17904         }
17905       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17906         SDValue SraC = Mask.getOperand(1);
17907         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17908       }
17909       if ((SraAmt + 1) != EltBits)
17910         return SDValue();
17911
17912       SDLoc DL(N);
17913
17914       // Now we know we at least have a plendvb with the mask val.  See if
17915       // we can form a psignb/w/d.
17916       // psign = x.type == y.type == mask.type && y = sub(0, x);
17917       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17918           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17919           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17920         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17921                "Unsupported VT for PSIGN");
17922         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17923         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17924       }
17925       // PBLENDVB only available on SSE 4.1
17926       if (!Subtarget->hasSSE41())
17927         return SDValue();
17928
17929       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17930
17931       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17932       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17933       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17934       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17935       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17936     }
17937   }
17938
17939   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17940     return SDValue();
17941
17942   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17943   MachineFunction &MF = DAG.getMachineFunction();
17944   bool OptForSize = MF.getFunction()->getAttributes().
17945     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
17946  
17947   // SHLD/SHRD instructions have lower register pressure, but on some 
17948   // platforms they have higher latency than the equivalent 
17949   // series of shifts/or that would otherwise be generated. 
17950   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
17951   // have higer latencies and we are not optimizing for size.  
17952   if (!OptForSize && Subtarget->isSHLDSlow())
17953     return SDValue();
17954
17955   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17956     std::swap(N0, N1);
17957   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17958     return SDValue();
17959   if (!N0.hasOneUse() || !N1.hasOneUse())
17960     return SDValue();
17961
17962   SDValue ShAmt0 = N0.getOperand(1);
17963   if (ShAmt0.getValueType() != MVT::i8)
17964     return SDValue();
17965   SDValue ShAmt1 = N1.getOperand(1);
17966   if (ShAmt1.getValueType() != MVT::i8)
17967     return SDValue();
17968   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17969     ShAmt0 = ShAmt0.getOperand(0);
17970   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17971     ShAmt1 = ShAmt1.getOperand(0);
17972
17973   SDLoc DL(N);
17974   unsigned Opc = X86ISD::SHLD;
17975   SDValue Op0 = N0.getOperand(0);
17976   SDValue Op1 = N1.getOperand(0);
17977   if (ShAmt0.getOpcode() == ISD::SUB) {
17978     Opc = X86ISD::SHRD;
17979     std::swap(Op0, Op1);
17980     std::swap(ShAmt0, ShAmt1);
17981   }
17982
17983   unsigned Bits = VT.getSizeInBits();
17984   if (ShAmt1.getOpcode() == ISD::SUB) {
17985     SDValue Sum = ShAmt1.getOperand(0);
17986     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17987       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17988       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17989         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17990       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17991         return DAG.getNode(Opc, DL, VT,
17992                            Op0, Op1,
17993                            DAG.getNode(ISD::TRUNCATE, DL,
17994                                        MVT::i8, ShAmt0));
17995     }
17996   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17997     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17998     if (ShAmt0C &&
17999         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18000       return DAG.getNode(Opc, DL, VT,
18001                          N0.getOperand(0), N1.getOperand(0),
18002                          DAG.getNode(ISD::TRUNCATE, DL,
18003                                        MVT::i8, ShAmt0));
18004   }
18005
18006   return SDValue();
18007 }
18008
18009 // Generate NEG and CMOV for integer abs.
18010 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18011   EVT VT = N->getValueType(0);
18012
18013   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18014   // 8-bit integer abs to NEG and CMOV.
18015   if (VT.isInteger() && VT.getSizeInBits() == 8)
18016     return SDValue();
18017
18018   SDValue N0 = N->getOperand(0);
18019   SDValue N1 = N->getOperand(1);
18020   SDLoc DL(N);
18021
18022   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18023   // and change it to SUB and CMOV.
18024   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18025       N0.getOpcode() == ISD::ADD &&
18026       N0.getOperand(1) == N1 &&
18027       N1.getOpcode() == ISD::SRA &&
18028       N1.getOperand(0) == N0.getOperand(0))
18029     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18030       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18031         // Generate SUB & CMOV.
18032         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18033                                   DAG.getConstant(0, VT), N0.getOperand(0));
18034
18035         SDValue Ops[] = { N0.getOperand(0), Neg,
18036                           DAG.getConstant(X86::COND_GE, MVT::i8),
18037                           SDValue(Neg.getNode(), 1) };
18038         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18039                            Ops, array_lengthof(Ops));
18040       }
18041   return SDValue();
18042 }
18043
18044 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18045 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18046                                  TargetLowering::DAGCombinerInfo &DCI,
18047                                  const X86Subtarget *Subtarget) {
18048   EVT VT = N->getValueType(0);
18049   if (DCI.isBeforeLegalizeOps())
18050     return SDValue();
18051
18052   if (Subtarget->hasCMov()) {
18053     SDValue RV = performIntegerAbsCombine(N, DAG);
18054     if (RV.getNode())
18055       return RV;
18056   }
18057
18058   // Try forming BMI if it is available.
18059   if (!Subtarget->hasBMI())
18060     return SDValue();
18061
18062   if (VT != MVT::i32 && VT != MVT::i64)
18063     return SDValue();
18064
18065   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18066
18067   // Create BLSMSK instructions by finding X ^ (X-1)
18068   SDValue N0 = N->getOperand(0);
18069   SDValue N1 = N->getOperand(1);
18070   SDLoc DL(N);
18071
18072   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18073       isAllOnes(N0.getOperand(1)))
18074     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18075
18076   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18077       isAllOnes(N1.getOperand(1)))
18078     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18079
18080   return SDValue();
18081 }
18082
18083 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18084 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18085                                   TargetLowering::DAGCombinerInfo &DCI,
18086                                   const X86Subtarget *Subtarget) {
18087   LoadSDNode *Ld = cast<LoadSDNode>(N);
18088   EVT RegVT = Ld->getValueType(0);
18089   EVT MemVT = Ld->getMemoryVT();
18090   SDLoc dl(Ld);
18091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18092   unsigned RegSz = RegVT.getSizeInBits();
18093
18094   // On Sandybridge unaligned 256bit loads are inefficient.
18095   ISD::LoadExtType Ext = Ld->getExtensionType();
18096   unsigned Alignment = Ld->getAlignment();
18097   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18098   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18099       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18100     unsigned NumElems = RegVT.getVectorNumElements();
18101     if (NumElems < 2)
18102       return SDValue();
18103
18104     SDValue Ptr = Ld->getBasePtr();
18105     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18106
18107     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18108                                   NumElems/2);
18109     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18110                                 Ld->getPointerInfo(), Ld->isVolatile(),
18111                                 Ld->isNonTemporal(), Ld->isInvariant(),
18112                                 Alignment);
18113     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18114     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18115                                 Ld->getPointerInfo(), Ld->isVolatile(),
18116                                 Ld->isNonTemporal(), Ld->isInvariant(),
18117                                 std::min(16U, Alignment));
18118     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18119                              Load1.getValue(1),
18120                              Load2.getValue(1));
18121
18122     SDValue NewVec = DAG.getUNDEF(RegVT);
18123     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18124     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18125     return DCI.CombineTo(N, NewVec, TF, true);
18126   }
18127
18128   // If this is a vector EXT Load then attempt to optimize it using a
18129   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18130   // expansion is still better than scalar code.
18131   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18132   // emit a shuffle and a arithmetic shift.
18133   // TODO: It is possible to support ZExt by zeroing the undef values
18134   // during the shuffle phase or after the shuffle.
18135   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18136       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18137     assert(MemVT != RegVT && "Cannot extend to the same type");
18138     assert(MemVT.isVector() && "Must load a vector from memory");
18139
18140     unsigned NumElems = RegVT.getVectorNumElements();
18141     unsigned MemSz = MemVT.getSizeInBits();
18142     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18143
18144     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18145       return SDValue();
18146
18147     // All sizes must be a power of two.
18148     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18149       return SDValue();
18150
18151     // Attempt to load the original value using scalar loads.
18152     // Find the largest scalar type that divides the total loaded size.
18153     MVT SclrLoadTy = MVT::i8;
18154     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18155          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18156       MVT Tp = (MVT::SimpleValueType)tp;
18157       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18158         SclrLoadTy = Tp;
18159       }
18160     }
18161
18162     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18163     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18164         (64 <= MemSz))
18165       SclrLoadTy = MVT::f64;
18166
18167     // Calculate the number of scalar loads that we need to perform
18168     // in order to load our vector from memory.
18169     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18170     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18171       return SDValue();
18172
18173     unsigned loadRegZize = RegSz;
18174     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18175       loadRegZize /= 2;
18176
18177     // Represent our vector as a sequence of elements which are the
18178     // largest scalar that we can load.
18179     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18180       loadRegZize/SclrLoadTy.getSizeInBits());
18181
18182     // Represent the data using the same element type that is stored in
18183     // memory. In practice, we ''widen'' MemVT.
18184     EVT WideVecVT =
18185           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18186                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18187
18188     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18189       "Invalid vector type");
18190
18191     // We can't shuffle using an illegal type.
18192     if (!TLI.isTypeLegal(WideVecVT))
18193       return SDValue();
18194
18195     SmallVector<SDValue, 8> Chains;
18196     SDValue Ptr = Ld->getBasePtr();
18197     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18198                                         TLI.getPointerTy());
18199     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18200
18201     for (unsigned i = 0; i < NumLoads; ++i) {
18202       // Perform a single load.
18203       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18204                                        Ptr, Ld->getPointerInfo(),
18205                                        Ld->isVolatile(), Ld->isNonTemporal(),
18206                                        Ld->isInvariant(), Ld->getAlignment());
18207       Chains.push_back(ScalarLoad.getValue(1));
18208       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18209       // another round of DAGCombining.
18210       if (i == 0)
18211         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18212       else
18213         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18214                           ScalarLoad, DAG.getIntPtrConstant(i));
18215
18216       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18217     }
18218
18219     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18220                                Chains.size());
18221
18222     // Bitcast the loaded value to a vector of the original element type, in
18223     // the size of the target vector type.
18224     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18225     unsigned SizeRatio = RegSz/MemSz;
18226
18227     if (Ext == ISD::SEXTLOAD) {
18228       // If we have SSE4.1 we can directly emit a VSEXT node.
18229       if (Subtarget->hasSSE41()) {
18230         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18231         return DCI.CombineTo(N, Sext, TF, true);
18232       }
18233
18234       // Otherwise we'll shuffle the small elements in the high bits of the
18235       // larger type and perform an arithmetic shift. If the shift is not legal
18236       // it's better to scalarize.
18237       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18238         return SDValue();
18239
18240       // Redistribute the loaded elements into the different locations.
18241       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18242       for (unsigned i = 0; i != NumElems; ++i)
18243         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18244
18245       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18246                                            DAG.getUNDEF(WideVecVT),
18247                                            &ShuffleVec[0]);
18248
18249       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18250
18251       // Build the arithmetic shift.
18252       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18253                      MemVT.getVectorElementType().getSizeInBits();
18254       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18255                           DAG.getConstant(Amt, RegVT));
18256
18257       return DCI.CombineTo(N, Shuff, TF, true);
18258     }
18259
18260     // Redistribute the loaded elements into the different locations.
18261     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18262     for (unsigned i = 0; i != NumElems; ++i)
18263       ShuffleVec[i*SizeRatio] = i;
18264
18265     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18266                                          DAG.getUNDEF(WideVecVT),
18267                                          &ShuffleVec[0]);
18268
18269     // Bitcast to the requested type.
18270     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18271     // Replace the original load with the new sequence
18272     // and return the new chain.
18273     return DCI.CombineTo(N, Shuff, TF, true);
18274   }
18275
18276   return SDValue();
18277 }
18278
18279 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18280 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18281                                    const X86Subtarget *Subtarget) {
18282   StoreSDNode *St = cast<StoreSDNode>(N);
18283   EVT VT = St->getValue().getValueType();
18284   EVT StVT = St->getMemoryVT();
18285   SDLoc dl(St);
18286   SDValue StoredVal = St->getOperand(1);
18287   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18288
18289   // If we are saving a concatenation of two XMM registers, perform two stores.
18290   // On Sandy Bridge, 256-bit memory operations are executed by two
18291   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18292   // memory  operation.
18293   unsigned Alignment = St->getAlignment();
18294   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18295   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18296       StVT == VT && !IsAligned) {
18297     unsigned NumElems = VT.getVectorNumElements();
18298     if (NumElems < 2)
18299       return SDValue();
18300
18301     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18302     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18303
18304     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18305     SDValue Ptr0 = St->getBasePtr();
18306     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18307
18308     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18309                                 St->getPointerInfo(), St->isVolatile(),
18310                                 St->isNonTemporal(), Alignment);
18311     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18312                                 St->getPointerInfo(), St->isVolatile(),
18313                                 St->isNonTemporal(),
18314                                 std::min(16U, Alignment));
18315     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18316   }
18317
18318   // Optimize trunc store (of multiple scalars) to shuffle and store.
18319   // First, pack all of the elements in one place. Next, store to memory
18320   // in fewer chunks.
18321   if (St->isTruncatingStore() && VT.isVector()) {
18322     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18323     unsigned NumElems = VT.getVectorNumElements();
18324     assert(StVT != VT && "Cannot truncate to the same type");
18325     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18326     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18327
18328     // From, To sizes and ElemCount must be pow of two
18329     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18330     // We are going to use the original vector elt for storing.
18331     // Accumulated smaller vector elements must be a multiple of the store size.
18332     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18333
18334     unsigned SizeRatio  = FromSz / ToSz;
18335
18336     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18337
18338     // Create a type on which we perform the shuffle
18339     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18340             StVT.getScalarType(), NumElems*SizeRatio);
18341
18342     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18343
18344     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18345     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18346     for (unsigned i = 0; i != NumElems; ++i)
18347       ShuffleVec[i] = i * SizeRatio;
18348
18349     // Can't shuffle using an illegal type.
18350     if (!TLI.isTypeLegal(WideVecVT))
18351       return SDValue();
18352
18353     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18354                                          DAG.getUNDEF(WideVecVT),
18355                                          &ShuffleVec[0]);
18356     // At this point all of the data is stored at the bottom of the
18357     // register. We now need to save it to mem.
18358
18359     // Find the largest store unit
18360     MVT StoreType = MVT::i8;
18361     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18362          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18363       MVT Tp = (MVT::SimpleValueType)tp;
18364       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18365         StoreType = Tp;
18366     }
18367
18368     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18369     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18370         (64 <= NumElems * ToSz))
18371       StoreType = MVT::f64;
18372
18373     // Bitcast the original vector into a vector of store-size units
18374     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18375             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18376     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18377     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18378     SmallVector<SDValue, 8> Chains;
18379     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18380                                         TLI.getPointerTy());
18381     SDValue Ptr = St->getBasePtr();
18382
18383     // Perform one or more big stores into memory.
18384     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18385       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18386                                    StoreType, ShuffWide,
18387                                    DAG.getIntPtrConstant(i));
18388       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18389                                 St->getPointerInfo(), St->isVolatile(),
18390                                 St->isNonTemporal(), St->getAlignment());
18391       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18392       Chains.push_back(Ch);
18393     }
18394
18395     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18396                                Chains.size());
18397   }
18398
18399   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18400   // the FP state in cases where an emms may be missing.
18401   // A preferable solution to the general problem is to figure out the right
18402   // places to insert EMMS.  This qualifies as a quick hack.
18403
18404   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18405   if (VT.getSizeInBits() != 64)
18406     return SDValue();
18407
18408   const Function *F = DAG.getMachineFunction().getFunction();
18409   bool NoImplicitFloatOps = F->getAttributes().
18410     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18411   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18412                      && Subtarget->hasSSE2();
18413   if ((VT.isVector() ||
18414        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18415       isa<LoadSDNode>(St->getValue()) &&
18416       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18417       St->getChain().hasOneUse() && !St->isVolatile()) {
18418     SDNode* LdVal = St->getValue().getNode();
18419     LoadSDNode *Ld = 0;
18420     int TokenFactorIndex = -1;
18421     SmallVector<SDValue, 8> Ops;
18422     SDNode* ChainVal = St->getChain().getNode();
18423     // Must be a store of a load.  We currently handle two cases:  the load
18424     // is a direct child, and it's under an intervening TokenFactor.  It is
18425     // possible to dig deeper under nested TokenFactors.
18426     if (ChainVal == LdVal)
18427       Ld = cast<LoadSDNode>(St->getChain());
18428     else if (St->getValue().hasOneUse() &&
18429              ChainVal->getOpcode() == ISD::TokenFactor) {
18430       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18431         if (ChainVal->getOperand(i).getNode() == LdVal) {
18432           TokenFactorIndex = i;
18433           Ld = cast<LoadSDNode>(St->getValue());
18434         } else
18435           Ops.push_back(ChainVal->getOperand(i));
18436       }
18437     }
18438
18439     if (!Ld || !ISD::isNormalLoad(Ld))
18440       return SDValue();
18441
18442     // If this is not the MMX case, i.e. we are just turning i64 load/store
18443     // into f64 load/store, avoid the transformation if there are multiple
18444     // uses of the loaded value.
18445     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18446       return SDValue();
18447
18448     SDLoc LdDL(Ld);
18449     SDLoc StDL(N);
18450     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18451     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18452     // pair instead.
18453     if (Subtarget->is64Bit() || F64IsLegal) {
18454       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18455       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18456                                   Ld->getPointerInfo(), Ld->isVolatile(),
18457                                   Ld->isNonTemporal(), Ld->isInvariant(),
18458                                   Ld->getAlignment());
18459       SDValue NewChain = NewLd.getValue(1);
18460       if (TokenFactorIndex != -1) {
18461         Ops.push_back(NewChain);
18462         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18463                                Ops.size());
18464       }
18465       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18466                           St->getPointerInfo(),
18467                           St->isVolatile(), St->isNonTemporal(),
18468                           St->getAlignment());
18469     }
18470
18471     // Otherwise, lower to two pairs of 32-bit loads / stores.
18472     SDValue LoAddr = Ld->getBasePtr();
18473     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18474                                  DAG.getConstant(4, MVT::i32));
18475
18476     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18477                                Ld->getPointerInfo(),
18478                                Ld->isVolatile(), Ld->isNonTemporal(),
18479                                Ld->isInvariant(), Ld->getAlignment());
18480     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18481                                Ld->getPointerInfo().getWithOffset(4),
18482                                Ld->isVolatile(), Ld->isNonTemporal(),
18483                                Ld->isInvariant(),
18484                                MinAlign(Ld->getAlignment(), 4));
18485
18486     SDValue NewChain = LoLd.getValue(1);
18487     if (TokenFactorIndex != -1) {
18488       Ops.push_back(LoLd);
18489       Ops.push_back(HiLd);
18490       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18491                              Ops.size());
18492     }
18493
18494     LoAddr = St->getBasePtr();
18495     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18496                          DAG.getConstant(4, MVT::i32));
18497
18498     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18499                                 St->getPointerInfo(),
18500                                 St->isVolatile(), St->isNonTemporal(),
18501                                 St->getAlignment());
18502     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18503                                 St->getPointerInfo().getWithOffset(4),
18504                                 St->isVolatile(),
18505                                 St->isNonTemporal(),
18506                                 MinAlign(St->getAlignment(), 4));
18507     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18508   }
18509   return SDValue();
18510 }
18511
18512 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18513 /// and return the operands for the horizontal operation in LHS and RHS.  A
18514 /// horizontal operation performs the binary operation on successive elements
18515 /// of its first operand, then on successive elements of its second operand,
18516 /// returning the resulting values in a vector.  For example, if
18517 ///   A = < float a0, float a1, float a2, float a3 >
18518 /// and
18519 ///   B = < float b0, float b1, float b2, float b3 >
18520 /// then the result of doing a horizontal operation on A and B is
18521 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18522 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18523 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18524 /// set to A, RHS to B, and the routine returns 'true'.
18525 /// Note that the binary operation should have the property that if one of the
18526 /// operands is UNDEF then the result is UNDEF.
18527 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18528   // Look for the following pattern: if
18529   //   A = < float a0, float a1, float a2, float a3 >
18530   //   B = < float b0, float b1, float b2, float b3 >
18531   // and
18532   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18533   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18534   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18535   // which is A horizontal-op B.
18536
18537   // At least one of the operands should be a vector shuffle.
18538   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18539       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18540     return false;
18541
18542   MVT VT = LHS.getSimpleValueType();
18543
18544   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18545          "Unsupported vector type for horizontal add/sub");
18546
18547   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18548   // operate independently on 128-bit lanes.
18549   unsigned NumElts = VT.getVectorNumElements();
18550   unsigned NumLanes = VT.getSizeInBits()/128;
18551   unsigned NumLaneElts = NumElts / NumLanes;
18552   assert((NumLaneElts % 2 == 0) &&
18553          "Vector type should have an even number of elements in each lane");
18554   unsigned HalfLaneElts = NumLaneElts/2;
18555
18556   // View LHS in the form
18557   //   LHS = VECTOR_SHUFFLE A, B, LMask
18558   // If LHS is not a shuffle then pretend it is the shuffle
18559   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18560   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18561   // type VT.
18562   SDValue A, B;
18563   SmallVector<int, 16> LMask(NumElts);
18564   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18565     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18566       A = LHS.getOperand(0);
18567     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18568       B = LHS.getOperand(1);
18569     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18570     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18571   } else {
18572     if (LHS.getOpcode() != ISD::UNDEF)
18573       A = LHS;
18574     for (unsigned i = 0; i != NumElts; ++i)
18575       LMask[i] = i;
18576   }
18577
18578   // Likewise, view RHS in the form
18579   //   RHS = VECTOR_SHUFFLE C, D, RMask
18580   SDValue C, D;
18581   SmallVector<int, 16> RMask(NumElts);
18582   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18583     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18584       C = RHS.getOperand(0);
18585     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18586       D = RHS.getOperand(1);
18587     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18588     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18589   } else {
18590     if (RHS.getOpcode() != ISD::UNDEF)
18591       C = RHS;
18592     for (unsigned i = 0; i != NumElts; ++i)
18593       RMask[i] = i;
18594   }
18595
18596   // Check that the shuffles are both shuffling the same vectors.
18597   if (!(A == C && B == D) && !(A == D && B == C))
18598     return false;
18599
18600   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18601   if (!A.getNode() && !B.getNode())
18602     return false;
18603
18604   // If A and B occur in reverse order in RHS, then "swap" them (which means
18605   // rewriting the mask).
18606   if (A != C)
18607     CommuteVectorShuffleMask(RMask, NumElts);
18608
18609   // At this point LHS and RHS are equivalent to
18610   //   LHS = VECTOR_SHUFFLE A, B, LMask
18611   //   RHS = VECTOR_SHUFFLE A, B, RMask
18612   // Check that the masks correspond to performing a horizontal operation.
18613   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18614     for (unsigned i = 0; i != NumLaneElts; ++i) {
18615       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18616
18617       // Ignore any UNDEF components.
18618       if (LIdx < 0 || RIdx < 0 ||
18619           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18620           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18621         continue;
18622
18623       // Check that successive elements are being operated on.  If not, this is
18624       // not a horizontal operation.
18625       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18626       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18627       if (!(LIdx == Index && RIdx == Index + 1) &&
18628           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18629         return false;
18630     }
18631   }
18632
18633   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18634   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18635   return true;
18636 }
18637
18638 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18639 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18640                                   const X86Subtarget *Subtarget) {
18641   EVT VT = N->getValueType(0);
18642   SDValue LHS = N->getOperand(0);
18643   SDValue RHS = N->getOperand(1);
18644
18645   // Try to synthesize horizontal adds from adds of shuffles.
18646   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18647        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18648       isHorizontalBinOp(LHS, RHS, true))
18649     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18650   return SDValue();
18651 }
18652
18653 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18654 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18655                                   const X86Subtarget *Subtarget) {
18656   EVT VT = N->getValueType(0);
18657   SDValue LHS = N->getOperand(0);
18658   SDValue RHS = N->getOperand(1);
18659
18660   // Try to synthesize horizontal subs from subs of shuffles.
18661   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18662        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18663       isHorizontalBinOp(LHS, RHS, false))
18664     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18665   return SDValue();
18666 }
18667
18668 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18669 /// X86ISD::FXOR nodes.
18670 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18671   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18672   // F[X]OR(0.0, x) -> x
18673   // F[X]OR(x, 0.0) -> x
18674   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18675     if (C->getValueAPF().isPosZero())
18676       return N->getOperand(1);
18677   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18678     if (C->getValueAPF().isPosZero())
18679       return N->getOperand(0);
18680   return SDValue();
18681 }
18682
18683 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18684 /// X86ISD::FMAX nodes.
18685 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18686   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18687
18688   // Only perform optimizations if UnsafeMath is used.
18689   if (!DAG.getTarget().Options.UnsafeFPMath)
18690     return SDValue();
18691
18692   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18693   // into FMINC and FMAXC, which are Commutative operations.
18694   unsigned NewOp = 0;
18695   switch (N->getOpcode()) {
18696     default: llvm_unreachable("unknown opcode");
18697     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18698     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18699   }
18700
18701   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18702                      N->getOperand(0), N->getOperand(1));
18703 }
18704
18705 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18706 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18707   // FAND(0.0, x) -> 0.0
18708   // FAND(x, 0.0) -> 0.0
18709   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18710     if (C->getValueAPF().isPosZero())
18711       return N->getOperand(0);
18712   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18713     if (C->getValueAPF().isPosZero())
18714       return N->getOperand(1);
18715   return SDValue();
18716 }
18717
18718 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18719 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18720   // FANDN(x, 0.0) -> 0.0
18721   // FANDN(0.0, x) -> x
18722   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18723     if (C->getValueAPF().isPosZero())
18724       return N->getOperand(1);
18725   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18726     if (C->getValueAPF().isPosZero())
18727       return N->getOperand(1);
18728   return SDValue();
18729 }
18730
18731 static SDValue PerformBTCombine(SDNode *N,
18732                                 SelectionDAG &DAG,
18733                                 TargetLowering::DAGCombinerInfo &DCI) {
18734   // BT ignores high bits in the bit index operand.
18735   SDValue Op1 = N->getOperand(1);
18736   if (Op1.hasOneUse()) {
18737     unsigned BitWidth = Op1.getValueSizeInBits();
18738     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18739     APInt KnownZero, KnownOne;
18740     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18741                                           !DCI.isBeforeLegalizeOps());
18742     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18743     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18744         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18745       DCI.CommitTargetLoweringOpt(TLO);
18746   }
18747   return SDValue();
18748 }
18749
18750 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18751   SDValue Op = N->getOperand(0);
18752   if (Op.getOpcode() == ISD::BITCAST)
18753     Op = Op.getOperand(0);
18754   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18755   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18756       VT.getVectorElementType().getSizeInBits() ==
18757       OpVT.getVectorElementType().getSizeInBits()) {
18758     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18759   }
18760   return SDValue();
18761 }
18762
18763 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18764                                                const X86Subtarget *Subtarget) {
18765   EVT VT = N->getValueType(0);
18766   if (!VT.isVector())
18767     return SDValue();
18768
18769   SDValue N0 = N->getOperand(0);
18770   SDValue N1 = N->getOperand(1);
18771   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18772   SDLoc dl(N);
18773
18774   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18775   // both SSE and AVX2 since there is no sign-extended shift right
18776   // operation on a vector with 64-bit elements.
18777   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18778   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18779   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18780       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18781     SDValue N00 = N0.getOperand(0);
18782
18783     // EXTLOAD has a better solution on AVX2,
18784     // it may be replaced with X86ISD::VSEXT node.
18785     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18786       if (!ISD::isNormalLoad(N00.getNode()))
18787         return SDValue();
18788
18789     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18790         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18791                                   N00, N1);
18792       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18793     }
18794   }
18795   return SDValue();
18796 }
18797
18798 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18799                                   TargetLowering::DAGCombinerInfo &DCI,
18800                                   const X86Subtarget *Subtarget) {
18801   if (!DCI.isBeforeLegalizeOps())
18802     return SDValue();
18803
18804   if (!Subtarget->hasFp256())
18805     return SDValue();
18806
18807   EVT VT = N->getValueType(0);
18808   if (VT.isVector() && VT.getSizeInBits() == 256) {
18809     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18810     if (R.getNode())
18811       return R;
18812   }
18813
18814   return SDValue();
18815 }
18816
18817 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18818                                  const X86Subtarget* Subtarget) {
18819   SDLoc dl(N);
18820   EVT VT = N->getValueType(0);
18821
18822   // Let legalize expand this if it isn't a legal type yet.
18823   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18824     return SDValue();
18825
18826   EVT ScalarVT = VT.getScalarType();
18827   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18828       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18829     return SDValue();
18830
18831   SDValue A = N->getOperand(0);
18832   SDValue B = N->getOperand(1);
18833   SDValue C = N->getOperand(2);
18834
18835   bool NegA = (A.getOpcode() == ISD::FNEG);
18836   bool NegB = (B.getOpcode() == ISD::FNEG);
18837   bool NegC = (C.getOpcode() == ISD::FNEG);
18838
18839   // Negative multiplication when NegA xor NegB
18840   bool NegMul = (NegA != NegB);
18841   if (NegA)
18842     A = A.getOperand(0);
18843   if (NegB)
18844     B = B.getOperand(0);
18845   if (NegC)
18846     C = C.getOperand(0);
18847
18848   unsigned Opcode;
18849   if (!NegMul)
18850     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18851   else
18852     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18853
18854   return DAG.getNode(Opcode, dl, VT, A, B, C);
18855 }
18856
18857 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18858                                   TargetLowering::DAGCombinerInfo &DCI,
18859                                   const X86Subtarget *Subtarget) {
18860   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18861   //           (and (i32 x86isd::setcc_carry), 1)
18862   // This eliminates the zext. This transformation is necessary because
18863   // ISD::SETCC is always legalized to i8.
18864   SDLoc dl(N);
18865   SDValue N0 = N->getOperand(0);
18866   EVT VT = N->getValueType(0);
18867
18868   if (N0.getOpcode() == ISD::AND &&
18869       N0.hasOneUse() &&
18870       N0.getOperand(0).hasOneUse()) {
18871     SDValue N00 = N0.getOperand(0);
18872     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18873       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18874       if (!C || C->getZExtValue() != 1)
18875         return SDValue();
18876       return DAG.getNode(ISD::AND, dl, VT,
18877                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18878                                      N00.getOperand(0), N00.getOperand(1)),
18879                          DAG.getConstant(1, VT));
18880     }
18881   }
18882
18883   if (VT.is256BitVector()) {
18884     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18885     if (R.getNode())
18886       return R;
18887   }
18888
18889   return SDValue();
18890 }
18891
18892 // Optimize x == -y --> x+y == 0
18893 //          x != -y --> x+y != 0
18894 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18895   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18896   SDValue LHS = N->getOperand(0);
18897   SDValue RHS = N->getOperand(1);
18898
18899   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18900     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18901       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18902         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18903                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18904         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18905                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18906       }
18907   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18908     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18909       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18910         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18911                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18912         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18913                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18914       }
18915   return SDValue();
18916 }
18917
18918 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18919 // as "sbb reg,reg", since it can be extended without zext and produces
18920 // an all-ones bit which is more useful than 0/1 in some cases.
18921 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18922   return DAG.getNode(ISD::AND, DL, MVT::i8,
18923                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18924                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18925                      DAG.getConstant(1, MVT::i8));
18926 }
18927
18928 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18929 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18930                                    TargetLowering::DAGCombinerInfo &DCI,
18931                                    const X86Subtarget *Subtarget) {
18932   SDLoc DL(N);
18933   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18934   SDValue EFLAGS = N->getOperand(1);
18935
18936   if (CC == X86::COND_A) {
18937     // Try to convert COND_A into COND_B in an attempt to facilitate
18938     // materializing "setb reg".
18939     //
18940     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18941     // cannot take an immediate as its first operand.
18942     //
18943     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18944         EFLAGS.getValueType().isInteger() &&
18945         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18946       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18947                                    EFLAGS.getNode()->getVTList(),
18948                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18949       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18950       return MaterializeSETB(DL, NewEFLAGS, DAG);
18951     }
18952   }
18953
18954   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18955   // a zext and produces an all-ones bit which is more useful than 0/1 in some
18956   // cases.
18957   if (CC == X86::COND_B)
18958     return MaterializeSETB(DL, EFLAGS, DAG);
18959
18960   SDValue Flags;
18961
18962   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18963   if (Flags.getNode()) {
18964     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18965     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18966   }
18967
18968   return SDValue();
18969 }
18970
18971 // Optimize branch condition evaluation.
18972 //
18973 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18974                                     TargetLowering::DAGCombinerInfo &DCI,
18975                                     const X86Subtarget *Subtarget) {
18976   SDLoc DL(N);
18977   SDValue Chain = N->getOperand(0);
18978   SDValue Dest = N->getOperand(1);
18979   SDValue EFLAGS = N->getOperand(3);
18980   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18981
18982   SDValue Flags;
18983
18984   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18985   if (Flags.getNode()) {
18986     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18987     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18988                        Flags);
18989   }
18990
18991   return SDValue();
18992 }
18993
18994 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18995                                         const X86TargetLowering *XTLI) {
18996   SDValue Op0 = N->getOperand(0);
18997   EVT InVT = Op0->getValueType(0);
18998
18999   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19000   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19001     SDLoc dl(N);
19002     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19003     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19004     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19005   }
19006
19007   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19008   // a 32-bit target where SSE doesn't support i64->FP operations.
19009   if (Op0.getOpcode() == ISD::LOAD) {
19010     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19011     EVT VT = Ld->getValueType(0);
19012     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19013         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19014         !XTLI->getSubtarget()->is64Bit() &&
19015         VT == MVT::i64) {
19016       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19017                                           Ld->getChain(), Op0, DAG);
19018       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19019       return FILDChain;
19020     }
19021   }
19022   return SDValue();
19023 }
19024
19025 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19026 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19027                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19028   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19029   // the result is either zero or one (depending on the input carry bit).
19030   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19031   if (X86::isZeroNode(N->getOperand(0)) &&
19032       X86::isZeroNode(N->getOperand(1)) &&
19033       // We don't have a good way to replace an EFLAGS use, so only do this when
19034       // dead right now.
19035       SDValue(N, 1).use_empty()) {
19036     SDLoc DL(N);
19037     EVT VT = N->getValueType(0);
19038     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19039     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19040                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19041                                            DAG.getConstant(X86::COND_B,MVT::i8),
19042                                            N->getOperand(2)),
19043                                DAG.getConstant(1, VT));
19044     return DCI.CombineTo(N, Res1, CarryOut);
19045   }
19046
19047   return SDValue();
19048 }
19049
19050 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19051 //      (add Y, (setne X, 0)) -> sbb -1, Y
19052 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19053 //      (sub (setne X, 0), Y) -> adc -1, Y
19054 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19055   SDLoc DL(N);
19056
19057   // Look through ZExts.
19058   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19059   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19060     return SDValue();
19061
19062   SDValue SetCC = Ext.getOperand(0);
19063   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19064     return SDValue();
19065
19066   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19067   if (CC != X86::COND_E && CC != X86::COND_NE)
19068     return SDValue();
19069
19070   SDValue Cmp = SetCC.getOperand(1);
19071   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19072       !X86::isZeroNode(Cmp.getOperand(1)) ||
19073       !Cmp.getOperand(0).getValueType().isInteger())
19074     return SDValue();
19075
19076   SDValue CmpOp0 = Cmp.getOperand(0);
19077   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19078                                DAG.getConstant(1, CmpOp0.getValueType()));
19079
19080   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19081   if (CC == X86::COND_NE)
19082     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19083                        DL, OtherVal.getValueType(), OtherVal,
19084                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19085   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19086                      DL, OtherVal.getValueType(), OtherVal,
19087                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19088 }
19089
19090 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19091 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19092                                  const X86Subtarget *Subtarget) {
19093   EVT VT = N->getValueType(0);
19094   SDValue Op0 = N->getOperand(0);
19095   SDValue Op1 = N->getOperand(1);
19096
19097   // Try to synthesize horizontal adds from adds of shuffles.
19098   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19099        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19100       isHorizontalBinOp(Op0, Op1, true))
19101     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19102
19103   return OptimizeConditionalInDecrement(N, DAG);
19104 }
19105
19106 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19107                                  const X86Subtarget *Subtarget) {
19108   SDValue Op0 = N->getOperand(0);
19109   SDValue Op1 = N->getOperand(1);
19110
19111   // X86 can't encode an immediate LHS of a sub. See if we can push the
19112   // negation into a preceding instruction.
19113   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19114     // If the RHS of the sub is a XOR with one use and a constant, invert the
19115     // immediate. Then add one to the LHS of the sub so we can turn
19116     // X-Y -> X+~Y+1, saving one register.
19117     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19118         isa<ConstantSDNode>(Op1.getOperand(1))) {
19119       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19120       EVT VT = Op0.getValueType();
19121       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19122                                    Op1.getOperand(0),
19123                                    DAG.getConstant(~XorC, VT));
19124       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19125                          DAG.getConstant(C->getAPIntValue()+1, VT));
19126     }
19127   }
19128
19129   // Try to synthesize horizontal adds from adds of shuffles.
19130   EVT VT = N->getValueType(0);
19131   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19132        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19133       isHorizontalBinOp(Op0, Op1, true))
19134     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19135
19136   return OptimizeConditionalInDecrement(N, DAG);
19137 }
19138
19139 /// performVZEXTCombine - Performs build vector combines
19140 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19141                                         TargetLowering::DAGCombinerInfo &DCI,
19142                                         const X86Subtarget *Subtarget) {
19143   // (vzext (bitcast (vzext (x)) -> (vzext x)
19144   SDValue In = N->getOperand(0);
19145   while (In.getOpcode() == ISD::BITCAST)
19146     In = In.getOperand(0);
19147
19148   if (In.getOpcode() != X86ISD::VZEXT)
19149     return SDValue();
19150
19151   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19152                      In.getOperand(0));
19153 }
19154
19155 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19156                                              DAGCombinerInfo &DCI) const {
19157   SelectionDAG &DAG = DCI.DAG;
19158   switch (N->getOpcode()) {
19159   default: break;
19160   case ISD::EXTRACT_VECTOR_ELT:
19161     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19162   case ISD::VSELECT:
19163   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19164   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19165   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19166   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19167   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19168   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19169   case ISD::SHL:
19170   case ISD::SRA:
19171   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19172   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19173   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19174   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19175   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19176   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19177   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19178   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19179   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19180   case X86ISD::FXOR:
19181   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19182   case X86ISD::FMIN:
19183   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19184   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19185   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19186   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19187   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19188   case ISD::ANY_EXTEND:
19189   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19190   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19191   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19192   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19193   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
19194   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19195   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19196   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19197   case X86ISD::SHUFP:       // Handle all target specific shuffles
19198   case X86ISD::PALIGNR:
19199   case X86ISD::UNPCKH:
19200   case X86ISD::UNPCKL:
19201   case X86ISD::MOVHLPS:
19202   case X86ISD::MOVLHPS:
19203   case X86ISD::PSHUFD:
19204   case X86ISD::PSHUFHW:
19205   case X86ISD::PSHUFLW:
19206   case X86ISD::MOVSS:
19207   case X86ISD::MOVSD:
19208   case X86ISD::VPERMILP:
19209   case X86ISD::VPERM2X128:
19210   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19211   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19212   }
19213
19214   return SDValue();
19215 }
19216
19217 /// isTypeDesirableForOp - Return true if the target has native support for
19218 /// the specified value type and it is 'desirable' to use the type for the
19219 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19220 /// instruction encodings are longer and some i16 instructions are slow.
19221 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19222   if (!isTypeLegal(VT))
19223     return false;
19224   if (VT != MVT::i16)
19225     return true;
19226
19227   switch (Opc) {
19228   default:
19229     return true;
19230   case ISD::LOAD:
19231   case ISD::SIGN_EXTEND:
19232   case ISD::ZERO_EXTEND:
19233   case ISD::ANY_EXTEND:
19234   case ISD::SHL:
19235   case ISD::SRL:
19236   case ISD::SUB:
19237   case ISD::ADD:
19238   case ISD::MUL:
19239   case ISD::AND:
19240   case ISD::OR:
19241   case ISD::XOR:
19242     return false;
19243   }
19244 }
19245
19246 /// IsDesirableToPromoteOp - This method query the target whether it is
19247 /// beneficial for dag combiner to promote the specified node. If true, it
19248 /// should return the desired promotion type by reference.
19249 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19250   EVT VT = Op.getValueType();
19251   if (VT != MVT::i16)
19252     return false;
19253
19254   bool Promote = false;
19255   bool Commute = false;
19256   switch (Op.getOpcode()) {
19257   default: break;
19258   case ISD::LOAD: {
19259     LoadSDNode *LD = cast<LoadSDNode>(Op);
19260     // If the non-extending load has a single use and it's not live out, then it
19261     // might be folded.
19262     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19263                                                      Op.hasOneUse()*/) {
19264       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19265              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19266         // The only case where we'd want to promote LOAD (rather then it being
19267         // promoted as an operand is when it's only use is liveout.
19268         if (UI->getOpcode() != ISD::CopyToReg)
19269           return false;
19270       }
19271     }
19272     Promote = true;
19273     break;
19274   }
19275   case ISD::SIGN_EXTEND:
19276   case ISD::ZERO_EXTEND:
19277   case ISD::ANY_EXTEND:
19278     Promote = true;
19279     break;
19280   case ISD::SHL:
19281   case ISD::SRL: {
19282     SDValue N0 = Op.getOperand(0);
19283     // Look out for (store (shl (load), x)).
19284     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19285       return false;
19286     Promote = true;
19287     break;
19288   }
19289   case ISD::ADD:
19290   case ISD::MUL:
19291   case ISD::AND:
19292   case ISD::OR:
19293   case ISD::XOR:
19294     Commute = true;
19295     // fallthrough
19296   case ISD::SUB: {
19297     SDValue N0 = Op.getOperand(0);
19298     SDValue N1 = Op.getOperand(1);
19299     if (!Commute && MayFoldLoad(N1))
19300       return false;
19301     // Avoid disabling potential load folding opportunities.
19302     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19303       return false;
19304     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19305       return false;
19306     Promote = true;
19307   }
19308   }
19309
19310   PVT = MVT::i32;
19311   return Promote;
19312 }
19313
19314 //===----------------------------------------------------------------------===//
19315 //                           X86 Inline Assembly Support
19316 //===----------------------------------------------------------------------===//
19317
19318 namespace {
19319   // Helper to match a string separated by whitespace.
19320   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19321     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19322
19323     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19324       StringRef piece(*args[i]);
19325       if (!s.startswith(piece)) // Check if the piece matches.
19326         return false;
19327
19328       s = s.substr(piece.size());
19329       StringRef::size_type pos = s.find_first_not_of(" \t");
19330       if (pos == 0) // We matched a prefix.
19331         return false;
19332
19333       s = s.substr(pos);
19334     }
19335
19336     return s.empty();
19337   }
19338   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19339 }
19340
19341 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19342
19343   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19344     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19345         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19346         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19347
19348       if (AsmPieces.size() == 3)
19349         return true;
19350       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19351         return true;
19352     }
19353   }
19354   return false;
19355 }
19356
19357 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19358   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19359
19360   std::string AsmStr = IA->getAsmString();
19361
19362   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19363   if (!Ty || Ty->getBitWidth() % 16 != 0)
19364     return false;
19365
19366   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19367   SmallVector<StringRef, 4> AsmPieces;
19368   SplitString(AsmStr, AsmPieces, ";\n");
19369
19370   switch (AsmPieces.size()) {
19371   default: return false;
19372   case 1:
19373     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19374     // we will turn this bswap into something that will be lowered to logical
19375     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19376     // lower so don't worry about this.
19377     // bswap $0
19378     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19379         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19380         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19381         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19382         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19383         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19384       // No need to check constraints, nothing other than the equivalent of
19385       // "=r,0" would be valid here.
19386       return IntrinsicLowering::LowerToByteSwap(CI);
19387     }
19388
19389     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19390     if (CI->getType()->isIntegerTy(16) &&
19391         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19392         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19393          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19394       AsmPieces.clear();
19395       const std::string &ConstraintsStr = IA->getConstraintString();
19396       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19397       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19398       if (clobbersFlagRegisters(AsmPieces))
19399         return IntrinsicLowering::LowerToByteSwap(CI);
19400     }
19401     break;
19402   case 3:
19403     if (CI->getType()->isIntegerTy(32) &&
19404         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19405         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19406         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19407         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19408       AsmPieces.clear();
19409       const std::string &ConstraintsStr = IA->getConstraintString();
19410       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19411       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19412       if (clobbersFlagRegisters(AsmPieces))
19413         return IntrinsicLowering::LowerToByteSwap(CI);
19414     }
19415
19416     if (CI->getType()->isIntegerTy(64)) {
19417       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19418       if (Constraints.size() >= 2 &&
19419           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19420           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19421         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19422         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19423             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19424             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19425           return IntrinsicLowering::LowerToByteSwap(CI);
19426       }
19427     }
19428     break;
19429   }
19430   return false;
19431 }
19432
19433 /// getConstraintType - Given a constraint letter, return the type of
19434 /// constraint it is for this target.
19435 X86TargetLowering::ConstraintType
19436 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19437   if (Constraint.size() == 1) {
19438     switch (Constraint[0]) {
19439     case 'R':
19440     case 'q':
19441     case 'Q':
19442     case 'f':
19443     case 't':
19444     case 'u':
19445     case 'y':
19446     case 'x':
19447     case 'Y':
19448     case 'l':
19449       return C_RegisterClass;
19450     case 'a':
19451     case 'b':
19452     case 'c':
19453     case 'd':
19454     case 'S':
19455     case 'D':
19456     case 'A':
19457       return C_Register;
19458     case 'I':
19459     case 'J':
19460     case 'K':
19461     case 'L':
19462     case 'M':
19463     case 'N':
19464     case 'G':
19465     case 'C':
19466     case 'e':
19467     case 'Z':
19468       return C_Other;
19469     default:
19470       break;
19471     }
19472   }
19473   return TargetLowering::getConstraintType(Constraint);
19474 }
19475
19476 /// Examine constraint type and operand type and determine a weight value.
19477 /// This object must already have been set up with the operand type
19478 /// and the current alternative constraint selected.
19479 TargetLowering::ConstraintWeight
19480   X86TargetLowering::getSingleConstraintMatchWeight(
19481     AsmOperandInfo &info, const char *constraint) const {
19482   ConstraintWeight weight = CW_Invalid;
19483   Value *CallOperandVal = info.CallOperandVal;
19484     // If we don't have a value, we can't do a match,
19485     // but allow it at the lowest weight.
19486   if (CallOperandVal == NULL)
19487     return CW_Default;
19488   Type *type = CallOperandVal->getType();
19489   // Look at the constraint type.
19490   switch (*constraint) {
19491   default:
19492     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19493   case 'R':
19494   case 'q':
19495   case 'Q':
19496   case 'a':
19497   case 'b':
19498   case 'c':
19499   case 'd':
19500   case 'S':
19501   case 'D':
19502   case 'A':
19503     if (CallOperandVal->getType()->isIntegerTy())
19504       weight = CW_SpecificReg;
19505     break;
19506   case 'f':
19507   case 't':
19508   case 'u':
19509     if (type->isFloatingPointTy())
19510       weight = CW_SpecificReg;
19511     break;
19512   case 'y':
19513     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19514       weight = CW_SpecificReg;
19515     break;
19516   case 'x':
19517   case 'Y':
19518     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19519         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19520       weight = CW_Register;
19521     break;
19522   case 'I':
19523     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19524       if (C->getZExtValue() <= 31)
19525         weight = CW_Constant;
19526     }
19527     break;
19528   case 'J':
19529     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19530       if (C->getZExtValue() <= 63)
19531         weight = CW_Constant;
19532     }
19533     break;
19534   case 'K':
19535     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19536       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19537         weight = CW_Constant;
19538     }
19539     break;
19540   case 'L':
19541     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19542       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19543         weight = CW_Constant;
19544     }
19545     break;
19546   case 'M':
19547     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19548       if (C->getZExtValue() <= 3)
19549         weight = CW_Constant;
19550     }
19551     break;
19552   case 'N':
19553     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19554       if (C->getZExtValue() <= 0xff)
19555         weight = CW_Constant;
19556     }
19557     break;
19558   case 'G':
19559   case 'C':
19560     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19561       weight = CW_Constant;
19562     }
19563     break;
19564   case 'e':
19565     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19566       if ((C->getSExtValue() >= -0x80000000LL) &&
19567           (C->getSExtValue() <= 0x7fffffffLL))
19568         weight = CW_Constant;
19569     }
19570     break;
19571   case 'Z':
19572     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19573       if (C->getZExtValue() <= 0xffffffff)
19574         weight = CW_Constant;
19575     }
19576     break;
19577   }
19578   return weight;
19579 }
19580
19581 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19582 /// with another that has more specific requirements based on the type of the
19583 /// corresponding operand.
19584 const char *X86TargetLowering::
19585 LowerXConstraint(EVT ConstraintVT) const {
19586   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19587   // 'f' like normal targets.
19588   if (ConstraintVT.isFloatingPoint()) {
19589     if (Subtarget->hasSSE2())
19590       return "Y";
19591     if (Subtarget->hasSSE1())
19592       return "x";
19593   }
19594
19595   return TargetLowering::LowerXConstraint(ConstraintVT);
19596 }
19597
19598 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19599 /// vector.  If it is invalid, don't add anything to Ops.
19600 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19601                                                      std::string &Constraint,
19602                                                      std::vector<SDValue>&Ops,
19603                                                      SelectionDAG &DAG) const {
19604   SDValue Result(0, 0);
19605
19606   // Only support length 1 constraints for now.
19607   if (Constraint.length() > 1) return;
19608
19609   char ConstraintLetter = Constraint[0];
19610   switch (ConstraintLetter) {
19611   default: break;
19612   case 'I':
19613     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19614       if (C->getZExtValue() <= 31) {
19615         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19616         break;
19617       }
19618     }
19619     return;
19620   case 'J':
19621     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19622       if (C->getZExtValue() <= 63) {
19623         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19624         break;
19625       }
19626     }
19627     return;
19628   case 'K':
19629     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19630       if (isInt<8>(C->getSExtValue())) {
19631         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19632         break;
19633       }
19634     }
19635     return;
19636   case 'N':
19637     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19638       if (C->getZExtValue() <= 255) {
19639         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19640         break;
19641       }
19642     }
19643     return;
19644   case 'e': {
19645     // 32-bit signed value
19646     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19647       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19648                                            C->getSExtValue())) {
19649         // Widen to 64 bits here to get it sign extended.
19650         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19651         break;
19652       }
19653     // FIXME gcc accepts some relocatable values here too, but only in certain
19654     // memory models; it's complicated.
19655     }
19656     return;
19657   }
19658   case 'Z': {
19659     // 32-bit unsigned value
19660     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19661       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19662                                            C->getZExtValue())) {
19663         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19664         break;
19665       }
19666     }
19667     // FIXME gcc accepts some relocatable values here too, but only in certain
19668     // memory models; it's complicated.
19669     return;
19670   }
19671   case 'i': {
19672     // Literal immediates are always ok.
19673     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19674       // Widen to 64 bits here to get it sign extended.
19675       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19676       break;
19677     }
19678
19679     // In any sort of PIC mode addresses need to be computed at runtime by
19680     // adding in a register or some sort of table lookup.  These can't
19681     // be used as immediates.
19682     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19683       return;
19684
19685     // If we are in non-pic codegen mode, we allow the address of a global (with
19686     // an optional displacement) to be used with 'i'.
19687     GlobalAddressSDNode *GA = 0;
19688     int64_t Offset = 0;
19689
19690     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19691     while (1) {
19692       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19693         Offset += GA->getOffset();
19694         break;
19695       } else if (Op.getOpcode() == ISD::ADD) {
19696         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19697           Offset += C->getZExtValue();
19698           Op = Op.getOperand(0);
19699           continue;
19700         }
19701       } else if (Op.getOpcode() == ISD::SUB) {
19702         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19703           Offset += -C->getZExtValue();
19704           Op = Op.getOperand(0);
19705           continue;
19706         }
19707       }
19708
19709       // Otherwise, this isn't something we can handle, reject it.
19710       return;
19711     }
19712
19713     const GlobalValue *GV = GA->getGlobal();
19714     // If we require an extra load to get this address, as in PIC mode, we
19715     // can't accept it.
19716     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19717                                                         getTargetMachine())))
19718       return;
19719
19720     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19721                                         GA->getValueType(0), Offset);
19722     break;
19723   }
19724   }
19725
19726   if (Result.getNode()) {
19727     Ops.push_back(Result);
19728     return;
19729   }
19730   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19731 }
19732
19733 std::pair<unsigned, const TargetRegisterClass*>
19734 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19735                                                 MVT VT) const {
19736   // First, see if this is a constraint that directly corresponds to an LLVM
19737   // register class.
19738   if (Constraint.size() == 1) {
19739     // GCC Constraint Letters
19740     switch (Constraint[0]) {
19741     default: break;
19742       // TODO: Slight differences here in allocation order and leaving
19743       // RIP in the class. Do they matter any more here than they do
19744       // in the normal allocation?
19745     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19746       if (Subtarget->is64Bit()) {
19747         if (VT == MVT::i32 || VT == MVT::f32)
19748           return std::make_pair(0U, &X86::GR32RegClass);
19749         if (VT == MVT::i16)
19750           return std::make_pair(0U, &X86::GR16RegClass);
19751         if (VT == MVT::i8 || VT == MVT::i1)
19752           return std::make_pair(0U, &X86::GR8RegClass);
19753         if (VT == MVT::i64 || VT == MVT::f64)
19754           return std::make_pair(0U, &X86::GR64RegClass);
19755         break;
19756       }
19757       // 32-bit fallthrough
19758     case 'Q':   // Q_REGS
19759       if (VT == MVT::i32 || VT == MVT::f32)
19760         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19761       if (VT == MVT::i16)
19762         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19763       if (VT == MVT::i8 || VT == MVT::i1)
19764         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19765       if (VT == MVT::i64)
19766         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19767       break;
19768     case 'r':   // GENERAL_REGS
19769     case 'l':   // INDEX_REGS
19770       if (VT == MVT::i8 || VT == MVT::i1)
19771         return std::make_pair(0U, &X86::GR8RegClass);
19772       if (VT == MVT::i16)
19773         return std::make_pair(0U, &X86::GR16RegClass);
19774       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19775         return std::make_pair(0U, &X86::GR32RegClass);
19776       return std::make_pair(0U, &X86::GR64RegClass);
19777     case 'R':   // LEGACY_REGS
19778       if (VT == MVT::i8 || VT == MVT::i1)
19779         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19780       if (VT == MVT::i16)
19781         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19782       if (VT == MVT::i32 || !Subtarget->is64Bit())
19783         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19784       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19785     case 'f':  // FP Stack registers.
19786       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19787       // value to the correct fpstack register class.
19788       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19789         return std::make_pair(0U, &X86::RFP32RegClass);
19790       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19791         return std::make_pair(0U, &X86::RFP64RegClass);
19792       return std::make_pair(0U, &X86::RFP80RegClass);
19793     case 'y':   // MMX_REGS if MMX allowed.
19794       if (!Subtarget->hasMMX()) break;
19795       return std::make_pair(0U, &X86::VR64RegClass);
19796     case 'Y':   // SSE_REGS if SSE2 allowed
19797       if (!Subtarget->hasSSE2()) break;
19798       // FALL THROUGH.
19799     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19800       if (!Subtarget->hasSSE1()) break;
19801
19802       switch (VT.SimpleTy) {
19803       default: break;
19804       // Scalar SSE types.
19805       case MVT::f32:
19806       case MVT::i32:
19807         return std::make_pair(0U, &X86::FR32RegClass);
19808       case MVT::f64:
19809       case MVT::i64:
19810         return std::make_pair(0U, &X86::FR64RegClass);
19811       // Vector types.
19812       case MVT::v16i8:
19813       case MVT::v8i16:
19814       case MVT::v4i32:
19815       case MVT::v2i64:
19816       case MVT::v4f32:
19817       case MVT::v2f64:
19818         return std::make_pair(0U, &X86::VR128RegClass);
19819       // AVX types.
19820       case MVT::v32i8:
19821       case MVT::v16i16:
19822       case MVT::v8i32:
19823       case MVT::v4i64:
19824       case MVT::v8f32:
19825       case MVT::v4f64:
19826         return std::make_pair(0U, &X86::VR256RegClass);
19827       case MVT::v8f64:
19828       case MVT::v16f32:
19829       case MVT::v16i32:
19830       case MVT::v8i64:
19831         return std::make_pair(0U, &X86::VR512RegClass);
19832       }
19833       break;
19834     }
19835   }
19836
19837   // Use the default implementation in TargetLowering to convert the register
19838   // constraint into a member of a register class.
19839   std::pair<unsigned, const TargetRegisterClass*> Res;
19840   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19841
19842   // Not found as a standard register?
19843   if (Res.second == 0) {
19844     // Map st(0) -> st(7) -> ST0
19845     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19846         tolower(Constraint[1]) == 's' &&
19847         tolower(Constraint[2]) == 't' &&
19848         Constraint[3] == '(' &&
19849         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19850         Constraint[5] == ')' &&
19851         Constraint[6] == '}') {
19852
19853       Res.first = X86::ST0+Constraint[4]-'0';
19854       Res.second = &X86::RFP80RegClass;
19855       return Res;
19856     }
19857
19858     // GCC allows "st(0)" to be called just plain "st".
19859     if (StringRef("{st}").equals_lower(Constraint)) {
19860       Res.first = X86::ST0;
19861       Res.second = &X86::RFP80RegClass;
19862       return Res;
19863     }
19864
19865     // flags -> EFLAGS
19866     if (StringRef("{flags}").equals_lower(Constraint)) {
19867       Res.first = X86::EFLAGS;
19868       Res.second = &X86::CCRRegClass;
19869       return Res;
19870     }
19871
19872     // 'A' means EAX + EDX.
19873     if (Constraint == "A") {
19874       Res.first = X86::EAX;
19875       Res.second = &X86::GR32_ADRegClass;
19876       return Res;
19877     }
19878     return Res;
19879   }
19880
19881   // Otherwise, check to see if this is a register class of the wrong value
19882   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19883   // turn into {ax},{dx}.
19884   if (Res.second->hasType(VT))
19885     return Res;   // Correct type already, nothing to do.
19886
19887   // All of the single-register GCC register classes map their values onto
19888   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19889   // really want an 8-bit or 32-bit register, map to the appropriate register
19890   // class and return the appropriate register.
19891   if (Res.second == &X86::GR16RegClass) {
19892     if (VT == MVT::i8 || VT == MVT::i1) {
19893       unsigned DestReg = 0;
19894       switch (Res.first) {
19895       default: break;
19896       case X86::AX: DestReg = X86::AL; break;
19897       case X86::DX: DestReg = X86::DL; break;
19898       case X86::CX: DestReg = X86::CL; break;
19899       case X86::BX: DestReg = X86::BL; break;
19900       }
19901       if (DestReg) {
19902         Res.first = DestReg;
19903         Res.second = &X86::GR8RegClass;
19904       }
19905     } else if (VT == MVT::i32 || VT == MVT::f32) {
19906       unsigned DestReg = 0;
19907       switch (Res.first) {
19908       default: break;
19909       case X86::AX: DestReg = X86::EAX; break;
19910       case X86::DX: DestReg = X86::EDX; break;
19911       case X86::CX: DestReg = X86::ECX; break;
19912       case X86::BX: DestReg = X86::EBX; break;
19913       case X86::SI: DestReg = X86::ESI; break;
19914       case X86::DI: DestReg = X86::EDI; break;
19915       case X86::BP: DestReg = X86::EBP; break;
19916       case X86::SP: DestReg = X86::ESP; break;
19917       }
19918       if (DestReg) {
19919         Res.first = DestReg;
19920         Res.second = &X86::GR32RegClass;
19921       }
19922     } else if (VT == MVT::i64 || VT == MVT::f64) {
19923       unsigned DestReg = 0;
19924       switch (Res.first) {
19925       default: break;
19926       case X86::AX: DestReg = X86::RAX; break;
19927       case X86::DX: DestReg = X86::RDX; break;
19928       case X86::CX: DestReg = X86::RCX; break;
19929       case X86::BX: DestReg = X86::RBX; break;
19930       case X86::SI: DestReg = X86::RSI; break;
19931       case X86::DI: DestReg = X86::RDI; break;
19932       case X86::BP: DestReg = X86::RBP; break;
19933       case X86::SP: DestReg = X86::RSP; break;
19934       }
19935       if (DestReg) {
19936         Res.first = DestReg;
19937         Res.second = &X86::GR64RegClass;
19938       }
19939     }
19940   } else if (Res.second == &X86::FR32RegClass ||
19941              Res.second == &X86::FR64RegClass ||
19942              Res.second == &X86::VR128RegClass ||
19943              Res.second == &X86::VR256RegClass ||
19944              Res.second == &X86::FR32XRegClass ||
19945              Res.second == &X86::FR64XRegClass ||
19946              Res.second == &X86::VR128XRegClass ||
19947              Res.second == &X86::VR256XRegClass ||
19948              Res.second == &X86::VR512RegClass) {
19949     // Handle references to XMM physical registers that got mapped into the
19950     // wrong class.  This can happen with constraints like {xmm0} where the
19951     // target independent register mapper will just pick the first match it can
19952     // find, ignoring the required type.
19953
19954     if (VT == MVT::f32 || VT == MVT::i32)
19955       Res.second = &X86::FR32RegClass;
19956     else if (VT == MVT::f64 || VT == MVT::i64)
19957       Res.second = &X86::FR64RegClass;
19958     else if (X86::VR128RegClass.hasType(VT))
19959       Res.second = &X86::VR128RegClass;
19960     else if (X86::VR256RegClass.hasType(VT))
19961       Res.second = &X86::VR256RegClass;
19962     else if (X86::VR512RegClass.hasType(VT))
19963       Res.second = &X86::VR512RegClass;
19964   }
19965
19966   return Res;
19967 }