2c991aa8e245d4782c77c8a1daca6288adf9ae60
[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/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetWindows())
193     return new X86WindowsTargetObjectFile();
194   if (Subtarget->isTargetCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(TM)) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird, it always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit since we have so many registers use the ILP scheduler, for
234   // 32-bit code use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2
247   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248     addBypassSlowDiv(32, 8);
249     if (Subtarget->is64Bit())
250       addBypassSlowDiv(64, 16);
251   }
252
253   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
254     // Setup Windows compiler runtime calls.
255     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257     setLibcallName(RTLIB::SREM_I64, "_allrem");
258     setLibcallName(RTLIB::UREM_I64, "_aullrem");
259     setLibcallName(RTLIB::MUL_I64, "_allmul");
260     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265
266     // The _ftol2 runtime function has an unusual calling conv, which
267     // is modeled by a special pseudo-instruction.
268     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
272   }
273
274   if (Subtarget->isTargetDarwin()) {
275     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276     setUseUnderscoreSetJmp(false);
277     setUseUnderscoreLongJmp(false);
278   } else if (Subtarget->isTargetMingw()) {
279     // MS runtime is weird: it exports _setjmp, but longjmp!
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(false);
282   } else {
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(true);
285   }
286
287   // Set up the register classes.
288   addRegisterClass(MVT::i8, &X86::GR8RegClass);
289   addRegisterClass(MVT::i16, &X86::GR16RegClass);
290   addRegisterClass(MVT::i32, &X86::GR32RegClass);
291   if (Subtarget->is64Bit())
292     addRegisterClass(MVT::i64, &X86::GR64RegClass);
293
294   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295
296   // We don't accept any truncstore of integer registers.
297   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
303
304   // SETOEQ and SETUNE require checking two conditions.
305   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311
312   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313   // operation.
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
321   } else if (!TM.Options.UseSoftFloat) {
322     // We have an algorithm for SSE2->double, and we turn this into a
323     // 64-bit FILD followed by conditional FADD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
325     // We have an algorithm for SSE2, and we turn this into a 64-bit
326     // FILD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
328   }
329
330   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331   // this operation.
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
334
335   if (!TM.Options.UseSoftFloat) {
336     // SSE has no i16 to fp conversion, only i32
337     if (X86ScalarSSEf32) {
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
339       // f32 and f64 cases are Legal, f80 case is not
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     } else {
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     }
345   } else {
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
348   }
349
350   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
351   // are Legal, f80 is custom lowered.
352   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
353   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
354
355   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
359
360   if (X86ScalarSSEf32) {
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
362     // f32 and f64 cases are Legal, f80 case is not
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   } else {
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   }
368
369   // Handle FP_TO_UINT by promoting the destination to a larger signed
370   // conversion.
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
374
375   if (Subtarget->is64Bit()) {
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
378   } else if (!TM.Options.UseSoftFloat) {
379     // Since AVX is a superset of SSE3, only check for SSE here.
380     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381       // Expand FP_TO_UINT into a select.
382       // FIXME: We would like to use a Custom expander here eventually to do
383       // the optimal thing for SSE vs. the default expansion in the legalizer.
384       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
385     else
386       // With SSE3 we can use fisttpll to convert to a signed i64; without
387       // SSE, we're stuck with a fistpll.
388       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
389   }
390
391   if (isTargetFTOL()) {
392     // Use the _ftol2 runtime function, which has a pseudo-instruction
393     // to handle its weird calling convention.
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
395   }
396
397   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398   if (!X86ScalarSSEf64) {
399     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
400     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
401     if (Subtarget->is64Bit()) {
402       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
403       // Without SSE, i64->f64 goes through memory.
404       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
405     }
406   }
407
408   // Scalar integer divide and remainder are lowered to use operations that
409   // produce two results, to match the available instructions. This exposes
410   // the two-result form to trivial CSE, which is able to combine x/y and x%y
411   // into a single instruction.
412   //
413   // Scalar integer multiply-high is also lowered to use two-result
414   // operations, to match the available instructions. However, plain multiply
415   // (low) operations are left as Legal, as there are single-result
416   // instructions for this in x86. Using the two-result multiply instructions
417   // when both high and low results are needed must be arranged by dagcombine.
418   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419     MVT VT = IntVTs[i];
420     setOperationAction(ISD::MULHS, VT, Expand);
421     setOperationAction(ISD::MULHU, VT, Expand);
422     setOperationAction(ISD::SDIV, VT, Expand);
423     setOperationAction(ISD::UDIV, VT, Expand);
424     setOperationAction(ISD::SREM, VT, Expand);
425     setOperationAction(ISD::UREM, VT, Expand);
426
427     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428     setOperationAction(ISD::ADDC, VT, Custom);
429     setOperationAction(ISD::ADDE, VT, Custom);
430     setOperationAction(ISD::SUBC, VT, Custom);
431     setOperationAction(ISD::SUBE, VT, Custom);
432   }
433
434   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
435   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
436   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
443   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
444   if (Subtarget->is64Bit())
445     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
449   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
453   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
454
455   // Promote the i8 variants and force them on up to i32 which has a shorter
456   // encoding.
457   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
459   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
460   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
461   if (Subtarget->hasBMI()) {
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
466   } else {
467     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
468     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
469     if (Subtarget->is64Bit())
470       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasLZCNT()) {
474     // When promoting the i8 variants, force them to i32 for a shorter
475     // encoding.
476     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
479     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
482     if (Subtarget->is64Bit())
483       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
484   } else {
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
491     if (Subtarget->is64Bit()) {
492       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
493       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
494     }
495   }
496
497   if (Subtarget->hasPOPCNT()) {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
499   } else {
500     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
505   }
506
507   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
508
509   if (!Subtarget->hasMOVBE())
510     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
511
512   // These should be promoted to a larger select which is supported.
513   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
514   // X86 wants to expand cmov itself.
515   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
516   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
529     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
530   }
531   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
532   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534   // support continuation, user-level threading, and etc.. As a result, no
535   // other SjLj exception interfaces are implemented and please don't build
536   // your own exception handling based on them.
537   // LLVM/Clang supports zero-cost DWARF exception handling.
538   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
540
541   // Darwin ABI issue.
542   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
543   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
544   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
546   if (Subtarget->is64Bit())
547     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
549   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
550   if (Subtarget->is64Bit()) {
551     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
552     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
553     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
554     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
555     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
556   }
557   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
559   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
561   if (Subtarget->is64Bit()) {
562     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
563     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
565   }
566
567   if (Subtarget->hasSSE1())
568     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
569
570   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
571
572   // Expand certain atomics
573   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
574     MVT VT = IntVTs[i];
575     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
578   }
579
580   if (!Subtarget->is64Bit()) {
581     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
593   }
594
595   if (Subtarget->hasCmpxchg16b()) {
596     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
597   }
598
599   // FIXME - use subtarget debug flags
600   if (!Subtarget->isTargetDarwin() &&
601       !Subtarget->isTargetELF() &&
602       !Subtarget->isTargetCygMing()) {
603     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
604   }
605
606   if (Subtarget->is64Bit()) {
607     setExceptionPointerRegister(X86::RAX);
608     setExceptionSelectorRegister(X86::RDX);
609   } else {
610     setExceptionPointerRegister(X86::EAX);
611     setExceptionSelectorRegister(X86::EDX);
612   }
613   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
615
616   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
618
619   setOperationAction(ISD::TRAP, MVT::Other, Legal);
620   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
621
622   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
624   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
625   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626     // TargetInfo::X86_64ABIBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
629   } else {
630     // TargetInfo::CharPtrBuiltinVaList
631     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
632     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
633   }
634
635   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
636   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
637
638   if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
639     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                        MVT::i64 : MVT::i32, Custom);
641   else if (TM.Options.EnableSegmentedStacks)
642     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643                        MVT::i64 : MVT::i32, Custom);
644   else
645     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646                        MVT::i64 : MVT::i32, Expand);
647
648   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649     // f32 and f64 use SSE.
650     // Set up the FP register classes.
651     addRegisterClass(MVT::f32, &X86::FR32RegClass);
652     addRegisterClass(MVT::f64, &X86::FR64RegClass);
653
654     // Use ANDPD to simulate FABS.
655     setOperationAction(ISD::FABS , MVT::f64, Custom);
656     setOperationAction(ISD::FABS , MVT::f32, Custom);
657
658     // Use XORP to simulate FNEG.
659     setOperationAction(ISD::FNEG , MVT::f64, Custom);
660     setOperationAction(ISD::FNEG , MVT::f32, Custom);
661
662     // Use ANDPD and ORPD to simulate FCOPYSIGN.
663     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
665
666     // Lower this to FGETSIGNx86 plus an AND.
667     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
669
670     // We don't support sin/cos/fmod
671     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
672     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
673     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
675     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
676     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
677
678     // Expand FP immediates into loads from the stack, except for the special
679     // cases we handle.
680     addLegalFPImmediate(APFloat(+0.0)); // xorpd
681     addLegalFPImmediate(APFloat(+0.0f)); // xorps
682   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683     // Use SSE for f32, x87 for f64.
684     // Set up the FP register classes.
685     addRegisterClass(MVT::f32, &X86::FR32RegClass);
686     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
687
688     // Use ANDPS to simulate FABS.
689     setOperationAction(ISD::FABS , MVT::f32, Custom);
690
691     // Use XORP to simulate FNEG.
692     setOperationAction(ISD::FNEG , MVT::f32, Custom);
693
694     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
695
696     // Use ANDPS and ORPS to simulate FCOPYSIGN.
697     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
699
700     // We don't support sin/cos/fmod
701     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
702     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
703     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704
705     // Special cases we handle for FP constants.
706     addLegalFPImmediate(APFloat(+0.0f)); // xorps
707     addLegalFPImmediate(APFloat(+0.0)); // FLD0
708     addLegalFPImmediate(APFloat(+1.0)); // FLD1
709     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
711
712     if (!TM.Options.UnsafeFPMath) {
713       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
714       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
715       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
716     }
717   } else if (!TM.Options.UseSoftFloat) {
718     // f32 and f64 in x87.
719     // Set up the FP register classes.
720     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
722
723     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
724     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
725     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
730       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
733       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
735     }
736     addLegalFPImmediate(APFloat(+0.0)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
744   }
745
746   // We don't support FMA.
747   setOperationAction(ISD::FMA, MVT::f64, Expand);
748   setOperationAction(ISD::FMA, MVT::f32, Expand);
749
750   // Long double always uses X87.
751   if (!TM.Options.UseSoftFloat) {
752     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
754     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
755     {
756       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757       addLegalFPImmediate(TmpFlt);  // FLD0
758       TmpFlt.changeSign();
759       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
760
761       bool ignored;
762       APFloat TmpFlt2(+1.0);
763       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
764                       &ignored);
765       addLegalFPImmediate(TmpFlt2);  // FLD1
766       TmpFlt2.changeSign();
767       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
768     }
769
770     if (!TM.Options.UnsafeFPMath) {
771       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
772       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
773       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
774     }
775
776     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
778     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
780     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781     setOperationAction(ISD::FMA, MVT::f80, Expand);
782   }
783
784   // Always use a library call for pow.
785   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
786   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
787   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
788
789   setOperationAction(ISD::FLOG, MVT::f80, Expand);
790   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792   setOperationAction(ISD::FEXP, MVT::f80, Expand);
793   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
794
795   // First set operation action for all vector types to either promote
796   // (for widening) or expand (for scalarization). Then we will selectively
797   // turn on ones that can be effectively codegen'd.
798   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800     MVT VT = (MVT::SimpleValueType)i;
801     setOperationAction(ISD::ADD , VT, Expand);
802     setOperationAction(ISD::SUB , VT, Expand);
803     setOperationAction(ISD::FADD, VT, Expand);
804     setOperationAction(ISD::FNEG, VT, Expand);
805     setOperationAction(ISD::FSUB, VT, Expand);
806     setOperationAction(ISD::MUL , VT, Expand);
807     setOperationAction(ISD::FMUL, VT, Expand);
808     setOperationAction(ISD::SDIV, VT, Expand);
809     setOperationAction(ISD::UDIV, VT, Expand);
810     setOperationAction(ISD::FDIV, VT, Expand);
811     setOperationAction(ISD::SREM, VT, Expand);
812     setOperationAction(ISD::UREM, VT, Expand);
813     setOperationAction(ISD::LOAD, VT, Expand);
814     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819     setOperationAction(ISD::FABS, VT, Expand);
820     setOperationAction(ISD::FSIN, VT, Expand);
821     setOperationAction(ISD::FSINCOS, VT, Expand);
822     setOperationAction(ISD::FCOS, VT, Expand);
823     setOperationAction(ISD::FSINCOS, VT, Expand);
824     setOperationAction(ISD::FREM, VT, Expand);
825     setOperationAction(ISD::FMA,  VT, Expand);
826     setOperationAction(ISD::FPOWI, VT, Expand);
827     setOperationAction(ISD::FSQRT, VT, Expand);
828     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829     setOperationAction(ISD::FFLOOR, VT, Expand);
830     setOperationAction(ISD::FCEIL, VT, Expand);
831     setOperationAction(ISD::FTRUNC, VT, Expand);
832     setOperationAction(ISD::FRINT, VT, Expand);
833     setOperationAction(ISD::FNEARBYINT, VT, Expand);
834     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836     setOperationAction(ISD::SDIVREM, VT, Expand);
837     setOperationAction(ISD::UDIVREM, VT, Expand);
838     setOperationAction(ISD::FPOW, VT, Expand);
839     setOperationAction(ISD::CTPOP, VT, Expand);
840     setOperationAction(ISD::CTTZ, VT, Expand);
841     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::CTLZ, VT, Expand);
843     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
844     setOperationAction(ISD::SHL, VT, Expand);
845     setOperationAction(ISD::SRA, VT, Expand);
846     setOperationAction(ISD::SRL, VT, Expand);
847     setOperationAction(ISD::ROTL, VT, Expand);
848     setOperationAction(ISD::ROTR, VT, Expand);
849     setOperationAction(ISD::BSWAP, VT, Expand);
850     setOperationAction(ISD::SETCC, VT, Expand);
851     setOperationAction(ISD::FLOG, VT, Expand);
852     setOperationAction(ISD::FLOG2, VT, Expand);
853     setOperationAction(ISD::FLOG10, VT, Expand);
854     setOperationAction(ISD::FEXP, VT, Expand);
855     setOperationAction(ISD::FEXP2, VT, Expand);
856     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
857     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
858     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
859     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
861     setOperationAction(ISD::TRUNCATE, VT, Expand);
862     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
863     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
864     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
865     setOperationAction(ISD::VSELECT, VT, Expand);
866     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
867              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
868       setTruncStoreAction(VT,
869                           (MVT::SimpleValueType)InnerVT, Expand);
870     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
871     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
872     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
873   }
874
875   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
876   // with -msoft-float, disable use of MMX as well.
877   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
878     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
879     // No operations on x86mmx supported, everything uses intrinsics.
880   }
881
882   // MMX-sized vectors (other than x86mmx) are expected to be expanded
883   // into smaller operations.
884   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
885   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
886   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
887   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
888   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
889   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
890   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
891   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
892   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
893   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
894   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
895   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
896   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
897   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
898   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
899   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
902   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
903   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
904   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
906   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
907   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
908   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
911   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
912   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
913
914   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
915     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
916
917     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
920     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
921     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
922     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
923     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
924     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
925     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
926     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
927     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
928     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
929   }
930
931   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
932     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
933
934     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
935     // registers cannot be used even for integer operations.
936     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
937     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
938     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
939     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
940
941     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
942     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
943     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
944     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
945     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
946     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
947     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
948     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
949     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
950     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
951     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
952     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
957     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
958     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
959
960     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
964
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
966     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
970
971     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
972     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
973       MVT VT = (MVT::SimpleValueType)i;
974       // Do not attempt to custom lower non-power-of-2 vectors
975       if (!isPowerOf2_32(VT.getVectorNumElements()))
976         continue;
977       // Do not attempt to custom lower non-128-bit vectors
978       if (!VT.is128BitVector())
979         continue;
980       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
981       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
982       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
983     }
984
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
986     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
988     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991
992     if (Subtarget->is64Bit()) {
993       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
994       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
995     }
996
997     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
998     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
999       MVT VT = (MVT::SimpleValueType)i;
1000
1001       // Do not attempt to promote non-128-bit vectors
1002       if (!VT.is128BitVector())
1003         continue;
1004
1005       setOperationAction(ISD::AND,    VT, Promote);
1006       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1007       setOperationAction(ISD::OR,     VT, Promote);
1008       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1009       setOperationAction(ISD::XOR,    VT, Promote);
1010       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1011       setOperationAction(ISD::LOAD,   VT, Promote);
1012       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1013       setOperationAction(ISD::SELECT, VT, Promote);
1014       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1015     }
1016
1017     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018
1019     // Custom lower v2i64 and v2f64 selects.
1020     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1021     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1022     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1023     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1024
1025     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1026     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1027
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1029     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1030     // As there is no 64-bit GPR available, we need build a special custom
1031     // sequence to convert from v2i32 to v2f32.
1032     if (!Subtarget->is64Bit())
1033       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1034
1035     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1036     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1037
1038     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1039   }
1040
1041   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1042     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1043     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1044     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1045     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1046     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1047     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1048     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1049     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1050     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1051     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1052
1053     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1054     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1055     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1056     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1057     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1059     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1060     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1061     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1062     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1063
1064     // FIXME: Do we need to handle scalar-to-vector here?
1065     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1066
1067     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1069     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1070     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1071     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1072
1073     // i8 and i16 vectors are custom , because the source register and source
1074     // source memory operand types are not the same width.  f32 vectors are
1075     // custom since the immediate controlling the insert encodes additional
1076     // information.
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1079     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1080     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1081
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1086
1087     // FIXME: these should be Legal but thats only for the case where
1088     // the index is constant.  For now custom expand to deal with that.
1089     if (Subtarget->is64Bit()) {
1090       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1091       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1092     }
1093   }
1094
1095   if (Subtarget->hasSSE2()) {
1096     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1101
1102     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1103     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1104
1105     // In the customized shift lowering, the legal cases in AVX2 will be
1106     // recognized.
1107     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1114
1115     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1116     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1117   }
1118
1119   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1120     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1122     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1123     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1124     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1125     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1126
1127     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1129     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1130
1131     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1133     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1134     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1135     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1137     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1138     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1139     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1140     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1141     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1142     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1143
1144     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1147     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1148     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1150     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1151     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1152     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1153     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1154     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1155     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1156
1157     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1158
1159     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1161     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1162     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1163
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1166
1167     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1168
1169     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1179
1180     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1184
1185     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1187     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1193
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1198     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1199     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1200     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1201     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1202     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1203     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1204     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1205     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1206
1207     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1208       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1210       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1212       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1213       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1214     }
1215
1216     if (Subtarget->hasInt256()) {
1217       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1218       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1219       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1220       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1221
1222       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1223       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1224       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1225       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1226
1227       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1228       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1229       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1230       // Don't lower v32i8 because there is no 128-bit byte mul
1231
1232       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1233
1234       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1235     } else {
1236       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1237       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1238       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1239       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1240
1241       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1242       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1243       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1244       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1245
1246       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1247       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1248       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1249       // Don't lower v32i8 because there is no 128-bit byte mul
1250     }
1251
1252     // In the customized shift lowering, the legal cases in AVX2 will be
1253     // recognized.
1254     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1255     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1256
1257     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1258     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1259
1260     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1261
1262     // Custom lower several nodes for 256-bit types.
1263     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1264              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1265       MVT VT = (MVT::SimpleValueType)i;
1266
1267       // Extract subvector is special because the value type
1268       // (result) is 128-bit but the source is 256-bit wide.
1269       if (VT.is128BitVector())
1270         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1271
1272       // Do not attempt to custom lower other non-256-bit vectors
1273       if (!VT.is256BitVector())
1274         continue;
1275
1276       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1277       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1278       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1279       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1280       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1281       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1282       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1283     }
1284
1285     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1286     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1287       MVT VT = (MVT::SimpleValueType)i;
1288
1289       // Do not attempt to promote non-256-bit vectors
1290       if (!VT.is256BitVector())
1291         continue;
1292
1293       setOperationAction(ISD::AND,    VT, Promote);
1294       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1295       setOperationAction(ISD::OR,     VT, Promote);
1296       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1297       setOperationAction(ISD::XOR,    VT, Promote);
1298       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1299       setOperationAction(ISD::LOAD,   VT, Promote);
1300       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1301       setOperationAction(ISD::SELECT, VT, Promote);
1302       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303     }
1304   }
1305
1306   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1307     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1308     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1309     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1310     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1311
1312     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1313     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1314     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1315
1316     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1317     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1318     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1319     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1320     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1321     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1325     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1326     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1327
1328     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1330     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1333     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1334
1335     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1337     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1338     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1340     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1341     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1342     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1343     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1344
1345     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1346     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1347     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1348     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1349     if (Subtarget->is64Bit()) {
1350       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1351       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1352       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1353       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1354     }
1355     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1358     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1361     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1362     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1363
1364     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1369     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1370     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1371     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1373     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1376     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1377
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1383     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1384
1385     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1386     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1387
1388     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1389
1390     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1391     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1392     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1393     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1394     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1395     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1396     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1397
1398     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1399     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1400
1401     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1402     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1403
1404     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1405
1406     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1407     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1408
1409     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1410     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1411
1412     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1413     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1414
1415     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1416     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1417     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1418     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1419     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1420     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1421
1422     // Custom lower several nodes.
1423     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1424              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1425       MVT VT = (MVT::SimpleValueType)i;
1426
1427       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1428       // Extract subvector is special because the value type
1429       // (result) is 256/128-bit but the source is 512-bit wide.
1430       if (VT.is128BitVector() || VT.is256BitVector())
1431         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1432
1433       if (VT.getVectorElementType() == MVT::i1)
1434         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1435
1436       // Do not attempt to custom lower other non-512-bit vectors
1437       if (!VT.is512BitVector())
1438         continue;
1439
1440       if ( EltSize >= 32) {
1441         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1442         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1443         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1444         setOperationAction(ISD::VSELECT,             VT, Legal);
1445         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1446         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1447         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1448       }
1449     }
1450     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1451       MVT VT = (MVT::SimpleValueType)i;
1452
1453       // Do not attempt to promote non-256-bit vectors
1454       if (!VT.is512BitVector())
1455         continue;
1456
1457       setOperationAction(ISD::SELECT, VT, Promote);
1458       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1459     }
1460   }// has  AVX-512
1461
1462   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1463   // of this type with custom code.
1464   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1465            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1466     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1467                        Custom);
1468   }
1469
1470   // We want to custom lower some of our intrinsics.
1471   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1472   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1473   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1474
1475   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1476   // handle type legalization for these operations here.
1477   //
1478   // FIXME: We really should do custom legalization for addition and
1479   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1480   // than generic legalization for 64-bit multiplication-with-overflow, though.
1481   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1482     // Add/Sub/Mul with overflow operations are custom lowered.
1483     MVT VT = IntVTs[i];
1484     setOperationAction(ISD::SADDO, VT, Custom);
1485     setOperationAction(ISD::UADDO, VT, Custom);
1486     setOperationAction(ISD::SSUBO, VT, Custom);
1487     setOperationAction(ISD::USUBO, VT, Custom);
1488     setOperationAction(ISD::SMULO, VT, Custom);
1489     setOperationAction(ISD::UMULO, VT, Custom);
1490   }
1491
1492   // There are no 8-bit 3-address imul/mul instructions
1493   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1494   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1495
1496   if (!Subtarget->is64Bit()) {
1497     // These libcalls are not available in 32-bit.
1498     setLibcallName(RTLIB::SHL_I128, 0);
1499     setLibcallName(RTLIB::SRL_I128, 0);
1500     setLibcallName(RTLIB::SRA_I128, 0);
1501   }
1502
1503   // Combine sin / cos into one node or libcall if possible.
1504   if (Subtarget->hasSinCos()) {
1505     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1506     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1507     if (Subtarget->isTargetDarwin()) {
1508       // For MacOSX, we don't want to the normal expansion of a libcall to
1509       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1510       // traffic.
1511       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1512       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1513     }
1514   }
1515
1516   // We have target-specific dag combine patterns for the following nodes:
1517   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1518   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1519   setTargetDAGCombine(ISD::VSELECT);
1520   setTargetDAGCombine(ISD::SELECT);
1521   setTargetDAGCombine(ISD::SHL);
1522   setTargetDAGCombine(ISD::SRA);
1523   setTargetDAGCombine(ISD::SRL);
1524   setTargetDAGCombine(ISD::OR);
1525   setTargetDAGCombine(ISD::AND);
1526   setTargetDAGCombine(ISD::ADD);
1527   setTargetDAGCombine(ISD::FADD);
1528   setTargetDAGCombine(ISD::FSUB);
1529   setTargetDAGCombine(ISD::FMA);
1530   setTargetDAGCombine(ISD::SUB);
1531   setTargetDAGCombine(ISD::LOAD);
1532   setTargetDAGCombine(ISD::STORE);
1533   setTargetDAGCombine(ISD::ZERO_EXTEND);
1534   setTargetDAGCombine(ISD::ANY_EXTEND);
1535   setTargetDAGCombine(ISD::SIGN_EXTEND);
1536   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1537   setTargetDAGCombine(ISD::TRUNCATE);
1538   setTargetDAGCombine(ISD::SINT_TO_FP);
1539   setTargetDAGCombine(ISD::SETCC);
1540   if (Subtarget->is64Bit())
1541     setTargetDAGCombine(ISD::MUL);
1542   setTargetDAGCombine(ISD::XOR);
1543
1544   computeRegisterProperties();
1545
1546   // On Darwin, -Os means optimize for size without hurting performance,
1547   // do not reduce the limit.
1548   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1549   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1550   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1551   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1552   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1553   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1554   setPrefLoopAlignment(4); // 2^4 bytes.
1555
1556   // Predictable cmov don't hurt on atom because it's in-order.
1557   PredictableSelectIsExpensive = !Subtarget->isAtom();
1558
1559   setPrefFunctionAlignment(4); // 2^4 bytes.
1560 }
1561
1562 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1563   if (!VT.isVector())
1564     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1565
1566   if (Subtarget->hasAVX512())
1567     switch(VT.getVectorNumElements()) {
1568     case  8: return MVT::v8i1;
1569     case 16: return MVT::v16i1;
1570   }
1571
1572   return VT.changeVectorElementTypeToInteger();
1573 }
1574
1575 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1576 /// the desired ByVal argument alignment.
1577 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1578   if (MaxAlign == 16)
1579     return;
1580   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1581     if (VTy->getBitWidth() == 128)
1582       MaxAlign = 16;
1583   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1584     unsigned EltAlign = 0;
1585     getMaxByValAlign(ATy->getElementType(), EltAlign);
1586     if (EltAlign > MaxAlign)
1587       MaxAlign = EltAlign;
1588   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1589     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1590       unsigned EltAlign = 0;
1591       getMaxByValAlign(STy->getElementType(i), EltAlign);
1592       if (EltAlign > MaxAlign)
1593         MaxAlign = EltAlign;
1594       if (MaxAlign == 16)
1595         break;
1596     }
1597   }
1598 }
1599
1600 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1601 /// function arguments in the caller parameter area. For X86, aggregates
1602 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1603 /// are at 4-byte boundaries.
1604 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1605   if (Subtarget->is64Bit()) {
1606     // Max of 8 and alignment of type.
1607     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1608     if (TyAlign > 8)
1609       return TyAlign;
1610     return 8;
1611   }
1612
1613   unsigned Align = 4;
1614   if (Subtarget->hasSSE1())
1615     getMaxByValAlign(Ty, Align);
1616   return Align;
1617 }
1618
1619 /// getOptimalMemOpType - Returns the target specific optimal type for load
1620 /// and store operations as a result of memset, memcpy, and memmove
1621 /// lowering. If DstAlign is zero that means it's safe to destination
1622 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1623 /// means there isn't a need to check it against alignment requirement,
1624 /// probably because the source does not need to be loaded. If 'IsMemset' is
1625 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1626 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1627 /// source is constant so it does not need to be loaded.
1628 /// It returns EVT::Other if the type should be determined using generic
1629 /// target-independent logic.
1630 EVT
1631 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1632                                        unsigned DstAlign, unsigned SrcAlign,
1633                                        bool IsMemset, bool ZeroMemset,
1634                                        bool MemcpyStrSrc,
1635                                        MachineFunction &MF) const {
1636   const Function *F = MF.getFunction();
1637   if ((!IsMemset || ZeroMemset) &&
1638       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1639                                        Attribute::NoImplicitFloat)) {
1640     if (Size >= 16 &&
1641         (Subtarget->isUnalignedMemAccessFast() ||
1642          ((DstAlign == 0 || DstAlign >= 16) &&
1643           (SrcAlign == 0 || SrcAlign >= 16)))) {
1644       if (Size >= 32) {
1645         if (Subtarget->hasInt256())
1646           return MVT::v8i32;
1647         if (Subtarget->hasFp256())
1648           return MVT::v8f32;
1649       }
1650       if (Subtarget->hasSSE2())
1651         return MVT::v4i32;
1652       if (Subtarget->hasSSE1())
1653         return MVT::v4f32;
1654     } else if (!MemcpyStrSrc && Size >= 8 &&
1655                !Subtarget->is64Bit() &&
1656                Subtarget->hasSSE2()) {
1657       // Do not use f64 to lower memcpy if source is string constant. It's
1658       // better to use i32 to avoid the loads.
1659       return MVT::f64;
1660     }
1661   }
1662   if (Subtarget->is64Bit() && Size >= 8)
1663     return MVT::i64;
1664   return MVT::i32;
1665 }
1666
1667 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1668   if (VT == MVT::f32)
1669     return X86ScalarSSEf32;
1670   else if (VT == MVT::f64)
1671     return X86ScalarSSEf64;
1672   return true;
1673 }
1674
1675 bool
1676 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1677                                                  unsigned,
1678                                                  bool *Fast) const {
1679   if (Fast)
1680     *Fast = Subtarget->isUnalignedMemAccessFast();
1681   return true;
1682 }
1683
1684 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1685 /// current function.  The returned value is a member of the
1686 /// MachineJumpTableInfo::JTEntryKind enum.
1687 unsigned X86TargetLowering::getJumpTableEncoding() const {
1688   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1689   // symbol.
1690   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1691       Subtarget->isPICStyleGOT())
1692     return MachineJumpTableInfo::EK_Custom32;
1693
1694   // Otherwise, use the normal jump table encoding heuristics.
1695   return TargetLowering::getJumpTableEncoding();
1696 }
1697
1698 const MCExpr *
1699 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1700                                              const MachineBasicBlock *MBB,
1701                                              unsigned uid,MCContext &Ctx) const{
1702   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1703          Subtarget->isPICStyleGOT());
1704   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1705   // entries.
1706   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1707                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1708 }
1709
1710 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1711 /// jumptable.
1712 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1713                                                     SelectionDAG &DAG) const {
1714   if (!Subtarget->is64Bit())
1715     // This doesn't have SDLoc associated with it, but is not really the
1716     // same as a Register.
1717     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1718   return Table;
1719 }
1720
1721 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1722 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1723 /// MCExpr.
1724 const MCExpr *X86TargetLowering::
1725 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1726                              MCContext &Ctx) const {
1727   // X86-64 uses RIP relative addressing based on the jump table label.
1728   if (Subtarget->isPICStyleRIPRel())
1729     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1730
1731   // Otherwise, the reference is relative to the PIC base.
1732   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1733 }
1734
1735 // FIXME: Why this routine is here? Move to RegInfo!
1736 std::pair<const TargetRegisterClass*, uint8_t>
1737 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1738   const TargetRegisterClass *RRC = 0;
1739   uint8_t Cost = 1;
1740   switch (VT.SimpleTy) {
1741   default:
1742     return TargetLowering::findRepresentativeClass(VT);
1743   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1744     RRC = Subtarget->is64Bit() ?
1745       (const TargetRegisterClass*)&X86::GR64RegClass :
1746       (const TargetRegisterClass*)&X86::GR32RegClass;
1747     break;
1748   case MVT::x86mmx:
1749     RRC = &X86::VR64RegClass;
1750     break;
1751   case MVT::f32: case MVT::f64:
1752   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1753   case MVT::v4f32: case MVT::v2f64:
1754   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1755   case MVT::v4f64:
1756     RRC = &X86::VR128RegClass;
1757     break;
1758   }
1759   return std::make_pair(RRC, Cost);
1760 }
1761
1762 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1763                                                unsigned &Offset) const {
1764   if (!Subtarget->isTargetLinux())
1765     return false;
1766
1767   if (Subtarget->is64Bit()) {
1768     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1769     Offset = 0x28;
1770     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1771       AddressSpace = 256;
1772     else
1773       AddressSpace = 257;
1774   } else {
1775     // %gs:0x14 on i386
1776     Offset = 0x14;
1777     AddressSpace = 256;
1778   }
1779   return true;
1780 }
1781
1782 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1783                                             unsigned DestAS) const {
1784   assert(SrcAS != DestAS && "Expected different address spaces!");
1785
1786   return SrcAS < 256 && DestAS < 256;
1787 }
1788
1789 //===----------------------------------------------------------------------===//
1790 //               Return Value Calling Convention Implementation
1791 //===----------------------------------------------------------------------===//
1792
1793 #include "X86GenCallingConv.inc"
1794
1795 bool
1796 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1797                                   MachineFunction &MF, bool isVarArg,
1798                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1799                         LLVMContext &Context) const {
1800   SmallVector<CCValAssign, 16> RVLocs;
1801   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1802                  RVLocs, Context);
1803   return CCInfo.CheckReturn(Outs, RetCC_X86);
1804 }
1805
1806 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1807   static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1808   return ScratchRegs;
1809 }
1810
1811 SDValue
1812 X86TargetLowering::LowerReturn(SDValue Chain,
1813                                CallingConv::ID CallConv, bool isVarArg,
1814                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1815                                const SmallVectorImpl<SDValue> &OutVals,
1816                                SDLoc dl, SelectionDAG &DAG) const {
1817   MachineFunction &MF = DAG.getMachineFunction();
1818   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1819
1820   SmallVector<CCValAssign, 16> RVLocs;
1821   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1822                  RVLocs, *DAG.getContext());
1823   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1824
1825   SDValue Flag;
1826   SmallVector<SDValue, 6> RetOps;
1827   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1828   // Operand #1 = Bytes To Pop
1829   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1830                    MVT::i16));
1831
1832   // Copy the result values into the output registers.
1833   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1834     CCValAssign &VA = RVLocs[i];
1835     assert(VA.isRegLoc() && "Can only return in registers!");
1836     SDValue ValToCopy = OutVals[i];
1837     EVT ValVT = ValToCopy.getValueType();
1838
1839     // Promote values to the appropriate types
1840     if (VA.getLocInfo() == CCValAssign::SExt)
1841       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1842     else if (VA.getLocInfo() == CCValAssign::ZExt)
1843       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1844     else if (VA.getLocInfo() == CCValAssign::AExt)
1845       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1846     else if (VA.getLocInfo() == CCValAssign::BCvt)
1847       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1848
1849     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1850            "Unexpected FP-extend for return value.");  
1851
1852     // If this is x86-64, and we disabled SSE, we can't return FP values,
1853     // or SSE or MMX vectors.
1854     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1855          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1856           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1857       report_fatal_error("SSE register return with SSE disabled");
1858     }
1859     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1860     // llvm-gcc has never done it right and no one has noticed, so this
1861     // should be OK for now.
1862     if (ValVT == MVT::f64 &&
1863         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1864       report_fatal_error("SSE2 register return with SSE2 disabled");
1865
1866     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1867     // the RET instruction and handled by the FP Stackifier.
1868     if (VA.getLocReg() == X86::ST0 ||
1869         VA.getLocReg() == X86::ST1) {
1870       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1871       // change the value to the FP stack register class.
1872       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1873         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1874       RetOps.push_back(ValToCopy);
1875       // Don't emit a copytoreg.
1876       continue;
1877     }
1878
1879     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1880     // which is returned in RAX / RDX.
1881     if (Subtarget->is64Bit()) {
1882       if (ValVT == MVT::x86mmx) {
1883         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1884           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1885           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1886                                   ValToCopy);
1887           // If we don't have SSE2 available, convert to v4f32 so the generated
1888           // register is legal.
1889           if (!Subtarget->hasSSE2())
1890             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1891         }
1892       }
1893     }
1894
1895     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1896     Flag = Chain.getValue(1);
1897     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1898   }
1899
1900   // The x86-64 ABIs require that for returning structs by value we copy
1901   // the sret argument into %rax/%eax (depending on ABI) for the return.
1902   // Win32 requires us to put the sret argument to %eax as well.
1903   // We saved the argument into a virtual register in the entry block,
1904   // so now we copy the value out and into %rax/%eax.
1905   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1906       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1907     MachineFunction &MF = DAG.getMachineFunction();
1908     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1909     unsigned Reg = FuncInfo->getSRetReturnReg();
1910     assert(Reg &&
1911            "SRetReturnReg should have been set in LowerFormalArguments().");
1912     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1913
1914     unsigned RetValReg
1915         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1916           X86::RAX : X86::EAX;
1917     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1918     Flag = Chain.getValue(1);
1919
1920     // RAX/EAX now acts like a return value.
1921     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1922   }
1923
1924   RetOps[0] = Chain;  // Update chain.
1925
1926   // Add the flag if we have it.
1927   if (Flag.getNode())
1928     RetOps.push_back(Flag);
1929
1930   return DAG.getNode(X86ISD::RET_FLAG, dl,
1931                      MVT::Other, &RetOps[0], RetOps.size());
1932 }
1933
1934 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1935   if (N->getNumValues() != 1)
1936     return false;
1937   if (!N->hasNUsesOfValue(1, 0))
1938     return false;
1939
1940   SDValue TCChain = Chain;
1941   SDNode *Copy = *N->use_begin();
1942   if (Copy->getOpcode() == ISD::CopyToReg) {
1943     // If the copy has a glue operand, we conservatively assume it isn't safe to
1944     // perform a tail call.
1945     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1946       return false;
1947     TCChain = Copy->getOperand(0);
1948   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1949     return false;
1950
1951   bool HasRet = false;
1952   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1953        UI != UE; ++UI) {
1954     if (UI->getOpcode() != X86ISD::RET_FLAG)
1955       return false;
1956     HasRet = true;
1957   }
1958
1959   if (!HasRet)
1960     return false;
1961
1962   Chain = TCChain;
1963   return true;
1964 }
1965
1966 MVT
1967 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1968                                             ISD::NodeType ExtendKind) const {
1969   MVT ReturnMVT;
1970   // TODO: Is this also valid on 32-bit?
1971   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1972     ReturnMVT = MVT::i8;
1973   else
1974     ReturnMVT = MVT::i32;
1975
1976   MVT MinVT = getRegisterType(ReturnMVT);
1977   return VT.bitsLT(MinVT) ? MinVT : VT;
1978 }
1979
1980 /// LowerCallResult - Lower the result values of a call into the
1981 /// appropriate copies out of appropriate physical registers.
1982 ///
1983 SDValue
1984 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1985                                    CallingConv::ID CallConv, bool isVarArg,
1986                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1987                                    SDLoc dl, SelectionDAG &DAG,
1988                                    SmallVectorImpl<SDValue> &InVals) const {
1989
1990   // Assign locations to each value returned by this call.
1991   SmallVector<CCValAssign, 16> RVLocs;
1992   bool Is64Bit = Subtarget->is64Bit();
1993   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1994                  getTargetMachine(), RVLocs, *DAG.getContext());
1995   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1996
1997   // Copy all of the result registers out of their specified physreg.
1998   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1999     CCValAssign &VA = RVLocs[i];
2000     EVT CopyVT = VA.getValVT();
2001
2002     // If this is x86-64, and we disabled SSE, we can't return FP values
2003     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2004         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2005       report_fatal_error("SSE register return with SSE disabled");
2006     }
2007
2008     SDValue Val;
2009
2010     // If this is a call to a function that returns an fp value on the floating
2011     // point stack, we must guarantee the value is popped from the stack, so
2012     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2013     // if the return value is not used. We use the FpPOP_RETVAL instruction
2014     // instead.
2015     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2016       // If we prefer to use the value in xmm registers, copy it out as f80 and
2017       // use a truncate to move it from fp stack reg to xmm reg.
2018       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2019       SDValue Ops[] = { Chain, InFlag };
2020       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2021                                          MVT::Other, MVT::Glue, Ops), 1);
2022       Val = Chain.getValue(0);
2023
2024       // Round the f80 to the right size, which also moves it to the appropriate
2025       // xmm register.
2026       if (CopyVT != VA.getValVT())
2027         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2028                           // This truncation won't change the value.
2029                           DAG.getIntPtrConstant(1));
2030     } else {
2031       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2032                                  CopyVT, InFlag).getValue(1);
2033       Val = Chain.getValue(0);
2034     }
2035     InFlag = Chain.getValue(2);
2036     InVals.push_back(Val);
2037   }
2038
2039   return Chain;
2040 }
2041
2042 //===----------------------------------------------------------------------===//
2043 //                C & StdCall & Fast Calling Convention implementation
2044 //===----------------------------------------------------------------------===//
2045 //  StdCall calling convention seems to be standard for many Windows' API
2046 //  routines and around. It differs from C calling convention just a little:
2047 //  callee should clean up the stack, not caller. Symbols should be also
2048 //  decorated in some fancy way :) It doesn't support any vector arguments.
2049 //  For info on fast calling convention see Fast Calling Convention (tail call)
2050 //  implementation LowerX86_32FastCCCallTo.
2051
2052 /// CallIsStructReturn - Determines whether a call uses struct return
2053 /// semantics.
2054 enum StructReturnType {
2055   NotStructReturn,
2056   RegStructReturn,
2057   StackStructReturn
2058 };
2059 static StructReturnType
2060 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2061   if (Outs.empty())
2062     return NotStructReturn;
2063
2064   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2065   if (!Flags.isSRet())
2066     return NotStructReturn;
2067   if (Flags.isInReg())
2068     return RegStructReturn;
2069   return StackStructReturn;
2070 }
2071
2072 /// ArgsAreStructReturn - Determines whether a function uses struct
2073 /// return semantics.
2074 static StructReturnType
2075 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2076   if (Ins.empty())
2077     return NotStructReturn;
2078
2079   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2080   if (!Flags.isSRet())
2081     return NotStructReturn;
2082   if (Flags.isInReg())
2083     return RegStructReturn;
2084   return StackStructReturn;
2085 }
2086
2087 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2088 /// by "Src" to address "Dst" with size and alignment information specified by
2089 /// the specific parameter attribute. The copy will be passed as a byval
2090 /// function parameter.
2091 static SDValue
2092 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2093                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2094                           SDLoc dl) {
2095   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2096
2097   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2098                        /*isVolatile*/false, /*AlwaysInline=*/true,
2099                        MachinePointerInfo(), MachinePointerInfo());
2100 }
2101
2102 /// IsTailCallConvention - Return true if the calling convention is one that
2103 /// supports tail call optimization.
2104 static bool IsTailCallConvention(CallingConv::ID CC) {
2105   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2106           CC == CallingConv::HiPE);
2107 }
2108
2109 /// \brief Return true if the calling convention is a C calling convention.
2110 static bool IsCCallConvention(CallingConv::ID CC) {
2111   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2112           CC == CallingConv::X86_64_SysV);
2113 }
2114
2115 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2116   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2117     return false;
2118
2119   CallSite CS(CI);
2120   CallingConv::ID CalleeCC = CS.getCallingConv();
2121   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2122     return false;
2123
2124   return true;
2125 }
2126
2127 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2128 /// a tailcall target by changing its ABI.
2129 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2130                                    bool GuaranteedTailCallOpt) {
2131   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2132 }
2133
2134 SDValue
2135 X86TargetLowering::LowerMemArgument(SDValue Chain,
2136                                     CallingConv::ID CallConv,
2137                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2138                                     SDLoc dl, SelectionDAG &DAG,
2139                                     const CCValAssign &VA,
2140                                     MachineFrameInfo *MFI,
2141                                     unsigned i) const {
2142   // Create the nodes corresponding to a load from this parameter slot.
2143   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2144   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2145                               getTargetMachine().Options.GuaranteedTailCallOpt);
2146   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2147   EVT ValVT;
2148
2149   // If value is passed by pointer we have address passed instead of the value
2150   // itself.
2151   if (VA.getLocInfo() == CCValAssign::Indirect)
2152     ValVT = VA.getLocVT();
2153   else
2154     ValVT = VA.getValVT();
2155
2156   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2157   // changed with more analysis.
2158   // In case of tail call optimization mark all arguments mutable. Since they
2159   // could be overwritten by lowering of arguments in case of a tail call.
2160   if (Flags.isByVal()) {
2161     unsigned Bytes = Flags.getByValSize();
2162     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2163     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2164     return DAG.getFrameIndex(FI, getPointerTy());
2165   } else {
2166     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2167                                     VA.getLocMemOffset(), isImmutable);
2168     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2169     return DAG.getLoad(ValVT, dl, Chain, FIN,
2170                        MachinePointerInfo::getFixedStack(FI),
2171                        false, false, false, 0);
2172   }
2173 }
2174
2175 SDValue
2176 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2177                                         CallingConv::ID CallConv,
2178                                         bool isVarArg,
2179                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2180                                         SDLoc dl,
2181                                         SelectionDAG &DAG,
2182                                         SmallVectorImpl<SDValue> &InVals)
2183                                           const {
2184   MachineFunction &MF = DAG.getMachineFunction();
2185   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2186
2187   const Function* Fn = MF.getFunction();
2188   if (Fn->hasExternalLinkage() &&
2189       Subtarget->isTargetCygMing() &&
2190       Fn->getName() == "main")
2191     FuncInfo->setForceFramePointer(true);
2192
2193   MachineFrameInfo *MFI = MF.getFrameInfo();
2194   bool Is64Bit = Subtarget->is64Bit();
2195   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2196
2197   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2198          "Var args not supported with calling convention fastcc, ghc or hipe");
2199
2200   // Assign locations to all of the incoming arguments.
2201   SmallVector<CCValAssign, 16> ArgLocs;
2202   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2203                  ArgLocs, *DAG.getContext());
2204
2205   // Allocate shadow area for Win64
2206   if (IsWin64)
2207     CCInfo.AllocateStack(32, 8);
2208
2209   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2210
2211   unsigned LastVal = ~0U;
2212   SDValue ArgValue;
2213   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2214     CCValAssign &VA = ArgLocs[i];
2215     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2216     // places.
2217     assert(VA.getValNo() != LastVal &&
2218            "Don't support value assigned to multiple locs yet");
2219     (void)LastVal;
2220     LastVal = VA.getValNo();
2221
2222     if (VA.isRegLoc()) {
2223       EVT RegVT = VA.getLocVT();
2224       const TargetRegisterClass *RC;
2225       if (RegVT == MVT::i32)
2226         RC = &X86::GR32RegClass;
2227       else if (Is64Bit && RegVT == MVT::i64)
2228         RC = &X86::GR64RegClass;
2229       else if (RegVT == MVT::f32)
2230         RC = &X86::FR32RegClass;
2231       else if (RegVT == MVT::f64)
2232         RC = &X86::FR64RegClass;
2233       else if (RegVT.is512BitVector())
2234         RC = &X86::VR512RegClass;
2235       else if (RegVT.is256BitVector())
2236         RC = &X86::VR256RegClass;
2237       else if (RegVT.is128BitVector())
2238         RC = &X86::VR128RegClass;
2239       else if (RegVT == MVT::x86mmx)
2240         RC = &X86::VR64RegClass;
2241       else if (RegVT == MVT::i1)
2242         RC = &X86::VK1RegClass;
2243       else if (RegVT == MVT::v8i1)
2244         RC = &X86::VK8RegClass;
2245       else if (RegVT == MVT::v16i1)
2246         RC = &X86::VK16RegClass;
2247       else
2248         llvm_unreachable("Unknown argument type!");
2249
2250       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2251       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2252
2253       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2254       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2255       // right size.
2256       if (VA.getLocInfo() == CCValAssign::SExt)
2257         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2258                                DAG.getValueType(VA.getValVT()));
2259       else if (VA.getLocInfo() == CCValAssign::ZExt)
2260         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2261                                DAG.getValueType(VA.getValVT()));
2262       else if (VA.getLocInfo() == CCValAssign::BCvt)
2263         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2264
2265       if (VA.isExtInLoc()) {
2266         // Handle MMX values passed in XMM regs.
2267         if (RegVT.isVector())
2268           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2269         else
2270           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2271       }
2272     } else {
2273       assert(VA.isMemLoc());
2274       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2275     }
2276
2277     // If value is passed via pointer - do a load.
2278     if (VA.getLocInfo() == CCValAssign::Indirect)
2279       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2280                              MachinePointerInfo(), false, false, false, 0);
2281
2282     InVals.push_back(ArgValue);
2283   }
2284
2285   // The x86-64 ABIs require that for returning structs by value we copy
2286   // the sret argument into %rax/%eax (depending on ABI) for the return.
2287   // Win32 requires us to put the sret argument to %eax as well.
2288   // Save the argument into a virtual register so that we can access it
2289   // from the return points.
2290   if (MF.getFunction()->hasStructRetAttr() &&
2291       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2292     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2293     unsigned Reg = FuncInfo->getSRetReturnReg();
2294     if (!Reg) {
2295       MVT PtrTy = getPointerTy();
2296       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2297       FuncInfo->setSRetReturnReg(Reg);
2298     }
2299     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2300     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2301   }
2302
2303   unsigned StackSize = CCInfo.getNextStackOffset();
2304   // Align stack specially for tail calls.
2305   if (FuncIsMadeTailCallSafe(CallConv,
2306                              MF.getTarget().Options.GuaranteedTailCallOpt))
2307     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2308
2309   // If the function takes variable number of arguments, make a frame index for
2310   // the start of the first vararg value... for expansion of llvm.va_start.
2311   if (isVarArg) {
2312     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2313                     CallConv != CallingConv::X86_ThisCall)) {
2314       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2315     }
2316     if (Is64Bit) {
2317       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2318
2319       // FIXME: We should really autogenerate these arrays
2320       static const uint16_t GPR64ArgRegsWin64[] = {
2321         X86::RCX, X86::RDX, X86::R8,  X86::R9
2322       };
2323       static const uint16_t GPR64ArgRegs64Bit[] = {
2324         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2325       };
2326       static const uint16_t XMMArgRegs64Bit[] = {
2327         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2328         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2329       };
2330       const uint16_t *GPR64ArgRegs;
2331       unsigned NumXMMRegs = 0;
2332
2333       if (IsWin64) {
2334         // The XMM registers which might contain var arg parameters are shadowed
2335         // in their paired GPR.  So we only need to save the GPR to their home
2336         // slots.
2337         TotalNumIntRegs = 4;
2338         GPR64ArgRegs = GPR64ArgRegsWin64;
2339       } else {
2340         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2341         GPR64ArgRegs = GPR64ArgRegs64Bit;
2342
2343         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2344                                                 TotalNumXMMRegs);
2345       }
2346       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2347                                                        TotalNumIntRegs);
2348
2349       bool NoImplicitFloatOps = Fn->getAttributes().
2350         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2351       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2352              "SSE register cannot be used when SSE is disabled!");
2353       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2354                NoImplicitFloatOps) &&
2355              "SSE register cannot be used when SSE is disabled!");
2356       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2357           !Subtarget->hasSSE1())
2358         // Kernel mode asks for SSE to be disabled, so don't push them
2359         // on the stack.
2360         TotalNumXMMRegs = 0;
2361
2362       if (IsWin64) {
2363         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2364         // Get to the caller-allocated home save location.  Add 8 to account
2365         // for the return address.
2366         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2367         FuncInfo->setRegSaveFrameIndex(
2368           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2369         // Fixup to set vararg frame on shadow area (4 x i64).
2370         if (NumIntRegs < 4)
2371           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2372       } else {
2373         // For X86-64, if there are vararg parameters that are passed via
2374         // registers, then we must store them to their spots on the stack so
2375         // they may be loaded by deferencing the result of va_next.
2376         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2377         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2378         FuncInfo->setRegSaveFrameIndex(
2379           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2380                                false));
2381       }
2382
2383       // Store the integer parameter registers.
2384       SmallVector<SDValue, 8> MemOps;
2385       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2386                                         getPointerTy());
2387       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2388       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2389         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2390                                   DAG.getIntPtrConstant(Offset));
2391         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2392                                      &X86::GR64RegClass);
2393         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2394         SDValue Store =
2395           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2396                        MachinePointerInfo::getFixedStack(
2397                          FuncInfo->getRegSaveFrameIndex(), Offset),
2398                        false, false, 0);
2399         MemOps.push_back(Store);
2400         Offset += 8;
2401       }
2402
2403       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2404         // Now store the XMM (fp + vector) parameter registers.
2405         SmallVector<SDValue, 11> SaveXMMOps;
2406         SaveXMMOps.push_back(Chain);
2407
2408         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2409         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2410         SaveXMMOps.push_back(ALVal);
2411
2412         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2413                                FuncInfo->getRegSaveFrameIndex()));
2414         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2415                                FuncInfo->getVarArgsFPOffset()));
2416
2417         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2418           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2419                                        &X86::VR128RegClass);
2420           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2421           SaveXMMOps.push_back(Val);
2422         }
2423         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2424                                      MVT::Other,
2425                                      &SaveXMMOps[0], SaveXMMOps.size()));
2426       }
2427
2428       if (!MemOps.empty())
2429         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2430                             &MemOps[0], MemOps.size());
2431     }
2432   }
2433
2434   // Some CCs need callee pop.
2435   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2436                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2437     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2438   } else {
2439     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2440     // If this is an sret function, the return should pop the hidden pointer.
2441     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2442         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2443         argsAreStructReturn(Ins) == StackStructReturn)
2444       FuncInfo->setBytesToPopOnReturn(4);
2445   }
2446
2447   if (!Is64Bit) {
2448     // RegSaveFrameIndex is X86-64 only.
2449     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2450     if (CallConv == CallingConv::X86_FastCall ||
2451         CallConv == CallingConv::X86_ThisCall)
2452       // fastcc functions can't have varargs.
2453       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2454   }
2455
2456   FuncInfo->setArgumentStackSize(StackSize);
2457
2458   return Chain;
2459 }
2460
2461 SDValue
2462 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2463                                     SDValue StackPtr, SDValue Arg,
2464                                     SDLoc dl, SelectionDAG &DAG,
2465                                     const CCValAssign &VA,
2466                                     ISD::ArgFlagsTy Flags) const {
2467   unsigned LocMemOffset = VA.getLocMemOffset();
2468   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2469   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2470   if (Flags.isByVal())
2471     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2472
2473   return DAG.getStore(Chain, dl, Arg, PtrOff,
2474                       MachinePointerInfo::getStack(LocMemOffset),
2475                       false, false, 0);
2476 }
2477
2478 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2479 /// optimization is performed and it is required.
2480 SDValue
2481 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2482                                            SDValue &OutRetAddr, SDValue Chain,
2483                                            bool IsTailCall, bool Is64Bit,
2484                                            int FPDiff, SDLoc dl) const {
2485   // Adjust the Return address stack slot.
2486   EVT VT = getPointerTy();
2487   OutRetAddr = getReturnAddressFrameIndex(DAG);
2488
2489   // Load the "old" Return address.
2490   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2491                            false, false, false, 0);
2492   return SDValue(OutRetAddr.getNode(), 1);
2493 }
2494
2495 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2496 /// optimization is performed and it is required (FPDiff!=0).
2497 static SDValue
2498 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2499                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2500                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2501   // Store the return address to the appropriate stack slot.
2502   if (!FPDiff) return Chain;
2503   // Calculate the new stack slot for the return address.
2504   int NewReturnAddrFI =
2505     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2506                                          false);
2507   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2508   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2509                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2510                        false, false, 0);
2511   return Chain;
2512 }
2513
2514 SDValue
2515 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2516                              SmallVectorImpl<SDValue> &InVals) const {
2517   SelectionDAG &DAG                     = CLI.DAG;
2518   SDLoc &dl                             = CLI.DL;
2519   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2520   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2521   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2522   SDValue Chain                         = CLI.Chain;
2523   SDValue Callee                        = CLI.Callee;
2524   CallingConv::ID CallConv              = CLI.CallConv;
2525   bool &isTailCall                      = CLI.IsTailCall;
2526   bool isVarArg                         = CLI.IsVarArg;
2527
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   bool Is64Bit        = Subtarget->is64Bit();
2530   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2531   StructReturnType SR = callIsStructReturn(Outs);
2532   bool IsSibcall      = false;
2533
2534   if (MF.getTarget().Options.DisableTailCalls)
2535     isTailCall = false;
2536
2537   if (isTailCall) {
2538     // Check if it's really possible to do a tail call.
2539     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2540                     isVarArg, SR != NotStructReturn,
2541                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2542                     Outs, OutVals, Ins, DAG);
2543
2544     // Sibcalls are automatically detected tailcalls which do not require
2545     // ABI changes.
2546     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2547       IsSibcall = true;
2548
2549     if (isTailCall)
2550       ++NumTailCalls;
2551   }
2552
2553   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2554          "Var args not supported with calling convention fastcc, ghc or hipe");
2555
2556   // Analyze operands of the call, assigning locations to each operand.
2557   SmallVector<CCValAssign, 16> ArgLocs;
2558   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2559                  ArgLocs, *DAG.getContext());
2560
2561   // Allocate shadow area for Win64
2562   if (IsWin64)
2563     CCInfo.AllocateStack(32, 8);
2564
2565   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2566
2567   // Get a count of how many bytes are to be pushed on the stack.
2568   unsigned NumBytes = CCInfo.getNextStackOffset();
2569   if (IsSibcall)
2570     // This is a sibcall. The memory operands are available in caller's
2571     // own caller's stack.
2572     NumBytes = 0;
2573   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2574            IsTailCallConvention(CallConv))
2575     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2576
2577   int FPDiff = 0;
2578   if (isTailCall && !IsSibcall) {
2579     // Lower arguments at fp - stackoffset + fpdiff.
2580     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2581     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2582
2583     FPDiff = NumBytesCallerPushed - NumBytes;
2584
2585     // Set the delta of movement of the returnaddr stackslot.
2586     // But only set if delta is greater than previous delta.
2587     if (FPDiff < X86Info->getTCReturnAddrDelta())
2588       X86Info->setTCReturnAddrDelta(FPDiff);
2589   }
2590
2591   unsigned NumBytesToPush = NumBytes;
2592   unsigned NumBytesToPop = NumBytes;
2593
2594   // If we have an inalloca argument, all stack space has already been allocated
2595   // for us and be right at the top of the stack.  We don't support multiple
2596   // arguments passed in memory when using inalloca.
2597   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2598     NumBytesToPush = 0;
2599     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2600            "an inalloca argument must be the only memory argument");
2601   }
2602
2603   if (!IsSibcall)
2604     Chain = DAG.getCALLSEQ_START(
2605         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2606
2607   SDValue RetAddrFrIdx;
2608   // Load return address for tail calls.
2609   if (isTailCall && FPDiff)
2610     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2611                                     Is64Bit, FPDiff, dl);
2612
2613   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2614   SmallVector<SDValue, 8> MemOpChains;
2615   SDValue StackPtr;
2616
2617   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2618   // of tail call optimization arguments are handle later.
2619   const X86RegisterInfo *RegInfo =
2620     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2621   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2622     // Skip inalloca arguments, they have already been written.
2623     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2624     if (Flags.isInAlloca())
2625       continue;
2626
2627     CCValAssign &VA = ArgLocs[i];
2628     EVT RegVT = VA.getLocVT();
2629     SDValue Arg = OutVals[i];
2630     bool isByVal = Flags.isByVal();
2631
2632     // Promote the value if needed.
2633     switch (VA.getLocInfo()) {
2634     default: llvm_unreachable("Unknown loc info!");
2635     case CCValAssign::Full: break;
2636     case CCValAssign::SExt:
2637       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2638       break;
2639     case CCValAssign::ZExt:
2640       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2641       break;
2642     case CCValAssign::AExt:
2643       if (RegVT.is128BitVector()) {
2644         // Special case: passing MMX values in XMM registers.
2645         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2646         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2647         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2648       } else
2649         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2650       break;
2651     case CCValAssign::BCvt:
2652       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2653       break;
2654     case CCValAssign::Indirect: {
2655       // Store the argument.
2656       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2657       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2658       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2659                            MachinePointerInfo::getFixedStack(FI),
2660                            false, false, 0);
2661       Arg = SpillSlot;
2662       break;
2663     }
2664     }
2665
2666     if (VA.isRegLoc()) {
2667       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2668       if (isVarArg && IsWin64) {
2669         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2670         // shadow reg if callee is a varargs function.
2671         unsigned ShadowReg = 0;
2672         switch (VA.getLocReg()) {
2673         case X86::XMM0: ShadowReg = X86::RCX; break;
2674         case X86::XMM1: ShadowReg = X86::RDX; break;
2675         case X86::XMM2: ShadowReg = X86::R8; break;
2676         case X86::XMM3: ShadowReg = X86::R9; break;
2677         }
2678         if (ShadowReg)
2679           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2680       }
2681     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2682       assert(VA.isMemLoc());
2683       if (StackPtr.getNode() == 0)
2684         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2685                                       getPointerTy());
2686       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2687                                              dl, DAG, VA, Flags));
2688     }
2689   }
2690
2691   if (!MemOpChains.empty())
2692     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2693                         &MemOpChains[0], MemOpChains.size());
2694
2695   if (Subtarget->isPICStyleGOT()) {
2696     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2697     // GOT pointer.
2698     if (!isTailCall) {
2699       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2700                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2701     } else {
2702       // If we are tail calling and generating PIC/GOT style code load the
2703       // address of the callee into ECX. The value in ecx is used as target of
2704       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2705       // for tail calls on PIC/GOT architectures. Normally we would just put the
2706       // address of GOT into ebx and then call target@PLT. But for tail calls
2707       // ebx would be restored (since ebx is callee saved) before jumping to the
2708       // target@PLT.
2709
2710       // Note: The actual moving to ECX is done further down.
2711       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2712       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2713           !G->getGlobal()->hasProtectedVisibility())
2714         Callee = LowerGlobalAddress(Callee, DAG);
2715       else if (isa<ExternalSymbolSDNode>(Callee))
2716         Callee = LowerExternalSymbol(Callee, DAG);
2717     }
2718   }
2719
2720   if (Is64Bit && isVarArg && !IsWin64) {
2721     // From AMD64 ABI document:
2722     // For calls that may call functions that use varargs or stdargs
2723     // (prototype-less calls or calls to functions containing ellipsis (...) in
2724     // the declaration) %al is used as hidden argument to specify the number
2725     // of SSE registers used. The contents of %al do not need to match exactly
2726     // the number of registers, but must be an ubound on the number of SSE
2727     // registers used and is in the range 0 - 8 inclusive.
2728
2729     // Count the number of XMM registers allocated.
2730     static const uint16_t XMMArgRegs[] = {
2731       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2732       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2733     };
2734     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2735     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2736            && "SSE registers cannot be used when SSE is disabled");
2737
2738     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2739                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2740   }
2741
2742   // For tail calls lower the arguments to the 'real' stack slot.
2743   if (isTailCall) {
2744     // Force all the incoming stack arguments to be loaded from the stack
2745     // before any new outgoing arguments are stored to the stack, because the
2746     // outgoing stack slots may alias the incoming argument stack slots, and
2747     // the alias isn't otherwise explicit. This is slightly more conservative
2748     // than necessary, because it means that each store effectively depends
2749     // on every argument instead of just those arguments it would clobber.
2750     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2751
2752     SmallVector<SDValue, 8> MemOpChains2;
2753     SDValue FIN;
2754     int FI = 0;
2755     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2756       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2757         CCValAssign &VA = ArgLocs[i];
2758         if (VA.isRegLoc())
2759           continue;
2760         assert(VA.isMemLoc());
2761         SDValue Arg = OutVals[i];
2762         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2763         // Create frame index.
2764         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2765         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2766         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2767         FIN = DAG.getFrameIndex(FI, getPointerTy());
2768
2769         if (Flags.isByVal()) {
2770           // Copy relative to framepointer.
2771           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2772           if (StackPtr.getNode() == 0)
2773             StackPtr = DAG.getCopyFromReg(Chain, dl,
2774                                           RegInfo->getStackRegister(),
2775                                           getPointerTy());
2776           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2777
2778           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2779                                                            ArgChain,
2780                                                            Flags, DAG, dl));
2781         } else {
2782           // Store relative to framepointer.
2783           MemOpChains2.push_back(
2784             DAG.getStore(ArgChain, dl, Arg, FIN,
2785                          MachinePointerInfo::getFixedStack(FI),
2786                          false, false, 0));
2787         }
2788       }
2789     }
2790
2791     if (!MemOpChains2.empty())
2792       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2793                           &MemOpChains2[0], MemOpChains2.size());
2794
2795     // Store the return address to the appropriate stack slot.
2796     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2797                                      getPointerTy(), RegInfo->getSlotSize(),
2798                                      FPDiff, dl);
2799   }
2800
2801   // Build a sequence of copy-to-reg nodes chained together with token chain
2802   // and flag operands which copy the outgoing args into registers.
2803   SDValue InFlag;
2804   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2805     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2806                              RegsToPass[i].second, InFlag);
2807     InFlag = Chain.getValue(1);
2808   }
2809
2810   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2811     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2812     // In the 64-bit large code model, we have to make all calls
2813     // through a register, since the call instruction's 32-bit
2814     // pc-relative offset may not be large enough to hold the whole
2815     // address.
2816   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2817     // If the callee is a GlobalAddress node (quite common, every direct call
2818     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2819     // it.
2820
2821     // We should use extra load for direct calls to dllimported functions in
2822     // non-JIT mode.
2823     const GlobalValue *GV = G->getGlobal();
2824     if (!GV->hasDLLImportStorageClass()) {
2825       unsigned char OpFlags = 0;
2826       bool ExtraLoad = false;
2827       unsigned WrapperKind = ISD::DELETED_NODE;
2828
2829       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2830       // external symbols most go through the PLT in PIC mode.  If the symbol
2831       // has hidden or protected visibility, or if it is static or local, then
2832       // we don't need to use the PLT - we can directly call it.
2833       if (Subtarget->isTargetELF() &&
2834           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2835           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2836         OpFlags = X86II::MO_PLT;
2837       } else if (Subtarget->isPICStyleStubAny() &&
2838                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2839                  (!Subtarget->getTargetTriple().isMacOSX() ||
2840                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2841         // PC-relative references to external symbols should go through $stub,
2842         // unless we're building with the leopard linker or later, which
2843         // automatically synthesizes these stubs.
2844         OpFlags = X86II::MO_DARWIN_STUB;
2845       } else if (Subtarget->isPICStyleRIPRel() &&
2846                  isa<Function>(GV) &&
2847                  cast<Function>(GV)->getAttributes().
2848                    hasAttribute(AttributeSet::FunctionIndex,
2849                                 Attribute::NonLazyBind)) {
2850         // If the function is marked as non-lazy, generate an indirect call
2851         // which loads from the GOT directly. This avoids runtime overhead
2852         // at the cost of eager binding (and one extra byte of encoding).
2853         OpFlags = X86II::MO_GOTPCREL;
2854         WrapperKind = X86ISD::WrapperRIP;
2855         ExtraLoad = true;
2856       }
2857
2858       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2859                                           G->getOffset(), OpFlags);
2860
2861       // Add a wrapper if needed.
2862       if (WrapperKind != ISD::DELETED_NODE)
2863         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2864       // Add extra indirection if needed.
2865       if (ExtraLoad)
2866         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2867                              MachinePointerInfo::getGOT(),
2868                              false, false, false, 0);
2869     }
2870   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2871     unsigned char OpFlags = 0;
2872
2873     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2874     // external symbols should go through the PLT.
2875     if (Subtarget->isTargetELF() &&
2876         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2877       OpFlags = X86II::MO_PLT;
2878     } else if (Subtarget->isPICStyleStubAny() &&
2879                (!Subtarget->getTargetTriple().isMacOSX() ||
2880                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2881       // PC-relative references to external symbols should go through $stub,
2882       // unless we're building with the leopard linker or later, which
2883       // automatically synthesizes these stubs.
2884       OpFlags = X86II::MO_DARWIN_STUB;
2885     }
2886
2887     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2888                                          OpFlags);
2889   }
2890
2891   // Returns a chain & a flag for retval copy to use.
2892   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2893   SmallVector<SDValue, 8> Ops;
2894
2895   if (!IsSibcall && isTailCall) {
2896     Chain = DAG.getCALLSEQ_END(Chain,
2897                                DAG.getIntPtrConstant(NumBytesToPop, true),
2898                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2899     InFlag = Chain.getValue(1);
2900   }
2901
2902   Ops.push_back(Chain);
2903   Ops.push_back(Callee);
2904
2905   if (isTailCall)
2906     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2907
2908   // Add argument registers to the end of the list so that they are known live
2909   // into the call.
2910   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2911     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2912                                   RegsToPass[i].second.getValueType()));
2913
2914   // Add a register mask operand representing the call-preserved registers.
2915   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2916   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2917   assert(Mask && "Missing call preserved mask for calling convention");
2918   Ops.push_back(DAG.getRegisterMask(Mask));
2919
2920   if (InFlag.getNode())
2921     Ops.push_back(InFlag);
2922
2923   if (isTailCall) {
2924     // We used to do:
2925     //// If this is the first return lowered for this function, add the regs
2926     //// to the liveout set for the function.
2927     // This isn't right, although it's probably harmless on x86; liveouts
2928     // should be computed from returns not tail calls.  Consider a void
2929     // function making a tail call to a function returning int.
2930     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2931   }
2932
2933   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2934   InFlag = Chain.getValue(1);
2935
2936   // Create the CALLSEQ_END node.
2937   unsigned NumBytesForCalleeToPop;
2938   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2939                        getTargetMachine().Options.GuaranteedTailCallOpt))
2940     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2941   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2942            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2943            SR == StackStructReturn)
2944     // If this is a call to a struct-return function, the callee
2945     // pops the hidden struct pointer, so we have to push it back.
2946     // This is common for Darwin/X86, Linux & Mingw32 targets.
2947     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2948     NumBytesForCalleeToPop = 4;
2949   else
2950     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2951
2952   // Returns a flag for retval copy to use.
2953   if (!IsSibcall) {
2954     Chain = DAG.getCALLSEQ_END(Chain,
2955                                DAG.getIntPtrConstant(NumBytesToPop, true),
2956                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2957                                                      true),
2958                                InFlag, dl);
2959     InFlag = Chain.getValue(1);
2960   }
2961
2962   // Handle result values, copying them out of physregs into vregs that we
2963   // return.
2964   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2965                          Ins, dl, DAG, InVals);
2966 }
2967
2968 //===----------------------------------------------------------------------===//
2969 //                Fast Calling Convention (tail call) implementation
2970 //===----------------------------------------------------------------------===//
2971
2972 //  Like std call, callee cleans arguments, convention except that ECX is
2973 //  reserved for storing the tail called function address. Only 2 registers are
2974 //  free for argument passing (inreg). Tail call optimization is performed
2975 //  provided:
2976 //                * tailcallopt is enabled
2977 //                * caller/callee are fastcc
2978 //  On X86_64 architecture with GOT-style position independent code only local
2979 //  (within module) calls are supported at the moment.
2980 //  To keep the stack aligned according to platform abi the function
2981 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2982 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2983 //  If a tail called function callee has more arguments than the caller the
2984 //  caller needs to make sure that there is room to move the RETADDR to. This is
2985 //  achieved by reserving an area the size of the argument delta right after the
2986 //  original REtADDR, but before the saved framepointer or the spilled registers
2987 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2988 //  stack layout:
2989 //    arg1
2990 //    arg2
2991 //    RETADDR
2992 //    [ new RETADDR
2993 //      move area ]
2994 //    (possible EBP)
2995 //    ESI
2996 //    EDI
2997 //    local1 ..
2998
2999 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3000 /// for a 16 byte align requirement.
3001 unsigned
3002 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3003                                                SelectionDAG& DAG) const {
3004   MachineFunction &MF = DAG.getMachineFunction();
3005   const TargetMachine &TM = MF.getTarget();
3006   const X86RegisterInfo *RegInfo =
3007     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3008   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3009   unsigned StackAlignment = TFI.getStackAlignment();
3010   uint64_t AlignMask = StackAlignment - 1;
3011   int64_t Offset = StackSize;
3012   unsigned SlotSize = RegInfo->getSlotSize();
3013   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3014     // Number smaller than 12 so just add the difference.
3015     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3016   } else {
3017     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3018     Offset = ((~AlignMask) & Offset) + StackAlignment +
3019       (StackAlignment-SlotSize);
3020   }
3021   return Offset;
3022 }
3023
3024 /// MatchingStackOffset - Return true if the given stack call argument is
3025 /// already available in the same position (relatively) of the caller's
3026 /// incoming argument stack.
3027 static
3028 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3029                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3030                          const X86InstrInfo *TII) {
3031   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3032   int FI = INT_MAX;
3033   if (Arg.getOpcode() == ISD::CopyFromReg) {
3034     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3035     if (!TargetRegisterInfo::isVirtualRegister(VR))
3036       return false;
3037     MachineInstr *Def = MRI->getVRegDef(VR);
3038     if (!Def)
3039       return false;
3040     if (!Flags.isByVal()) {
3041       if (!TII->isLoadFromStackSlot(Def, FI))
3042         return false;
3043     } else {
3044       unsigned Opcode = Def->getOpcode();
3045       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3046           Def->getOperand(1).isFI()) {
3047         FI = Def->getOperand(1).getIndex();
3048         Bytes = Flags.getByValSize();
3049       } else
3050         return false;
3051     }
3052   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3053     if (Flags.isByVal())
3054       // ByVal argument is passed in as a pointer but it's now being
3055       // dereferenced. e.g.
3056       // define @foo(%struct.X* %A) {
3057       //   tail call @bar(%struct.X* byval %A)
3058       // }
3059       return false;
3060     SDValue Ptr = Ld->getBasePtr();
3061     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3062     if (!FINode)
3063       return false;
3064     FI = FINode->getIndex();
3065   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3066     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3067     FI = FINode->getIndex();
3068     Bytes = Flags.getByValSize();
3069   } else
3070     return false;
3071
3072   assert(FI != INT_MAX);
3073   if (!MFI->isFixedObjectIndex(FI))
3074     return false;
3075   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3076 }
3077
3078 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3079 /// for tail call optimization. Targets which want to do tail call
3080 /// optimization should implement this function.
3081 bool
3082 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3083                                                      CallingConv::ID CalleeCC,
3084                                                      bool isVarArg,
3085                                                      bool isCalleeStructRet,
3086                                                      bool isCallerStructRet,
3087                                                      Type *RetTy,
3088                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3089                                     const SmallVectorImpl<SDValue> &OutVals,
3090                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3091                                                      SelectionDAG &DAG) const {
3092   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3093     return false;
3094
3095   // If -tailcallopt is specified, make fastcc functions tail-callable.
3096   const MachineFunction &MF = DAG.getMachineFunction();
3097   const Function *CallerF = MF.getFunction();
3098
3099   // If the function return type is x86_fp80 and the callee return type is not,
3100   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3101   // perform a tailcall optimization here.
3102   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3103     return false;
3104
3105   CallingConv::ID CallerCC = CallerF->getCallingConv();
3106   bool CCMatch = CallerCC == CalleeCC;
3107   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3108   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3109
3110   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3111     if (IsTailCallConvention(CalleeCC) && CCMatch)
3112       return true;
3113     return false;
3114   }
3115
3116   // Look for obvious safe cases to perform tail call optimization that do not
3117   // require ABI changes. This is what gcc calls sibcall.
3118
3119   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3120   // emit a special epilogue.
3121   const X86RegisterInfo *RegInfo =
3122     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3123   if (RegInfo->needsStackRealignment(MF))
3124     return false;
3125
3126   // Also avoid sibcall optimization if either caller or callee uses struct
3127   // return semantics.
3128   if (isCalleeStructRet || isCallerStructRet)
3129     return false;
3130
3131   // An stdcall/thiscall caller is expected to clean up its arguments; the
3132   // callee isn't going to do that.
3133   // FIXME: this is more restrictive than needed. We could produce a tailcall
3134   // when the stack adjustment matches. For example, with a thiscall that takes
3135   // only one argument.
3136   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3137                    CallerCC == CallingConv::X86_ThisCall))
3138     return false;
3139
3140   // Do not sibcall optimize vararg calls unless all arguments are passed via
3141   // registers.
3142   if (isVarArg && !Outs.empty()) {
3143
3144     // Optimizing for varargs on Win64 is unlikely to be safe without
3145     // additional testing.
3146     if (IsCalleeWin64 || IsCallerWin64)
3147       return false;
3148
3149     SmallVector<CCValAssign, 16> ArgLocs;
3150     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151                    getTargetMachine(), ArgLocs, *DAG.getContext());
3152
3153     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3154     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3155       if (!ArgLocs[i].isRegLoc())
3156         return false;
3157   }
3158
3159   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3160   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3161   // this into a sibcall.
3162   bool Unused = false;
3163   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3164     if (!Ins[i].Used) {
3165       Unused = true;
3166       break;
3167     }
3168   }
3169   if (Unused) {
3170     SmallVector<CCValAssign, 16> RVLocs;
3171     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3172                    getTargetMachine(), RVLocs, *DAG.getContext());
3173     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3174     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3175       CCValAssign &VA = RVLocs[i];
3176       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3177         return false;
3178     }
3179   }
3180
3181   // If the calling conventions do not match, then we'd better make sure the
3182   // results are returned in the same way as what the caller expects.
3183   if (!CCMatch) {
3184     SmallVector<CCValAssign, 16> RVLocs1;
3185     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3186                     getTargetMachine(), RVLocs1, *DAG.getContext());
3187     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3188
3189     SmallVector<CCValAssign, 16> RVLocs2;
3190     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3191                     getTargetMachine(), RVLocs2, *DAG.getContext());
3192     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3193
3194     if (RVLocs1.size() != RVLocs2.size())
3195       return false;
3196     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3197       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3198         return false;
3199       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3200         return false;
3201       if (RVLocs1[i].isRegLoc()) {
3202         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3203           return false;
3204       } else {
3205         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3206           return false;
3207       }
3208     }
3209   }
3210
3211   // If the callee takes no arguments then go on to check the results of the
3212   // call.
3213   if (!Outs.empty()) {
3214     // Check if stack adjustment is needed. For now, do not do this if any
3215     // argument is passed on the stack.
3216     SmallVector<CCValAssign, 16> ArgLocs;
3217     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3218                    getTargetMachine(), ArgLocs, *DAG.getContext());
3219
3220     // Allocate shadow area for Win64
3221     if (IsCalleeWin64)
3222       CCInfo.AllocateStack(32, 8);
3223
3224     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3225     if (CCInfo.getNextStackOffset()) {
3226       MachineFunction &MF = DAG.getMachineFunction();
3227       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3228         return false;
3229
3230       // Check if the arguments are already laid out in the right way as
3231       // the caller's fixed stack objects.
3232       MachineFrameInfo *MFI = MF.getFrameInfo();
3233       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3234       const X86InstrInfo *TII =
3235         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3236       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3237         CCValAssign &VA = ArgLocs[i];
3238         SDValue Arg = OutVals[i];
3239         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3240         if (VA.getLocInfo() == CCValAssign::Indirect)
3241           return false;
3242         if (!VA.isRegLoc()) {
3243           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3244                                    MFI, MRI, TII))
3245             return false;
3246         }
3247       }
3248     }
3249
3250     // If the tailcall address may be in a register, then make sure it's
3251     // possible to register allocate for it. In 32-bit, the call address can
3252     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3253     // callee-saved registers are restored. These happen to be the same
3254     // registers used to pass 'inreg' arguments so watch out for those.
3255     if (!Subtarget->is64Bit() &&
3256         ((!isa<GlobalAddressSDNode>(Callee) &&
3257           !isa<ExternalSymbolSDNode>(Callee)) ||
3258          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3259       unsigned NumInRegs = 0;
3260       // In PIC we need an extra register to formulate the address computation
3261       // for the callee.
3262       unsigned MaxInRegs =
3263           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3264
3265       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3266         CCValAssign &VA = ArgLocs[i];
3267         if (!VA.isRegLoc())
3268           continue;
3269         unsigned Reg = VA.getLocReg();
3270         switch (Reg) {
3271         default: break;
3272         case X86::EAX: case X86::EDX: case X86::ECX:
3273           if (++NumInRegs == MaxInRegs)
3274             return false;
3275           break;
3276         }
3277       }
3278     }
3279   }
3280
3281   return true;
3282 }
3283
3284 FastISel *
3285 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3286                                   const TargetLibraryInfo *libInfo) const {
3287   return X86::createFastISel(funcInfo, libInfo);
3288 }
3289
3290 //===----------------------------------------------------------------------===//
3291 //                           Other Lowering Hooks
3292 //===----------------------------------------------------------------------===//
3293
3294 static bool MayFoldLoad(SDValue Op) {
3295   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3296 }
3297
3298 static bool MayFoldIntoStore(SDValue Op) {
3299   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3300 }
3301
3302 static bool isTargetShuffle(unsigned Opcode) {
3303   switch(Opcode) {
3304   default: return false;
3305   case X86ISD::PSHUFD:
3306   case X86ISD::PSHUFHW:
3307   case X86ISD::PSHUFLW:
3308   case X86ISD::SHUFP:
3309   case X86ISD::PALIGNR:
3310   case X86ISD::MOVLHPS:
3311   case X86ISD::MOVLHPD:
3312   case X86ISD::MOVHLPS:
3313   case X86ISD::MOVLPS:
3314   case X86ISD::MOVLPD:
3315   case X86ISD::MOVSHDUP:
3316   case X86ISD::MOVSLDUP:
3317   case X86ISD::MOVDDUP:
3318   case X86ISD::MOVSS:
3319   case X86ISD::MOVSD:
3320   case X86ISD::UNPCKL:
3321   case X86ISD::UNPCKH:
3322   case X86ISD::VPERMILP:
3323   case X86ISD::VPERM2X128:
3324   case X86ISD::VPERMI:
3325     return true;
3326   }
3327 }
3328
3329 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3330                                     SDValue V1, SelectionDAG &DAG) {
3331   switch(Opc) {
3332   default: llvm_unreachable("Unknown x86 shuffle node");
3333   case X86ISD::MOVSHDUP:
3334   case X86ISD::MOVSLDUP:
3335   case X86ISD::MOVDDUP:
3336     return DAG.getNode(Opc, dl, VT, V1);
3337   }
3338 }
3339
3340 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3341                                     SDValue V1, unsigned TargetMask,
3342                                     SelectionDAG &DAG) {
3343   switch(Opc) {
3344   default: llvm_unreachable("Unknown x86 shuffle node");
3345   case X86ISD::PSHUFD:
3346   case X86ISD::PSHUFHW:
3347   case X86ISD::PSHUFLW:
3348   case X86ISD::VPERMILP:
3349   case X86ISD::VPERMI:
3350     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3351   }
3352 }
3353
3354 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3355                                     SDValue V1, SDValue V2, unsigned TargetMask,
3356                                     SelectionDAG &DAG) {
3357   switch(Opc) {
3358   default: llvm_unreachable("Unknown x86 shuffle node");
3359   case X86ISD::PALIGNR:
3360   case X86ISD::SHUFP:
3361   case X86ISD::VPERM2X128:
3362     return DAG.getNode(Opc, dl, VT, V1, V2,
3363                        DAG.getConstant(TargetMask, MVT::i8));
3364   }
3365 }
3366
3367 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3368                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3369   switch(Opc) {
3370   default: llvm_unreachable("Unknown x86 shuffle node");
3371   case X86ISD::MOVLHPS:
3372   case X86ISD::MOVLHPD:
3373   case X86ISD::MOVHLPS:
3374   case X86ISD::MOVLPS:
3375   case X86ISD::MOVLPD:
3376   case X86ISD::MOVSS:
3377   case X86ISD::MOVSD:
3378   case X86ISD::UNPCKL:
3379   case X86ISD::UNPCKH:
3380     return DAG.getNode(Opc, dl, VT, V1, V2);
3381   }
3382 }
3383
3384 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3385   MachineFunction &MF = DAG.getMachineFunction();
3386   const X86RegisterInfo *RegInfo =
3387     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3388   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3389   int ReturnAddrIndex = FuncInfo->getRAIndex();
3390
3391   if (ReturnAddrIndex == 0) {
3392     // Set up a frame object for the return address.
3393     unsigned SlotSize = RegInfo->getSlotSize();
3394     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3395                                                            -(int64_t)SlotSize,
3396                                                            false);
3397     FuncInfo->setRAIndex(ReturnAddrIndex);
3398   }
3399
3400   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3401 }
3402
3403 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3404                                        bool hasSymbolicDisplacement) {
3405   // Offset should fit into 32 bit immediate field.
3406   if (!isInt<32>(Offset))
3407     return false;
3408
3409   // If we don't have a symbolic displacement - we don't have any extra
3410   // restrictions.
3411   if (!hasSymbolicDisplacement)
3412     return true;
3413
3414   // FIXME: Some tweaks might be needed for medium code model.
3415   if (M != CodeModel::Small && M != CodeModel::Kernel)
3416     return false;
3417
3418   // For small code model we assume that latest object is 16MB before end of 31
3419   // bits boundary. We may also accept pretty large negative constants knowing
3420   // that all objects are in the positive half of address space.
3421   if (M == CodeModel::Small && Offset < 16*1024*1024)
3422     return true;
3423
3424   // For kernel code model we know that all object resist in the negative half
3425   // of 32bits address space. We may not accept negative offsets, since they may
3426   // be just off and we may accept pretty large positive ones.
3427   if (M == CodeModel::Kernel && Offset > 0)
3428     return true;
3429
3430   return false;
3431 }
3432
3433 /// isCalleePop - Determines whether the callee is required to pop its
3434 /// own arguments. Callee pop is necessary to support tail calls.
3435 bool X86::isCalleePop(CallingConv::ID CallingConv,
3436                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3437   if (IsVarArg)
3438     return false;
3439
3440   switch (CallingConv) {
3441   default:
3442     return false;
3443   case CallingConv::X86_StdCall:
3444     return !is64Bit;
3445   case CallingConv::X86_FastCall:
3446     return !is64Bit;
3447   case CallingConv::X86_ThisCall:
3448     return !is64Bit;
3449   case CallingConv::Fast:
3450     return TailCallOpt;
3451   case CallingConv::GHC:
3452     return TailCallOpt;
3453   case CallingConv::HiPE:
3454     return TailCallOpt;
3455   }
3456 }
3457
3458 /// \brief Return true if the condition is an unsigned comparison operation.
3459 static bool isX86CCUnsigned(unsigned X86CC) {
3460   switch (X86CC) {
3461   default: llvm_unreachable("Invalid integer condition!");
3462   case X86::COND_E:     return true;
3463   case X86::COND_G:     return false;
3464   case X86::COND_GE:    return false;
3465   case X86::COND_L:     return false;
3466   case X86::COND_LE:    return false;
3467   case X86::COND_NE:    return true;
3468   case X86::COND_B:     return true;
3469   case X86::COND_A:     return true;
3470   case X86::COND_BE:    return true;
3471   case X86::COND_AE:    return true;
3472   }
3473   llvm_unreachable("covered switch fell through?!");
3474 }
3475
3476 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3477 /// specific condition code, returning the condition code and the LHS/RHS of the
3478 /// comparison to make.
3479 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3480                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3481   if (!isFP) {
3482     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3483       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3484         // X > -1   -> X == 0, jump !sign.
3485         RHS = DAG.getConstant(0, RHS.getValueType());
3486         return X86::COND_NS;
3487       }
3488       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3489         // X < 0   -> X == 0, jump on sign.
3490         return X86::COND_S;
3491       }
3492       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3493         // X < 1   -> X <= 0
3494         RHS = DAG.getConstant(0, RHS.getValueType());
3495         return X86::COND_LE;
3496       }
3497     }
3498
3499     switch (SetCCOpcode) {
3500     default: llvm_unreachable("Invalid integer condition!");
3501     case ISD::SETEQ:  return X86::COND_E;
3502     case ISD::SETGT:  return X86::COND_G;
3503     case ISD::SETGE:  return X86::COND_GE;
3504     case ISD::SETLT:  return X86::COND_L;
3505     case ISD::SETLE:  return X86::COND_LE;
3506     case ISD::SETNE:  return X86::COND_NE;
3507     case ISD::SETULT: return X86::COND_B;
3508     case ISD::SETUGT: return X86::COND_A;
3509     case ISD::SETULE: return X86::COND_BE;
3510     case ISD::SETUGE: return X86::COND_AE;
3511     }
3512   }
3513
3514   // First determine if it is required or is profitable to flip the operands.
3515
3516   // If LHS is a foldable load, but RHS is not, flip the condition.
3517   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3518       !ISD::isNON_EXTLoad(RHS.getNode())) {
3519     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3520     std::swap(LHS, RHS);
3521   }
3522
3523   switch (SetCCOpcode) {
3524   default: break;
3525   case ISD::SETOLT:
3526   case ISD::SETOLE:
3527   case ISD::SETUGT:
3528   case ISD::SETUGE:
3529     std::swap(LHS, RHS);
3530     break;
3531   }
3532
3533   // On a floating point condition, the flags are set as follows:
3534   // ZF  PF  CF   op
3535   //  0 | 0 | 0 | X > Y
3536   //  0 | 0 | 1 | X < Y
3537   //  1 | 0 | 0 | X == Y
3538   //  1 | 1 | 1 | unordered
3539   switch (SetCCOpcode) {
3540   default: llvm_unreachable("Condcode should be pre-legalized away");
3541   case ISD::SETUEQ:
3542   case ISD::SETEQ:   return X86::COND_E;
3543   case ISD::SETOLT:              // flipped
3544   case ISD::SETOGT:
3545   case ISD::SETGT:   return X86::COND_A;
3546   case ISD::SETOLE:              // flipped
3547   case ISD::SETOGE:
3548   case ISD::SETGE:   return X86::COND_AE;
3549   case ISD::SETUGT:              // flipped
3550   case ISD::SETULT:
3551   case ISD::SETLT:   return X86::COND_B;
3552   case ISD::SETUGE:              // flipped
3553   case ISD::SETULE:
3554   case ISD::SETLE:   return X86::COND_BE;
3555   case ISD::SETONE:
3556   case ISD::SETNE:   return X86::COND_NE;
3557   case ISD::SETUO:   return X86::COND_P;
3558   case ISD::SETO:    return X86::COND_NP;
3559   case ISD::SETOEQ:
3560   case ISD::SETUNE:  return X86::COND_INVALID;
3561   }
3562 }
3563
3564 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3565 /// code. Current x86 isa includes the following FP cmov instructions:
3566 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3567 static bool hasFPCMov(unsigned X86CC) {
3568   switch (X86CC) {
3569   default:
3570     return false;
3571   case X86::COND_B:
3572   case X86::COND_BE:
3573   case X86::COND_E:
3574   case X86::COND_P:
3575   case X86::COND_A:
3576   case X86::COND_AE:
3577   case X86::COND_NE:
3578   case X86::COND_NP:
3579     return true;
3580   }
3581 }
3582
3583 /// isFPImmLegal - Returns true if the target can instruction select the
3584 /// specified FP immediate natively. If false, the legalizer will
3585 /// materialize the FP immediate as a load from a constant pool.
3586 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3587   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3588     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3589       return true;
3590   }
3591   return false;
3592 }
3593
3594 /// \brief Returns true if it is beneficial to convert a load of a constant
3595 /// to just the constant itself.
3596 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3597                                                           Type *Ty) const {
3598   assert(Ty->isIntegerTy());
3599
3600   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3601   if (BitSize == 0 || BitSize > 64)
3602     return false;
3603   return true;
3604 }
3605
3606 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3607 /// the specified range (L, H].
3608 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3609   return (Val < 0) || (Val >= Low && Val < Hi);
3610 }
3611
3612 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3613 /// specified value.
3614 static bool isUndefOrEqual(int Val, int CmpVal) {
3615   return (Val < 0 || Val == CmpVal);
3616 }
3617
3618 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3619 /// from position Pos and ending in Pos+Size, falls within the specified
3620 /// sequential range (L, L+Pos]. or is undef.
3621 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3622                                        unsigned Pos, unsigned Size, int Low) {
3623   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3624     if (!isUndefOrEqual(Mask[i], Low))
3625       return false;
3626   return true;
3627 }
3628
3629 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3630 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3631 /// the second operand.
3632 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3633   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3634     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3635   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3636     return (Mask[0] < 2 && Mask[1] < 2);
3637   return false;
3638 }
3639
3640 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3641 /// is suitable for input to PSHUFHW.
3642 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3643   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3644     return false;
3645
3646   // Lower quadword copied in order or undef.
3647   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3648     return false;
3649
3650   // Upper quadword shuffled.
3651   for (unsigned i = 4; i != 8; ++i)
3652     if (!isUndefOrInRange(Mask[i], 4, 8))
3653       return false;
3654
3655   if (VT == MVT::v16i16) {
3656     // Lower quadword copied in order or undef.
3657     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3658       return false;
3659
3660     // Upper quadword shuffled.
3661     for (unsigned i = 12; i != 16; ++i)
3662       if (!isUndefOrInRange(Mask[i], 12, 16))
3663         return false;
3664   }
3665
3666   return true;
3667 }
3668
3669 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3670 /// is suitable for input to PSHUFLW.
3671 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3672   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3673     return false;
3674
3675   // Upper quadword copied in order.
3676   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3677     return false;
3678
3679   // Lower quadword shuffled.
3680   for (unsigned i = 0; i != 4; ++i)
3681     if (!isUndefOrInRange(Mask[i], 0, 4))
3682       return false;
3683
3684   if (VT == MVT::v16i16) {
3685     // Upper quadword copied in order.
3686     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3687       return false;
3688
3689     // Lower quadword shuffled.
3690     for (unsigned i = 8; i != 12; ++i)
3691       if (!isUndefOrInRange(Mask[i], 8, 12))
3692         return false;
3693   }
3694
3695   return true;
3696 }
3697
3698 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3699 /// is suitable for input to PALIGNR.
3700 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3701                           const X86Subtarget *Subtarget) {
3702   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3703       (VT.is256BitVector() && !Subtarget->hasInt256()))
3704     return false;
3705
3706   unsigned NumElts = VT.getVectorNumElements();
3707   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3708   unsigned NumLaneElts = NumElts/NumLanes;
3709
3710   // Do not handle 64-bit element shuffles with palignr.
3711   if (NumLaneElts == 2)
3712     return false;
3713
3714   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3715     unsigned i;
3716     for (i = 0; i != NumLaneElts; ++i) {
3717       if (Mask[i+l] >= 0)
3718         break;
3719     }
3720
3721     // Lane is all undef, go to next lane
3722     if (i == NumLaneElts)
3723       continue;
3724
3725     int Start = Mask[i+l];
3726
3727     // Make sure its in this lane in one of the sources
3728     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3729         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3730       return false;
3731
3732     // If not lane 0, then we must match lane 0
3733     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3734       return false;
3735
3736     // Correct second source to be contiguous with first source
3737     if (Start >= (int)NumElts)
3738       Start -= NumElts - NumLaneElts;
3739
3740     // Make sure we're shifting in the right direction.
3741     if (Start <= (int)(i+l))
3742       return false;
3743
3744     Start -= i;
3745
3746     // Check the rest of the elements to see if they are consecutive.
3747     for (++i; i != NumLaneElts; ++i) {
3748       int Idx = Mask[i+l];
3749
3750       // Make sure its in this lane
3751       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3752           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3753         return false;
3754
3755       // If not lane 0, then we must match lane 0
3756       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3757         return false;
3758
3759       if (Idx >= (int)NumElts)
3760         Idx -= NumElts - NumLaneElts;
3761
3762       if (!isUndefOrEqual(Idx, Start+i))
3763         return false;
3764
3765     }
3766   }
3767
3768   return true;
3769 }
3770
3771 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3772 /// the two vector operands have swapped position.
3773 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3774                                      unsigned NumElems) {
3775   for (unsigned i = 0; i != NumElems; ++i) {
3776     int idx = Mask[i];
3777     if (idx < 0)
3778       continue;
3779     else if (idx < (int)NumElems)
3780       Mask[i] = idx + NumElems;
3781     else
3782       Mask[i] = idx - NumElems;
3783   }
3784 }
3785
3786 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3787 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3788 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3789 /// reverse of what x86 shuffles want.
3790 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3791
3792   unsigned NumElems = VT.getVectorNumElements();
3793   unsigned NumLanes = VT.getSizeInBits()/128;
3794   unsigned NumLaneElems = NumElems/NumLanes;
3795
3796   if (NumLaneElems != 2 && NumLaneElems != 4)
3797     return false;
3798
3799   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3800   bool symetricMaskRequired =
3801     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3802
3803   // VSHUFPSY divides the resulting vector into 4 chunks.
3804   // The sources are also splitted into 4 chunks, and each destination
3805   // chunk must come from a different source chunk.
3806   //
3807   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3808   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3809   //
3810   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3811   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3812   //
3813   // VSHUFPDY divides the resulting vector into 4 chunks.
3814   // The sources are also splitted into 4 chunks, and each destination
3815   // chunk must come from a different source chunk.
3816   //
3817   //  SRC1 =>      X3       X2       X1       X0
3818   //  SRC2 =>      Y3       Y2       Y1       Y0
3819   //
3820   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3821   //
3822   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3823   unsigned HalfLaneElems = NumLaneElems/2;
3824   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3825     for (unsigned i = 0; i != NumLaneElems; ++i) {
3826       int Idx = Mask[i+l];
3827       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3828       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3829         return false;
3830       // For VSHUFPSY, the mask of the second half must be the same as the
3831       // first but with the appropriate offsets. This works in the same way as
3832       // VPERMILPS works with masks.
3833       if (!symetricMaskRequired || Idx < 0)
3834         continue;
3835       if (MaskVal[i] < 0) {
3836         MaskVal[i] = Idx - l;
3837         continue;
3838       }
3839       if ((signed)(Idx - l) != MaskVal[i])
3840         return false;
3841     }
3842   }
3843
3844   return true;
3845 }
3846
3847 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3848 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3849 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3850   if (!VT.is128BitVector())
3851     return false;
3852
3853   unsigned NumElems = VT.getVectorNumElements();
3854
3855   if (NumElems != 4)
3856     return false;
3857
3858   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3859   return isUndefOrEqual(Mask[0], 6) &&
3860          isUndefOrEqual(Mask[1], 7) &&
3861          isUndefOrEqual(Mask[2], 2) &&
3862          isUndefOrEqual(Mask[3], 3);
3863 }
3864
3865 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3866 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3867 /// <2, 3, 2, 3>
3868 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3869   if (!VT.is128BitVector())
3870     return false;
3871
3872   unsigned NumElems = VT.getVectorNumElements();
3873
3874   if (NumElems != 4)
3875     return false;
3876
3877   return isUndefOrEqual(Mask[0], 2) &&
3878          isUndefOrEqual(Mask[1], 3) &&
3879          isUndefOrEqual(Mask[2], 2) &&
3880          isUndefOrEqual(Mask[3], 3);
3881 }
3882
3883 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3884 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3885 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3886   if (!VT.is128BitVector())
3887     return false;
3888
3889   unsigned NumElems = VT.getVectorNumElements();
3890
3891   if (NumElems != 2 && NumElems != 4)
3892     return false;
3893
3894   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3895     if (!isUndefOrEqual(Mask[i], i + NumElems))
3896       return false;
3897
3898   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3899     if (!isUndefOrEqual(Mask[i], i))
3900       return false;
3901
3902   return true;
3903 }
3904
3905 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3907 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3908   if (!VT.is128BitVector())
3909     return false;
3910
3911   unsigned NumElems = VT.getVectorNumElements();
3912
3913   if (NumElems != 2 && NumElems != 4)
3914     return false;
3915
3916   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3917     if (!isUndefOrEqual(Mask[i], i))
3918       return false;
3919
3920   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3921     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3922       return false;
3923
3924   return true;
3925 }
3926
3927 //
3928 // Some special combinations that can be optimized.
3929 //
3930 static
3931 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3932                                SelectionDAG &DAG) {
3933   MVT VT = SVOp->getSimpleValueType(0);
3934   SDLoc dl(SVOp);
3935
3936   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3937     return SDValue();
3938
3939   ArrayRef<int> Mask = SVOp->getMask();
3940
3941   // These are the special masks that may be optimized.
3942   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3943   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3944   bool MatchEvenMask = true;
3945   bool MatchOddMask  = true;
3946   for (int i=0; i<8; ++i) {
3947     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3948       MatchEvenMask = false;
3949     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3950       MatchOddMask = false;
3951   }
3952
3953   if (!MatchEvenMask && !MatchOddMask)
3954     return SDValue();
3955
3956   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3957
3958   SDValue Op0 = SVOp->getOperand(0);
3959   SDValue Op1 = SVOp->getOperand(1);
3960
3961   if (MatchEvenMask) {
3962     // Shift the second operand right to 32 bits.
3963     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3964     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3965   } else {
3966     // Shift the first operand left to 32 bits.
3967     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3968     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3969   }
3970   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3971   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3972 }
3973
3974 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3975 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3976 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3977                          bool HasInt256, bool V2IsSplat = false) {
3978
3979   assert(VT.getSizeInBits() >= 128 &&
3980          "Unsupported vector type for unpckl");
3981
3982   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3983   unsigned NumLanes;
3984   unsigned NumOf256BitLanes;
3985   unsigned NumElts = VT.getVectorNumElements();
3986   if (VT.is256BitVector()) {
3987     if (NumElts != 4 && NumElts != 8 &&
3988         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3989     return false;
3990     NumLanes = 2;
3991     NumOf256BitLanes = 1;
3992   } else if (VT.is512BitVector()) {
3993     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3994            "Unsupported vector type for unpckh");
3995     NumLanes = 2;
3996     NumOf256BitLanes = 2;
3997   } else {
3998     NumLanes = 1;
3999     NumOf256BitLanes = 1;
4000   }
4001
4002   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4003   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4004
4005   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4006     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4007       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4008         int BitI  = Mask[l256*NumEltsInStride+l+i];
4009         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4010         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4011           return false;
4012         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4013           return false;
4014         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4015           return false;
4016       }
4017     }
4018   }
4019   return true;
4020 }
4021
4022 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4023 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4024 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4025                          bool HasInt256, bool V2IsSplat = false) {
4026   assert(VT.getSizeInBits() >= 128 &&
4027          "Unsupported vector type for unpckh");
4028
4029   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4030   unsigned NumLanes;
4031   unsigned NumOf256BitLanes;
4032   unsigned NumElts = VT.getVectorNumElements();
4033   if (VT.is256BitVector()) {
4034     if (NumElts != 4 && NumElts != 8 &&
4035         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4036     return false;
4037     NumLanes = 2;
4038     NumOf256BitLanes = 1;
4039   } else if (VT.is512BitVector()) {
4040     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4041            "Unsupported vector type for unpckh");
4042     NumLanes = 2;
4043     NumOf256BitLanes = 2;
4044   } else {
4045     NumLanes = 1;
4046     NumOf256BitLanes = 1;
4047   }
4048
4049   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4050   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4051
4052   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4053     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4054       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4055         int BitI  = Mask[l256*NumEltsInStride+l+i];
4056         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4057         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4058           return false;
4059         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4060           return false;
4061         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4062           return false;
4063       }
4064     }
4065   }
4066   return true;
4067 }
4068
4069 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4070 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4071 /// <0, 0, 1, 1>
4072 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4073   unsigned NumElts = VT.getVectorNumElements();
4074   bool Is256BitVec = VT.is256BitVector();
4075
4076   if (VT.is512BitVector())
4077     return false;
4078   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4079          "Unsupported vector type for unpckh");
4080
4081   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4082       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4083     return false;
4084
4085   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4086   // FIXME: Need a better way to get rid of this, there's no latency difference
4087   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4088   // the former later. We should also remove the "_undef" special mask.
4089   if (NumElts == 4 && Is256BitVec)
4090     return false;
4091
4092   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4093   // independently on 128-bit lanes.
4094   unsigned NumLanes = VT.getSizeInBits()/128;
4095   unsigned NumLaneElts = NumElts/NumLanes;
4096
4097   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4098     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4099       int BitI  = Mask[l+i];
4100       int BitI1 = Mask[l+i+1];
4101
4102       if (!isUndefOrEqual(BitI, j))
4103         return false;
4104       if (!isUndefOrEqual(BitI1, j))
4105         return false;
4106     }
4107   }
4108
4109   return true;
4110 }
4111
4112 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4113 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4114 /// <2, 2, 3, 3>
4115 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4116   unsigned NumElts = VT.getVectorNumElements();
4117
4118   if (VT.is512BitVector())
4119     return false;
4120
4121   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4122          "Unsupported vector type for unpckh");
4123
4124   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4125       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4126     return false;
4127
4128   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4129   // independently on 128-bit lanes.
4130   unsigned NumLanes = VT.getSizeInBits()/128;
4131   unsigned NumLaneElts = NumElts/NumLanes;
4132
4133   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4134     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4135       int BitI  = Mask[l+i];
4136       int BitI1 = Mask[l+i+1];
4137       if (!isUndefOrEqual(BitI, j))
4138         return false;
4139       if (!isUndefOrEqual(BitI1, j))
4140         return false;
4141     }
4142   }
4143   return true;
4144 }
4145
4146 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4147 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4148 /// MOVSD, and MOVD, i.e. setting the lowest element.
4149 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4150   if (VT.getVectorElementType().getSizeInBits() < 32)
4151     return false;
4152   if (!VT.is128BitVector())
4153     return false;
4154
4155   unsigned NumElts = VT.getVectorNumElements();
4156
4157   if (!isUndefOrEqual(Mask[0], NumElts))
4158     return false;
4159
4160   for (unsigned i = 1; i != NumElts; ++i)
4161     if (!isUndefOrEqual(Mask[i], i))
4162       return false;
4163
4164   return true;
4165 }
4166
4167 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4168 /// as permutations between 128-bit chunks or halves. As an example: this
4169 /// shuffle bellow:
4170 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4171 /// The first half comes from the second half of V1 and the second half from the
4172 /// the second half of V2.
4173 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4174   if (!HasFp256 || !VT.is256BitVector())
4175     return false;
4176
4177   // The shuffle result is divided into half A and half B. In total the two
4178   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4179   // B must come from C, D, E or F.
4180   unsigned HalfSize = VT.getVectorNumElements()/2;
4181   bool MatchA = false, MatchB = false;
4182
4183   // Check if A comes from one of C, D, E, F.
4184   for (unsigned Half = 0; Half != 4; ++Half) {
4185     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4186       MatchA = true;
4187       break;
4188     }
4189   }
4190
4191   // Check if B comes from one of C, D, E, F.
4192   for (unsigned Half = 0; Half != 4; ++Half) {
4193     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4194       MatchB = true;
4195       break;
4196     }
4197   }
4198
4199   return MatchA && MatchB;
4200 }
4201
4202 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4203 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4204 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4205   MVT VT = SVOp->getSimpleValueType(0);
4206
4207   unsigned HalfSize = VT.getVectorNumElements()/2;
4208
4209   unsigned FstHalf = 0, SndHalf = 0;
4210   for (unsigned i = 0; i < HalfSize; ++i) {
4211     if (SVOp->getMaskElt(i) > 0) {
4212       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4213       break;
4214     }
4215   }
4216   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4217     if (SVOp->getMaskElt(i) > 0) {
4218       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4219       break;
4220     }
4221   }
4222
4223   return (FstHalf | (SndHalf << 4));
4224 }
4225
4226 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4227 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4228   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4229   if (EltSize < 32)
4230     return false;
4231
4232   unsigned NumElts = VT.getVectorNumElements();
4233   Imm8 = 0;
4234   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4235     for (unsigned i = 0; i != NumElts; ++i) {
4236       if (Mask[i] < 0)
4237         continue;
4238       Imm8 |= Mask[i] << (i*2);
4239     }
4240     return true;
4241   }
4242
4243   unsigned LaneSize = 4;
4244   SmallVector<int, 4> MaskVal(LaneSize, -1);
4245
4246   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4247     for (unsigned i = 0; i != LaneSize; ++i) {
4248       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4249         return false;
4250       if (Mask[i+l] < 0)
4251         continue;
4252       if (MaskVal[i] < 0) {
4253         MaskVal[i] = Mask[i+l] - l;
4254         Imm8 |= MaskVal[i] << (i*2);
4255         continue;
4256       }
4257       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4258         return false;
4259     }
4260   }
4261   return true;
4262 }
4263
4264 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4265 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4266 /// Note that VPERMIL mask matching is different depending whether theunderlying
4267 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4268 /// to the same elements of the low, but to the higher half of the source.
4269 /// In VPERMILPD the two lanes could be shuffled independently of each other
4270 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4271 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4272   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4273   if (VT.getSizeInBits() < 256 || EltSize < 32)
4274     return false;
4275   bool symetricMaskRequired = (EltSize == 32);
4276   unsigned NumElts = VT.getVectorNumElements();
4277
4278   unsigned NumLanes = VT.getSizeInBits()/128;
4279   unsigned LaneSize = NumElts/NumLanes;
4280   // 2 or 4 elements in one lane
4281
4282   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4283   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4284     for (unsigned i = 0; i != LaneSize; ++i) {
4285       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4286         return false;
4287       if (symetricMaskRequired) {
4288         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4289           ExpectedMaskVal[i] = Mask[i+l] - l;
4290           continue;
4291         }
4292         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4293           return false;
4294       }
4295     }
4296   }
4297   return true;
4298 }
4299
4300 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4301 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4302 /// element of vector 2 and the other elements to come from vector 1 in order.
4303 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4304                                bool V2IsSplat = false, bool V2IsUndef = false) {
4305   if (!VT.is128BitVector())
4306     return false;
4307
4308   unsigned NumOps = VT.getVectorNumElements();
4309   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4310     return false;
4311
4312   if (!isUndefOrEqual(Mask[0], 0))
4313     return false;
4314
4315   for (unsigned i = 1; i != NumOps; ++i)
4316     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4317           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4318           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4319       return false;
4320
4321   return true;
4322 }
4323
4324 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4325 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4326 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4327 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4328                            const X86Subtarget *Subtarget) {
4329   if (!Subtarget->hasSSE3())
4330     return false;
4331
4332   unsigned NumElems = VT.getVectorNumElements();
4333
4334   if ((VT.is128BitVector() && NumElems != 4) ||
4335       (VT.is256BitVector() && NumElems != 8) ||
4336       (VT.is512BitVector() && NumElems != 16))
4337     return false;
4338
4339   // "i+1" is the value the indexed mask element must have
4340   for (unsigned i = 0; i != NumElems; i += 2)
4341     if (!isUndefOrEqual(Mask[i], i+1) ||
4342         !isUndefOrEqual(Mask[i+1], i+1))
4343       return false;
4344
4345   return true;
4346 }
4347
4348 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4349 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4350 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4351 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4352                            const X86Subtarget *Subtarget) {
4353   if (!Subtarget->hasSSE3())
4354     return false;
4355
4356   unsigned NumElems = VT.getVectorNumElements();
4357
4358   if ((VT.is128BitVector() && NumElems != 4) ||
4359       (VT.is256BitVector() && NumElems != 8) ||
4360       (VT.is512BitVector() && NumElems != 16))
4361     return false;
4362
4363   // "i" is the value the indexed mask element must have
4364   for (unsigned i = 0; i != NumElems; i += 2)
4365     if (!isUndefOrEqual(Mask[i], i) ||
4366         !isUndefOrEqual(Mask[i+1], i))
4367       return false;
4368
4369   return true;
4370 }
4371
4372 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4373 /// specifies a shuffle of elements that is suitable for input to 256-bit
4374 /// version of MOVDDUP.
4375 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4376   if (!HasFp256 || !VT.is256BitVector())
4377     return false;
4378
4379   unsigned NumElts = VT.getVectorNumElements();
4380   if (NumElts != 4)
4381     return false;
4382
4383   for (unsigned i = 0; i != NumElts/2; ++i)
4384     if (!isUndefOrEqual(Mask[i], 0))
4385       return false;
4386   for (unsigned i = NumElts/2; i != NumElts; ++i)
4387     if (!isUndefOrEqual(Mask[i], NumElts/2))
4388       return false;
4389   return true;
4390 }
4391
4392 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4393 /// specifies a shuffle of elements that is suitable for input to 128-bit
4394 /// version of MOVDDUP.
4395 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4396   if (!VT.is128BitVector())
4397     return false;
4398
4399   unsigned e = VT.getVectorNumElements() / 2;
4400   for (unsigned i = 0; i != e; ++i)
4401     if (!isUndefOrEqual(Mask[i], i))
4402       return false;
4403   for (unsigned i = 0; i != e; ++i)
4404     if (!isUndefOrEqual(Mask[e+i], i))
4405       return false;
4406   return true;
4407 }
4408
4409 /// isVEXTRACTIndex - Return true if the specified
4410 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4411 /// suitable for instruction that extract 128 or 256 bit vectors
4412 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4413   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4414   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4415     return false;
4416
4417   // The index should be aligned on a vecWidth-bit boundary.
4418   uint64_t Index =
4419     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4420
4421   MVT VT = N->getSimpleValueType(0);
4422   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4423   bool Result = (Index * ElSize) % vecWidth == 0;
4424
4425   return Result;
4426 }
4427
4428 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4429 /// operand specifies a subvector insert that is suitable for input to
4430 /// insertion of 128 or 256-bit subvectors
4431 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4432   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4433   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4434     return false;
4435   // The index should be aligned on a vecWidth-bit boundary.
4436   uint64_t Index =
4437     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4438
4439   MVT VT = N->getSimpleValueType(0);
4440   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4441   bool Result = (Index * ElSize) % vecWidth == 0;
4442
4443   return Result;
4444 }
4445
4446 bool X86::isVINSERT128Index(SDNode *N) {
4447   return isVINSERTIndex(N, 128);
4448 }
4449
4450 bool X86::isVINSERT256Index(SDNode *N) {
4451   return isVINSERTIndex(N, 256);
4452 }
4453
4454 bool X86::isVEXTRACT128Index(SDNode *N) {
4455   return isVEXTRACTIndex(N, 128);
4456 }
4457
4458 bool X86::isVEXTRACT256Index(SDNode *N) {
4459   return isVEXTRACTIndex(N, 256);
4460 }
4461
4462 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4463 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4464 /// Handles 128-bit and 256-bit.
4465 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4466   MVT VT = N->getSimpleValueType(0);
4467
4468   assert((VT.getSizeInBits() >= 128) &&
4469          "Unsupported vector type for PSHUF/SHUFP");
4470
4471   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4472   // independently on 128-bit lanes.
4473   unsigned NumElts = VT.getVectorNumElements();
4474   unsigned NumLanes = VT.getSizeInBits()/128;
4475   unsigned NumLaneElts = NumElts/NumLanes;
4476
4477   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4478          "Only supports 2, 4 or 8 elements per lane");
4479
4480   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4481   unsigned Mask = 0;
4482   for (unsigned i = 0; i != NumElts; ++i) {
4483     int Elt = N->getMaskElt(i);
4484     if (Elt < 0) continue;
4485     Elt &= NumLaneElts - 1;
4486     unsigned ShAmt = (i << Shift) % 8;
4487     Mask |= Elt << ShAmt;
4488   }
4489
4490   return Mask;
4491 }
4492
4493 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4494 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4495 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4496   MVT VT = N->getSimpleValueType(0);
4497
4498   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4499          "Unsupported vector type for PSHUFHW");
4500
4501   unsigned NumElts = VT.getVectorNumElements();
4502
4503   unsigned Mask = 0;
4504   for (unsigned l = 0; l != NumElts; l += 8) {
4505     // 8 nodes per lane, but we only care about the last 4.
4506     for (unsigned i = 0; i < 4; ++i) {
4507       int Elt = N->getMaskElt(l+i+4);
4508       if (Elt < 0) continue;
4509       Elt &= 0x3; // only 2-bits.
4510       Mask |= Elt << (i * 2);
4511     }
4512   }
4513
4514   return Mask;
4515 }
4516
4517 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4518 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4519 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4520   MVT VT = N->getSimpleValueType(0);
4521
4522   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4523          "Unsupported vector type for PSHUFHW");
4524
4525   unsigned NumElts = VT.getVectorNumElements();
4526
4527   unsigned Mask = 0;
4528   for (unsigned l = 0; l != NumElts; l += 8) {
4529     // 8 nodes per lane, but we only care about the first 4.
4530     for (unsigned i = 0; i < 4; ++i) {
4531       int Elt = N->getMaskElt(l+i);
4532       if (Elt < 0) continue;
4533       Elt &= 0x3; // only 2-bits
4534       Mask |= Elt << (i * 2);
4535     }
4536   }
4537
4538   return Mask;
4539 }
4540
4541 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4542 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4543 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4544   MVT VT = SVOp->getSimpleValueType(0);
4545   unsigned EltSize = VT.is512BitVector() ? 1 :
4546     VT.getVectorElementType().getSizeInBits() >> 3;
4547
4548   unsigned NumElts = VT.getVectorNumElements();
4549   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4550   unsigned NumLaneElts = NumElts/NumLanes;
4551
4552   int Val = 0;
4553   unsigned i;
4554   for (i = 0; i != NumElts; ++i) {
4555     Val = SVOp->getMaskElt(i);
4556     if (Val >= 0)
4557       break;
4558   }
4559   if (Val >= (int)NumElts)
4560     Val -= NumElts - NumLaneElts;
4561
4562   assert(Val - i > 0 && "PALIGNR imm should be positive");
4563   return (Val - i) * EltSize;
4564 }
4565
4566 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4567   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4568   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4569     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4570
4571   uint64_t Index =
4572     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4573
4574   MVT VecVT = N->getOperand(0).getSimpleValueType();
4575   MVT ElVT = VecVT.getVectorElementType();
4576
4577   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4578   return Index / NumElemsPerChunk;
4579 }
4580
4581 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4582   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4583   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4584     llvm_unreachable("Illegal insert subvector for VINSERT");
4585
4586   uint64_t Index =
4587     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4588
4589   MVT VecVT = N->getSimpleValueType(0);
4590   MVT ElVT = VecVT.getVectorElementType();
4591
4592   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4593   return Index / NumElemsPerChunk;
4594 }
4595
4596 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4597 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4598 /// and VINSERTI128 instructions.
4599 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4600   return getExtractVEXTRACTImmediate(N, 128);
4601 }
4602
4603 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4604 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4605 /// and VINSERTI64x4 instructions.
4606 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4607   return getExtractVEXTRACTImmediate(N, 256);
4608 }
4609
4610 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4611 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4612 /// and VINSERTI128 instructions.
4613 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4614   return getInsertVINSERTImmediate(N, 128);
4615 }
4616
4617 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4618 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4619 /// and VINSERTI64x4 instructions.
4620 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4621   return getInsertVINSERTImmediate(N, 256);
4622 }
4623
4624 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4625 /// constant +0.0.
4626 bool X86::isZeroNode(SDValue Elt) {
4627   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4628     return CN->isNullValue();
4629   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4630     return CFP->getValueAPF().isPosZero();
4631   return false;
4632 }
4633
4634 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4635 /// their permute mask.
4636 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4637                                     SelectionDAG &DAG) {
4638   MVT VT = SVOp->getSimpleValueType(0);
4639   unsigned NumElems = VT.getVectorNumElements();
4640   SmallVector<int, 8> MaskVec;
4641
4642   for (unsigned i = 0; i != NumElems; ++i) {
4643     int Idx = SVOp->getMaskElt(i);
4644     if (Idx >= 0) {
4645       if (Idx < (int)NumElems)
4646         Idx += NumElems;
4647       else
4648         Idx -= NumElems;
4649     }
4650     MaskVec.push_back(Idx);
4651   }
4652   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4653                               SVOp->getOperand(0), &MaskVec[0]);
4654 }
4655
4656 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4657 /// match movhlps. The lower half elements should come from upper half of
4658 /// V1 (and in order), and the upper half elements should come from the upper
4659 /// half of V2 (and in order).
4660 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4661   if (!VT.is128BitVector())
4662     return false;
4663   if (VT.getVectorNumElements() != 4)
4664     return false;
4665   for (unsigned i = 0, e = 2; i != e; ++i)
4666     if (!isUndefOrEqual(Mask[i], i+2))
4667       return false;
4668   for (unsigned i = 2; i != 4; ++i)
4669     if (!isUndefOrEqual(Mask[i], i+4))
4670       return false;
4671   return true;
4672 }
4673
4674 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4675 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4676 /// required.
4677 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4678   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4679     return false;
4680   N = N->getOperand(0).getNode();
4681   if (!ISD::isNON_EXTLoad(N))
4682     return false;
4683   if (LD)
4684     *LD = cast<LoadSDNode>(N);
4685   return true;
4686 }
4687
4688 // Test whether the given value is a vector value which will be legalized
4689 // into a load.
4690 static bool WillBeConstantPoolLoad(SDNode *N) {
4691   if (N->getOpcode() != ISD::BUILD_VECTOR)
4692     return false;
4693
4694   // Check for any non-constant elements.
4695   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4696     switch (N->getOperand(i).getNode()->getOpcode()) {
4697     case ISD::UNDEF:
4698     case ISD::ConstantFP:
4699     case ISD::Constant:
4700       break;
4701     default:
4702       return false;
4703     }
4704
4705   // Vectors of all-zeros and all-ones are materialized with special
4706   // instructions rather than being loaded.
4707   return !ISD::isBuildVectorAllZeros(N) &&
4708          !ISD::isBuildVectorAllOnes(N);
4709 }
4710
4711 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4712 /// match movlp{s|d}. The lower half elements should come from lower half of
4713 /// V1 (and in order), and the upper half elements should come from the upper
4714 /// half of V2 (and in order). And since V1 will become the source of the
4715 /// MOVLP, it must be either a vector load or a scalar load to vector.
4716 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4717                                ArrayRef<int> Mask, MVT VT) {
4718   if (!VT.is128BitVector())
4719     return false;
4720
4721   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4722     return false;
4723   // Is V2 is a vector load, don't do this transformation. We will try to use
4724   // load folding shufps op.
4725   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4726     return false;
4727
4728   unsigned NumElems = VT.getVectorNumElements();
4729
4730   if (NumElems != 2 && NumElems != 4)
4731     return false;
4732   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4733     if (!isUndefOrEqual(Mask[i], i))
4734       return false;
4735   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4736     if (!isUndefOrEqual(Mask[i], i+NumElems))
4737       return false;
4738   return true;
4739 }
4740
4741 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4742 /// all the same.
4743 static bool isSplatVector(SDNode *N) {
4744   if (N->getOpcode() != ISD::BUILD_VECTOR)
4745     return false;
4746
4747   SDValue SplatValue = N->getOperand(0);
4748   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4749     if (N->getOperand(i) != SplatValue)
4750       return false;
4751   return true;
4752 }
4753
4754 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4755 /// to an zero vector.
4756 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4757 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4758   SDValue V1 = N->getOperand(0);
4759   SDValue V2 = N->getOperand(1);
4760   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4761   for (unsigned i = 0; i != NumElems; ++i) {
4762     int Idx = N->getMaskElt(i);
4763     if (Idx >= (int)NumElems) {
4764       unsigned Opc = V2.getOpcode();
4765       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4766         continue;
4767       if (Opc != ISD::BUILD_VECTOR ||
4768           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4769         return false;
4770     } else if (Idx >= 0) {
4771       unsigned Opc = V1.getOpcode();
4772       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4773         continue;
4774       if (Opc != ISD::BUILD_VECTOR ||
4775           !X86::isZeroNode(V1.getOperand(Idx)))
4776         return false;
4777     }
4778   }
4779   return true;
4780 }
4781
4782 /// getZeroVector - Returns a vector of specified type with all zero elements.
4783 ///
4784 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4785                              SelectionDAG &DAG, SDLoc dl) {
4786   assert(VT.isVector() && "Expected a vector type");
4787
4788   // Always build SSE zero vectors as <4 x i32> bitcasted
4789   // to their dest type. This ensures they get CSE'd.
4790   SDValue Vec;
4791   if (VT.is128BitVector()) {  // SSE
4792     if (Subtarget->hasSSE2()) {  // SSE2
4793       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4794       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4795     } else { // SSE1
4796       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4797       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4798     }
4799   } else if (VT.is256BitVector()) { // AVX
4800     if (Subtarget->hasInt256()) { // AVX2
4801       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4802       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4803       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4804                         array_lengthof(Ops));
4805     } else {
4806       // 256-bit logic and arithmetic instructions in AVX are all
4807       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4808       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4809       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4810       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4811                         array_lengthof(Ops));
4812     }
4813   } else if (VT.is512BitVector()) { // AVX-512
4814       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4815       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4816                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4817       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4818   } else if (VT.getScalarType() == MVT::i1) {
4819     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4820     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4821     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4822                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4823     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4824                        Ops, VT.getVectorNumElements());
4825   } else
4826     llvm_unreachable("Unexpected vector type");
4827
4828   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4829 }
4830
4831 /// getOnesVector - Returns a vector of specified type with all bits set.
4832 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4833 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4834 /// Then bitcast to their original type, ensuring they get CSE'd.
4835 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4836                              SDLoc dl) {
4837   assert(VT.isVector() && "Expected a vector type");
4838
4839   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4840   SDValue Vec;
4841   if (VT.is256BitVector()) {
4842     if (HasInt256) { // AVX2
4843       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4844       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4845                         array_lengthof(Ops));
4846     } else { // AVX
4847       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4848       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4849     }
4850   } else if (VT.is128BitVector()) {
4851     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4852   } else
4853     llvm_unreachable("Unexpected vector type");
4854
4855   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4856 }
4857
4858 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4859 /// that point to V2 points to its first element.
4860 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4861   for (unsigned i = 0; i != NumElems; ++i) {
4862     if (Mask[i] > (int)NumElems) {
4863       Mask[i] = NumElems;
4864     }
4865   }
4866 }
4867
4868 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4869 /// operation of specified width.
4870 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4871                        SDValue V2) {
4872   unsigned NumElems = VT.getVectorNumElements();
4873   SmallVector<int, 8> Mask;
4874   Mask.push_back(NumElems);
4875   for (unsigned i = 1; i != NumElems; ++i)
4876     Mask.push_back(i);
4877   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4878 }
4879
4880 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4881 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4882                           SDValue V2) {
4883   unsigned NumElems = VT.getVectorNumElements();
4884   SmallVector<int, 8> Mask;
4885   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4886     Mask.push_back(i);
4887     Mask.push_back(i + NumElems);
4888   }
4889   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4890 }
4891
4892 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4893 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4894                           SDValue V2) {
4895   unsigned NumElems = VT.getVectorNumElements();
4896   SmallVector<int, 8> Mask;
4897   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4898     Mask.push_back(i + Half);
4899     Mask.push_back(i + NumElems + Half);
4900   }
4901   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4902 }
4903
4904 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4905 // a generic shuffle instruction because the target has no such instructions.
4906 // Generate shuffles which repeat i16 and i8 several times until they can be
4907 // represented by v4f32 and then be manipulated by target suported shuffles.
4908 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4909   MVT VT = V.getSimpleValueType();
4910   int NumElems = VT.getVectorNumElements();
4911   SDLoc dl(V);
4912
4913   while (NumElems > 4) {
4914     if (EltNo < NumElems/2) {
4915       V = getUnpackl(DAG, dl, VT, V, V);
4916     } else {
4917       V = getUnpackh(DAG, dl, VT, V, V);
4918       EltNo -= NumElems/2;
4919     }
4920     NumElems >>= 1;
4921   }
4922   return V;
4923 }
4924
4925 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4926 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4927   MVT VT = V.getSimpleValueType();
4928   SDLoc dl(V);
4929
4930   if (VT.is128BitVector()) {
4931     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4932     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4933     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4934                              &SplatMask[0]);
4935   } else if (VT.is256BitVector()) {
4936     // To use VPERMILPS to splat scalars, the second half of indicies must
4937     // refer to the higher part, which is a duplication of the lower one,
4938     // because VPERMILPS can only handle in-lane permutations.
4939     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4940                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4941
4942     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4943     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4944                              &SplatMask[0]);
4945   } else
4946     llvm_unreachable("Vector size not supported");
4947
4948   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4949 }
4950
4951 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4952 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4953   MVT SrcVT = SV->getSimpleValueType(0);
4954   SDValue V1 = SV->getOperand(0);
4955   SDLoc dl(SV);
4956
4957   int EltNo = SV->getSplatIndex();
4958   int NumElems = SrcVT.getVectorNumElements();
4959   bool Is256BitVec = SrcVT.is256BitVector();
4960
4961   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4962          "Unknown how to promote splat for type");
4963
4964   // Extract the 128-bit part containing the splat element and update
4965   // the splat element index when it refers to the higher register.
4966   if (Is256BitVec) {
4967     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4968     if (EltNo >= NumElems/2)
4969       EltNo -= NumElems/2;
4970   }
4971
4972   // All i16 and i8 vector types can't be used directly by a generic shuffle
4973   // instruction because the target has no such instruction. Generate shuffles
4974   // which repeat i16 and i8 several times until they fit in i32, and then can
4975   // be manipulated by target suported shuffles.
4976   MVT EltVT = SrcVT.getVectorElementType();
4977   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4978     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4979
4980   // Recreate the 256-bit vector and place the same 128-bit vector
4981   // into the low and high part. This is necessary because we want
4982   // to use VPERM* to shuffle the vectors
4983   if (Is256BitVec) {
4984     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4985   }
4986
4987   return getLegalSplat(DAG, V1, EltNo);
4988 }
4989
4990 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4991 /// vector of zero or undef vector.  This produces a shuffle where the low
4992 /// element of V2 is swizzled into the zero/undef vector, landing at element
4993 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4994 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4995                                            bool IsZero,
4996                                            const X86Subtarget *Subtarget,
4997                                            SelectionDAG &DAG) {
4998   MVT VT = V2.getSimpleValueType();
4999   SDValue V1 = IsZero
5000     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5001   unsigned NumElems = VT.getVectorNumElements();
5002   SmallVector<int, 16> MaskVec;
5003   for (unsigned i = 0; i != NumElems; ++i)
5004     // If this is the insertion idx, put the low elt of V2 here.
5005     MaskVec.push_back(i == Idx ? NumElems : i);
5006   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5007 }
5008
5009 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5010 /// target specific opcode. Returns true if the Mask could be calculated.
5011 /// Sets IsUnary to true if only uses one source.
5012 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5013                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5014   unsigned NumElems = VT.getVectorNumElements();
5015   SDValue ImmN;
5016
5017   IsUnary = false;
5018   switch(N->getOpcode()) {
5019   case X86ISD::SHUFP:
5020     ImmN = N->getOperand(N->getNumOperands()-1);
5021     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5022     break;
5023   case X86ISD::UNPCKH:
5024     DecodeUNPCKHMask(VT, Mask);
5025     break;
5026   case X86ISD::UNPCKL:
5027     DecodeUNPCKLMask(VT, Mask);
5028     break;
5029   case X86ISD::MOVHLPS:
5030     DecodeMOVHLPSMask(NumElems, Mask);
5031     break;
5032   case X86ISD::MOVLHPS:
5033     DecodeMOVLHPSMask(NumElems, Mask);
5034     break;
5035   case X86ISD::PALIGNR:
5036     ImmN = N->getOperand(N->getNumOperands()-1);
5037     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5038     break;
5039   case X86ISD::PSHUFD:
5040   case X86ISD::VPERMILP:
5041     ImmN = N->getOperand(N->getNumOperands()-1);
5042     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5043     IsUnary = true;
5044     break;
5045   case X86ISD::PSHUFHW:
5046     ImmN = N->getOperand(N->getNumOperands()-1);
5047     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5048     IsUnary = true;
5049     break;
5050   case X86ISD::PSHUFLW:
5051     ImmN = N->getOperand(N->getNumOperands()-1);
5052     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5053     IsUnary = true;
5054     break;
5055   case X86ISD::VPERMI:
5056     ImmN = N->getOperand(N->getNumOperands()-1);
5057     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5058     IsUnary = true;
5059     break;
5060   case X86ISD::MOVSS:
5061   case X86ISD::MOVSD: {
5062     // The index 0 always comes from the first element of the second source,
5063     // this is why MOVSS and MOVSD are used in the first place. The other
5064     // elements come from the other positions of the first source vector
5065     Mask.push_back(NumElems);
5066     for (unsigned i = 1; i != NumElems; ++i) {
5067       Mask.push_back(i);
5068     }
5069     break;
5070   }
5071   case X86ISD::VPERM2X128:
5072     ImmN = N->getOperand(N->getNumOperands()-1);
5073     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5074     if (Mask.empty()) return false;
5075     break;
5076   case X86ISD::MOVDDUP:
5077   case X86ISD::MOVLHPD:
5078   case X86ISD::MOVLPD:
5079   case X86ISD::MOVLPS:
5080   case X86ISD::MOVSHDUP:
5081   case X86ISD::MOVSLDUP:
5082     // Not yet implemented
5083     return false;
5084   default: llvm_unreachable("unknown target shuffle node");
5085   }
5086
5087   return true;
5088 }
5089
5090 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5091 /// element of the result of the vector shuffle.
5092 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5093                                    unsigned Depth) {
5094   if (Depth == 6)
5095     return SDValue();  // Limit search depth.
5096
5097   SDValue V = SDValue(N, 0);
5098   EVT VT = V.getValueType();
5099   unsigned Opcode = V.getOpcode();
5100
5101   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5102   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5103     int Elt = SV->getMaskElt(Index);
5104
5105     if (Elt < 0)
5106       return DAG.getUNDEF(VT.getVectorElementType());
5107
5108     unsigned NumElems = VT.getVectorNumElements();
5109     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5110                                          : SV->getOperand(1);
5111     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5112   }
5113
5114   // Recurse into target specific vector shuffles to find scalars.
5115   if (isTargetShuffle(Opcode)) {
5116     MVT ShufVT = V.getSimpleValueType();
5117     unsigned NumElems = ShufVT.getVectorNumElements();
5118     SmallVector<int, 16> ShuffleMask;
5119     bool IsUnary;
5120
5121     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5122       return SDValue();
5123
5124     int Elt = ShuffleMask[Index];
5125     if (Elt < 0)
5126       return DAG.getUNDEF(ShufVT.getVectorElementType());
5127
5128     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5129                                          : N->getOperand(1);
5130     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5131                                Depth+1);
5132   }
5133
5134   // Actual nodes that may contain scalar elements
5135   if (Opcode == ISD::BITCAST) {
5136     V = V.getOperand(0);
5137     EVT SrcVT = V.getValueType();
5138     unsigned NumElems = VT.getVectorNumElements();
5139
5140     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5141       return SDValue();
5142   }
5143
5144   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5145     return (Index == 0) ? V.getOperand(0)
5146                         : DAG.getUNDEF(VT.getVectorElementType());
5147
5148   if (V.getOpcode() == ISD::BUILD_VECTOR)
5149     return V.getOperand(Index);
5150
5151   return SDValue();
5152 }
5153
5154 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5155 /// shuffle operation which come from a consecutively from a zero. The
5156 /// search can start in two different directions, from left or right.
5157 /// We count undefs as zeros until PreferredNum is reached.
5158 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5159                                          unsigned NumElems, bool ZerosFromLeft,
5160                                          SelectionDAG &DAG,
5161                                          unsigned PreferredNum = -1U) {
5162   unsigned NumZeros = 0;
5163   for (unsigned i = 0; i != NumElems; ++i) {
5164     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5165     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5166     if (!Elt.getNode())
5167       break;
5168
5169     if (X86::isZeroNode(Elt))
5170       ++NumZeros;
5171     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5172       NumZeros = std::min(NumZeros + 1, PreferredNum);
5173     else
5174       break;
5175   }
5176
5177   return NumZeros;
5178 }
5179
5180 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5181 /// correspond consecutively to elements from one of the vector operands,
5182 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5183 static
5184 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5185                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5186                               unsigned NumElems, unsigned &OpNum) {
5187   bool SeenV1 = false;
5188   bool SeenV2 = false;
5189
5190   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5191     int Idx = SVOp->getMaskElt(i);
5192     // Ignore undef indicies
5193     if (Idx < 0)
5194       continue;
5195
5196     if (Idx < (int)NumElems)
5197       SeenV1 = true;
5198     else
5199       SeenV2 = true;
5200
5201     // Only accept consecutive elements from the same vector
5202     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5203       return false;
5204   }
5205
5206   OpNum = SeenV1 ? 0 : 1;
5207   return true;
5208 }
5209
5210 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5211 /// logical left shift of a vector.
5212 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5213                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5214   unsigned NumElems =
5215     SVOp->getSimpleValueType(0).getVectorNumElements();
5216   unsigned NumZeros = getNumOfConsecutiveZeros(
5217       SVOp, NumElems, false /* check zeros from right */, DAG,
5218       SVOp->getMaskElt(0));
5219   unsigned OpSrc;
5220
5221   if (!NumZeros)
5222     return false;
5223
5224   // Considering the elements in the mask that are not consecutive zeros,
5225   // check if they consecutively come from only one of the source vectors.
5226   //
5227   //               V1 = {X, A, B, C}     0
5228   //                         \  \  \    /
5229   //   vector_shuffle V1, V2 <1, 2, 3, X>
5230   //
5231   if (!isShuffleMaskConsecutive(SVOp,
5232             0,                   // Mask Start Index
5233             NumElems-NumZeros,   // Mask End Index(exclusive)
5234             NumZeros,            // Where to start looking in the src vector
5235             NumElems,            // Number of elements in vector
5236             OpSrc))              // Which source operand ?
5237     return false;
5238
5239   isLeft = false;
5240   ShAmt = NumZeros;
5241   ShVal = SVOp->getOperand(OpSrc);
5242   return true;
5243 }
5244
5245 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5246 /// logical left shift of a vector.
5247 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5248                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5249   unsigned NumElems =
5250     SVOp->getSimpleValueType(0).getVectorNumElements();
5251   unsigned NumZeros = getNumOfConsecutiveZeros(
5252       SVOp, NumElems, true /* check zeros from left */, DAG,
5253       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5254   unsigned OpSrc;
5255
5256   if (!NumZeros)
5257     return false;
5258
5259   // Considering the elements in the mask that are not consecutive zeros,
5260   // check if they consecutively come from only one of the source vectors.
5261   //
5262   //                           0    { A, B, X, X } = V2
5263   //                          / \    /  /
5264   //   vector_shuffle V1, V2 <X, X, 4, 5>
5265   //
5266   if (!isShuffleMaskConsecutive(SVOp,
5267             NumZeros,     // Mask Start Index
5268             NumElems,     // Mask End Index(exclusive)
5269             0,            // Where to start looking in the src vector
5270             NumElems,     // Number of elements in vector
5271             OpSrc))       // Which source operand ?
5272     return false;
5273
5274   isLeft = true;
5275   ShAmt = NumZeros;
5276   ShVal = SVOp->getOperand(OpSrc);
5277   return true;
5278 }
5279
5280 /// isVectorShift - Returns true if the shuffle can be implemented as a
5281 /// logical left or right shift of a vector.
5282 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5283                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5284   // Although the logic below support any bitwidth size, there are no
5285   // shift instructions which handle more than 128-bit vectors.
5286   if (!SVOp->getSimpleValueType(0).is128BitVector())
5287     return false;
5288
5289   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5290       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5291     return true;
5292
5293   return false;
5294 }
5295
5296 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5297 ///
5298 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5299                                        unsigned NumNonZero, unsigned NumZero,
5300                                        SelectionDAG &DAG,
5301                                        const X86Subtarget* Subtarget,
5302                                        const TargetLowering &TLI) {
5303   if (NumNonZero > 8)
5304     return SDValue();
5305
5306   SDLoc dl(Op);
5307   SDValue V(0, 0);
5308   bool First = true;
5309   for (unsigned i = 0; i < 16; ++i) {
5310     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5311     if (ThisIsNonZero && First) {
5312       if (NumZero)
5313         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5314       else
5315         V = DAG.getUNDEF(MVT::v8i16);
5316       First = false;
5317     }
5318
5319     if ((i & 1) != 0) {
5320       SDValue ThisElt(0, 0), LastElt(0, 0);
5321       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5322       if (LastIsNonZero) {
5323         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5324                               MVT::i16, Op.getOperand(i-1));
5325       }
5326       if (ThisIsNonZero) {
5327         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5328         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5329                               ThisElt, DAG.getConstant(8, MVT::i8));
5330         if (LastIsNonZero)
5331           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5332       } else
5333         ThisElt = LastElt;
5334
5335       if (ThisElt.getNode())
5336         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5337                         DAG.getIntPtrConstant(i/2));
5338     }
5339   }
5340
5341   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5342 }
5343
5344 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5345 ///
5346 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5347                                      unsigned NumNonZero, unsigned NumZero,
5348                                      SelectionDAG &DAG,
5349                                      const X86Subtarget* Subtarget,
5350                                      const TargetLowering &TLI) {
5351   if (NumNonZero > 4)
5352     return SDValue();
5353
5354   SDLoc dl(Op);
5355   SDValue V(0, 0);
5356   bool First = true;
5357   for (unsigned i = 0; i < 8; ++i) {
5358     bool isNonZero = (NonZeros & (1 << i)) != 0;
5359     if (isNonZero) {
5360       if (First) {
5361         if (NumZero)
5362           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5363         else
5364           V = DAG.getUNDEF(MVT::v8i16);
5365         First = false;
5366       }
5367       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5368                       MVT::v8i16, V, Op.getOperand(i),
5369                       DAG.getIntPtrConstant(i));
5370     }
5371   }
5372
5373   return V;
5374 }
5375
5376 /// getVShift - Return a vector logical shift node.
5377 ///
5378 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5379                          unsigned NumBits, SelectionDAG &DAG,
5380                          const TargetLowering &TLI, SDLoc dl) {
5381   assert(VT.is128BitVector() && "Unknown type for VShift");
5382   EVT ShVT = MVT::v2i64;
5383   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5384   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5385   return DAG.getNode(ISD::BITCAST, dl, VT,
5386                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5387                              DAG.getConstant(NumBits,
5388                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5389 }
5390
5391 static SDValue
5392 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5393
5394   // Check if the scalar load can be widened into a vector load. And if
5395   // the address is "base + cst" see if the cst can be "absorbed" into
5396   // the shuffle mask.
5397   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5398     SDValue Ptr = LD->getBasePtr();
5399     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5400       return SDValue();
5401     EVT PVT = LD->getValueType(0);
5402     if (PVT != MVT::i32 && PVT != MVT::f32)
5403       return SDValue();
5404
5405     int FI = -1;
5406     int64_t Offset = 0;
5407     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5408       FI = FINode->getIndex();
5409       Offset = 0;
5410     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5411                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5412       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5413       Offset = Ptr.getConstantOperandVal(1);
5414       Ptr = Ptr.getOperand(0);
5415     } else {
5416       return SDValue();
5417     }
5418
5419     // FIXME: 256-bit vector instructions don't require a strict alignment,
5420     // improve this code to support it better.
5421     unsigned RequiredAlign = VT.getSizeInBits()/8;
5422     SDValue Chain = LD->getChain();
5423     // Make sure the stack object alignment is at least 16 or 32.
5424     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5425     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5426       if (MFI->isFixedObjectIndex(FI)) {
5427         // Can't change the alignment. FIXME: It's possible to compute
5428         // the exact stack offset and reference FI + adjust offset instead.
5429         // If someone *really* cares about this. That's the way to implement it.
5430         return SDValue();
5431       } else {
5432         MFI->setObjectAlignment(FI, RequiredAlign);
5433       }
5434     }
5435
5436     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5437     // Ptr + (Offset & ~15).
5438     if (Offset < 0)
5439       return SDValue();
5440     if ((Offset % RequiredAlign) & 3)
5441       return SDValue();
5442     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5443     if (StartOffset)
5444       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5445                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5446
5447     int EltNo = (Offset - StartOffset) >> 2;
5448     unsigned NumElems = VT.getVectorNumElements();
5449
5450     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5451     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5452                              LD->getPointerInfo().getWithOffset(StartOffset),
5453                              false, false, false, 0);
5454
5455     SmallVector<int, 8> Mask;
5456     for (unsigned i = 0; i != NumElems; ++i)
5457       Mask.push_back(EltNo);
5458
5459     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5460   }
5461
5462   return SDValue();
5463 }
5464
5465 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5466 /// vector of type 'VT', see if the elements can be replaced by a single large
5467 /// load which has the same value as a build_vector whose operands are 'elts'.
5468 ///
5469 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5470 ///
5471 /// FIXME: we'd also like to handle the case where the last elements are zero
5472 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5473 /// There's even a handy isZeroNode for that purpose.
5474 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5475                                         SDLoc &DL, SelectionDAG &DAG,
5476                                         bool isAfterLegalize) {
5477   EVT EltVT = VT.getVectorElementType();
5478   unsigned NumElems = Elts.size();
5479
5480   LoadSDNode *LDBase = NULL;
5481   unsigned LastLoadedElt = -1U;
5482
5483   // For each element in the initializer, see if we've found a load or an undef.
5484   // If we don't find an initial load element, or later load elements are
5485   // non-consecutive, bail out.
5486   for (unsigned i = 0; i < NumElems; ++i) {
5487     SDValue Elt = Elts[i];
5488
5489     if (!Elt.getNode() ||
5490         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5491       return SDValue();
5492     if (!LDBase) {
5493       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5494         return SDValue();
5495       LDBase = cast<LoadSDNode>(Elt.getNode());
5496       LastLoadedElt = i;
5497       continue;
5498     }
5499     if (Elt.getOpcode() == ISD::UNDEF)
5500       continue;
5501
5502     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5503     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5504       return SDValue();
5505     LastLoadedElt = i;
5506   }
5507
5508   // If we have found an entire vector of loads and undefs, then return a large
5509   // load of the entire vector width starting at the base pointer.  If we found
5510   // consecutive loads for the low half, generate a vzext_load node.
5511   if (LastLoadedElt == NumElems - 1) {
5512
5513     if (isAfterLegalize &&
5514         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5515       return SDValue();
5516
5517     SDValue NewLd = SDValue();
5518
5519     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5520       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5521                           LDBase->getPointerInfo(),
5522                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5523                           LDBase->isInvariant(), 0);
5524     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5525                         LDBase->getPointerInfo(),
5526                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5527                         LDBase->isInvariant(), LDBase->getAlignment());
5528
5529     if (LDBase->hasAnyUseOfValue(1)) {
5530       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5531                                      SDValue(LDBase, 1),
5532                                      SDValue(NewLd.getNode(), 1));
5533       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5534       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5535                              SDValue(NewLd.getNode(), 1));
5536     }
5537
5538     return NewLd;
5539   }
5540   if (NumElems == 4 && LastLoadedElt == 1 &&
5541       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5542     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5543     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5544     SDValue ResNode =
5545         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5546                                 array_lengthof(Ops), MVT::i64,
5547                                 LDBase->getPointerInfo(),
5548                                 LDBase->getAlignment(),
5549                                 false/*isVolatile*/, true/*ReadMem*/,
5550                                 false/*WriteMem*/);
5551
5552     // Make sure the newly-created LOAD is in the same position as LDBase in
5553     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5554     // update uses of LDBase's output chain to use the TokenFactor.
5555     if (LDBase->hasAnyUseOfValue(1)) {
5556       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5557                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5558       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5559       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5560                              SDValue(ResNode.getNode(), 1));
5561     }
5562
5563     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5564   }
5565   return SDValue();
5566 }
5567
5568 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5569 /// to generate a splat value for the following cases:
5570 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5571 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5572 /// a scalar load, or a constant.
5573 /// The VBROADCAST node is returned when a pattern is found,
5574 /// or SDValue() otherwise.
5575 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5576                                     SelectionDAG &DAG) {
5577   if (!Subtarget->hasFp256())
5578     return SDValue();
5579
5580   MVT VT = Op.getSimpleValueType();
5581   SDLoc dl(Op);
5582
5583   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5584          "Unsupported vector type for broadcast.");
5585
5586   SDValue Ld;
5587   bool ConstSplatVal;
5588
5589   switch (Op.getOpcode()) {
5590     default:
5591       // Unknown pattern found.
5592       return SDValue();
5593
5594     case ISD::BUILD_VECTOR: {
5595       // The BUILD_VECTOR node must be a splat.
5596       if (!isSplatVector(Op.getNode()))
5597         return SDValue();
5598
5599       Ld = Op.getOperand(0);
5600       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5601                      Ld.getOpcode() == ISD::ConstantFP);
5602
5603       // The suspected load node has several users. Make sure that all
5604       // of its users are from the BUILD_VECTOR node.
5605       // Constants may have multiple users.
5606       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5607         return SDValue();
5608       break;
5609     }
5610
5611     case ISD::VECTOR_SHUFFLE: {
5612       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5613
5614       // Shuffles must have a splat mask where the first element is
5615       // broadcasted.
5616       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5617         return SDValue();
5618
5619       SDValue Sc = Op.getOperand(0);
5620       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5621           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5622
5623         if (!Subtarget->hasInt256())
5624           return SDValue();
5625
5626         // Use the register form of the broadcast instruction available on AVX2.
5627         if (VT.getSizeInBits() >= 256)
5628           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5629         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5630       }
5631
5632       Ld = Sc.getOperand(0);
5633       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5634                        Ld.getOpcode() == ISD::ConstantFP);
5635
5636       // The scalar_to_vector node and the suspected
5637       // load node must have exactly one user.
5638       // Constants may have multiple users.
5639
5640       // AVX-512 has register version of the broadcast
5641       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5642         Ld.getValueType().getSizeInBits() >= 32;
5643       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5644           !hasRegVer))
5645         return SDValue();
5646       break;
5647     }
5648   }
5649
5650   bool IsGE256 = (VT.getSizeInBits() >= 256);
5651
5652   // Handle the broadcasting a single constant scalar from the constant pool
5653   // into a vector. On Sandybridge it is still better to load a constant vector
5654   // from the constant pool and not to broadcast it from a scalar.
5655   if (ConstSplatVal && Subtarget->hasInt256()) {
5656     EVT CVT = Ld.getValueType();
5657     assert(!CVT.isVector() && "Must not broadcast a vector type");
5658     unsigned ScalarSize = CVT.getSizeInBits();
5659
5660     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5661       const Constant *C = 0;
5662       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5663         C = CI->getConstantIntValue();
5664       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5665         C = CF->getConstantFPValue();
5666
5667       assert(C && "Invalid constant type");
5668
5669       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5670       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5671       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5672       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5673                        MachinePointerInfo::getConstantPool(),
5674                        false, false, false, Alignment);
5675
5676       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5677     }
5678   }
5679
5680   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5681   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5682
5683   // Handle AVX2 in-register broadcasts.
5684   if (!IsLoad && Subtarget->hasInt256() &&
5685       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5686     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5687
5688   // The scalar source must be a normal load.
5689   if (!IsLoad)
5690     return SDValue();
5691
5692   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5693     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5694
5695   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5696   // double since there is no vbroadcastsd xmm
5697   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5698     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5699       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5700   }
5701
5702   // Unsupported broadcast.
5703   return SDValue();
5704 }
5705
5706 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5707   MVT VT = Op.getSimpleValueType();
5708
5709   // Skip if insert_vec_elt is not supported.
5710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5711   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5712     return SDValue();
5713
5714   SDLoc DL(Op);
5715   unsigned NumElems = Op.getNumOperands();
5716
5717   SDValue VecIn1;
5718   SDValue VecIn2;
5719   SmallVector<unsigned, 4> InsertIndices;
5720   SmallVector<int, 8> Mask(NumElems, -1);
5721
5722   for (unsigned i = 0; i != NumElems; ++i) {
5723     unsigned Opc = Op.getOperand(i).getOpcode();
5724
5725     if (Opc == ISD::UNDEF)
5726       continue;
5727
5728     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5729       // Quit if more than 1 elements need inserting.
5730       if (InsertIndices.size() > 1)
5731         return SDValue();
5732
5733       InsertIndices.push_back(i);
5734       continue;
5735     }
5736
5737     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5738     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5739
5740     // Quit if extracted from vector of different type.
5741     if (ExtractedFromVec.getValueType() != VT)
5742       return SDValue();
5743
5744     // Quit if non-constant index.
5745     if (!isa<ConstantSDNode>(ExtIdx))
5746       return SDValue();
5747
5748     if (VecIn1.getNode() == 0)
5749       VecIn1 = ExtractedFromVec;
5750     else if (VecIn1 != ExtractedFromVec) {
5751       if (VecIn2.getNode() == 0)
5752         VecIn2 = ExtractedFromVec;
5753       else if (VecIn2 != ExtractedFromVec)
5754         // Quit if more than 2 vectors to shuffle
5755         return SDValue();
5756     }
5757
5758     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5759
5760     if (ExtractedFromVec == VecIn1)
5761       Mask[i] = Idx;
5762     else if (ExtractedFromVec == VecIn2)
5763       Mask[i] = Idx + NumElems;
5764   }
5765
5766   if (VecIn1.getNode() == 0)
5767     return SDValue();
5768
5769   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5770   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5771   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5772     unsigned Idx = InsertIndices[i];
5773     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5774                      DAG.getIntPtrConstant(Idx));
5775   }
5776
5777   return NV;
5778 }
5779
5780 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5781 SDValue
5782 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5783
5784   MVT VT = Op.getSimpleValueType();
5785   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5786          "Unexpected type in LowerBUILD_VECTORvXi1!");
5787
5788   SDLoc dl(Op);
5789   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5790     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5791     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5792                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5793     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5794                        Ops, VT.getVectorNumElements());
5795   }
5796
5797   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5798     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5799     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5800                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5801     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5802                        Ops, VT.getVectorNumElements());
5803   }
5804
5805   bool AllContants = true;
5806   uint64_t Immediate = 0;
5807   int NonConstIdx = -1;
5808   bool IsSplat = true;
5809   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5810     SDValue In = Op.getOperand(idx);
5811     if (In.getOpcode() == ISD::UNDEF)
5812       continue;
5813     if (!isa<ConstantSDNode>(In)) {
5814       AllContants = false;
5815       NonConstIdx = idx;
5816     }
5817     else if (cast<ConstantSDNode>(In)->getZExtValue())
5818       Immediate |= (1ULL << idx);
5819     if (In != Op.getOperand(0))
5820       IsSplat = false;
5821   }
5822
5823   if (AllContants) {
5824     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5825       DAG.getConstant(Immediate, MVT::i16));
5826     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5827                        DAG.getIntPtrConstant(0));
5828   }
5829
5830   if (!IsSplat && (NonConstIdx != 0))
5831     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5832   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5833   SDValue Select;
5834   if (IsSplat)
5835     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5836                           DAG.getConstant(-1, SelectVT),
5837                           DAG.getConstant(0, SelectVT));
5838   else
5839     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5840                          DAG.getConstant((Immediate | 1), SelectVT),
5841                          DAG.getConstant(Immediate, SelectVT));
5842   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5843 }
5844
5845 SDValue
5846 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5847   SDLoc dl(Op);
5848
5849   MVT VT = Op.getSimpleValueType();
5850   MVT ExtVT = VT.getVectorElementType();
5851   unsigned NumElems = Op.getNumOperands();
5852
5853   // Generate vectors for predicate vectors.
5854   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5855     return LowerBUILD_VECTORvXi1(Op, DAG);
5856
5857   // Vectors containing all zeros can be matched by pxor and xorps later
5858   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5859     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5860     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5861     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5862       return Op;
5863
5864     return getZeroVector(VT, Subtarget, DAG, dl);
5865   }
5866
5867   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5868   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5869   // vpcmpeqd on 256-bit vectors.
5870   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5871     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5872       return Op;
5873
5874     if (!VT.is512BitVector())
5875       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5876   }
5877
5878   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5879   if (Broadcast.getNode())
5880     return Broadcast;
5881
5882   unsigned EVTBits = ExtVT.getSizeInBits();
5883
5884   unsigned NumZero  = 0;
5885   unsigned NumNonZero = 0;
5886   unsigned NonZeros = 0;
5887   bool IsAllConstants = true;
5888   SmallSet<SDValue, 8> Values;
5889   for (unsigned i = 0; i < NumElems; ++i) {
5890     SDValue Elt = Op.getOperand(i);
5891     if (Elt.getOpcode() == ISD::UNDEF)
5892       continue;
5893     Values.insert(Elt);
5894     if (Elt.getOpcode() != ISD::Constant &&
5895         Elt.getOpcode() != ISD::ConstantFP)
5896       IsAllConstants = false;
5897     if (X86::isZeroNode(Elt))
5898       NumZero++;
5899     else {
5900       NonZeros |= (1 << i);
5901       NumNonZero++;
5902     }
5903   }
5904
5905   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5906   if (NumNonZero == 0)
5907     return DAG.getUNDEF(VT);
5908
5909   // Special case for single non-zero, non-undef, element.
5910   if (NumNonZero == 1) {
5911     unsigned Idx = countTrailingZeros(NonZeros);
5912     SDValue Item = Op.getOperand(Idx);
5913
5914     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5915     // the value are obviously zero, truncate the value to i32 and do the
5916     // insertion that way.  Only do this if the value is non-constant or if the
5917     // value is a constant being inserted into element 0.  It is cheaper to do
5918     // a constant pool load than it is to do a movd + shuffle.
5919     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5920         (!IsAllConstants || Idx == 0)) {
5921       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5922         // Handle SSE only.
5923         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5924         EVT VecVT = MVT::v4i32;
5925         unsigned VecElts = 4;
5926
5927         // Truncate the value (which may itself be a constant) to i32, and
5928         // convert it to a vector with movd (S2V+shuffle to zero extend).
5929         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5930         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5931         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5932
5933         // Now we have our 32-bit value zero extended in the low element of
5934         // a vector.  If Idx != 0, swizzle it into place.
5935         if (Idx != 0) {
5936           SmallVector<int, 4> Mask;
5937           Mask.push_back(Idx);
5938           for (unsigned i = 1; i != VecElts; ++i)
5939             Mask.push_back(i);
5940           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5941                                       &Mask[0]);
5942         }
5943         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5944       }
5945     }
5946
5947     // If we have a constant or non-constant insertion into the low element of
5948     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5949     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5950     // depending on what the source datatype is.
5951     if (Idx == 0) {
5952       if (NumZero == 0)
5953         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5954
5955       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5956           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5957         if (VT.is256BitVector() || VT.is512BitVector()) {
5958           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5959           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5960                              Item, DAG.getIntPtrConstant(0));
5961         }
5962         assert(VT.is128BitVector() && "Expected an SSE value type!");
5963         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5964         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5965         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5966       }
5967
5968       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5969         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5970         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5971         if (VT.is256BitVector()) {
5972           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5973           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5974         } else {
5975           assert(VT.is128BitVector() && "Expected an SSE value type!");
5976           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5977         }
5978         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5979       }
5980     }
5981
5982     // Is it a vector logical left shift?
5983     if (NumElems == 2 && Idx == 1 &&
5984         X86::isZeroNode(Op.getOperand(0)) &&
5985         !X86::isZeroNode(Op.getOperand(1))) {
5986       unsigned NumBits = VT.getSizeInBits();
5987       return getVShift(true, VT,
5988                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5989                                    VT, Op.getOperand(1)),
5990                        NumBits/2, DAG, *this, dl);
5991     }
5992
5993     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5994       return SDValue();
5995
5996     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5997     // is a non-constant being inserted into an element other than the low one,
5998     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5999     // movd/movss) to move this into the low element, then shuffle it into
6000     // place.
6001     if (EVTBits == 32) {
6002       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6003
6004       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6005       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6006       SmallVector<int, 8> MaskVec;
6007       for (unsigned i = 0; i != NumElems; ++i)
6008         MaskVec.push_back(i == Idx ? 0 : 1);
6009       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6010     }
6011   }
6012
6013   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6014   if (Values.size() == 1) {
6015     if (EVTBits == 32) {
6016       // Instead of a shuffle like this:
6017       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6018       // Check if it's possible to issue this instead.
6019       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6020       unsigned Idx = countTrailingZeros(NonZeros);
6021       SDValue Item = Op.getOperand(Idx);
6022       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6023         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6024     }
6025     return SDValue();
6026   }
6027
6028   // A vector full of immediates; various special cases are already
6029   // handled, so this is best done with a single constant-pool load.
6030   if (IsAllConstants)
6031     return SDValue();
6032
6033   // For AVX-length vectors, build the individual 128-bit pieces and use
6034   // shuffles to put them in place.
6035   if (VT.is256BitVector() || VT.is512BitVector()) {
6036     SmallVector<SDValue, 64> V;
6037     for (unsigned i = 0; i != NumElems; ++i)
6038       V.push_back(Op.getOperand(i));
6039
6040     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6041
6042     // Build both the lower and upper subvector.
6043     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6044     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6045                                 NumElems/2);
6046
6047     // Recreate the wider vector with the lower and upper part.
6048     if (VT.is256BitVector())
6049       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6050     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6051   }
6052
6053   // Let legalizer expand 2-wide build_vectors.
6054   if (EVTBits == 64) {
6055     if (NumNonZero == 1) {
6056       // One half is zero or undef.
6057       unsigned Idx = countTrailingZeros(NonZeros);
6058       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6059                                  Op.getOperand(Idx));
6060       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6061     }
6062     return SDValue();
6063   }
6064
6065   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6066   if (EVTBits == 8 && NumElems == 16) {
6067     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6068                                         Subtarget, *this);
6069     if (V.getNode()) return V;
6070   }
6071
6072   if (EVTBits == 16 && NumElems == 8) {
6073     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6074                                       Subtarget, *this);
6075     if (V.getNode()) return V;
6076   }
6077
6078   // If element VT is == 32 bits, turn it into a number of shuffles.
6079   SmallVector<SDValue, 8> V(NumElems);
6080   if (NumElems == 4 && NumZero > 0) {
6081     for (unsigned i = 0; i < 4; ++i) {
6082       bool isZero = !(NonZeros & (1 << i));
6083       if (isZero)
6084         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6085       else
6086         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6087     }
6088
6089     for (unsigned i = 0; i < 2; ++i) {
6090       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6091         default: break;
6092         case 0:
6093           V[i] = V[i*2];  // Must be a zero vector.
6094           break;
6095         case 1:
6096           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6097           break;
6098         case 2:
6099           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6100           break;
6101         case 3:
6102           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6103           break;
6104       }
6105     }
6106
6107     bool Reverse1 = (NonZeros & 0x3) == 2;
6108     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6109     int MaskVec[] = {
6110       Reverse1 ? 1 : 0,
6111       Reverse1 ? 0 : 1,
6112       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6113       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6114     };
6115     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6116   }
6117
6118   if (Values.size() > 1 && VT.is128BitVector()) {
6119     // Check for a build vector of consecutive loads.
6120     for (unsigned i = 0; i < NumElems; ++i)
6121       V[i] = Op.getOperand(i);
6122
6123     // Check for elements which are consecutive loads.
6124     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6125     if (LD.getNode())
6126       return LD;
6127
6128     // Check for a build vector from mostly shuffle plus few inserting.
6129     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6130     if (Sh.getNode())
6131       return Sh;
6132
6133     // For SSE 4.1, use insertps to put the high elements into the low element.
6134     if (getSubtarget()->hasSSE41()) {
6135       SDValue Result;
6136       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6137         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6138       else
6139         Result = DAG.getUNDEF(VT);
6140
6141       for (unsigned i = 1; i < NumElems; ++i) {
6142         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6143         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6144                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6145       }
6146       return Result;
6147     }
6148
6149     // Otherwise, expand into a number of unpckl*, start by extending each of
6150     // our (non-undef) elements to the full vector width with the element in the
6151     // bottom slot of the vector (which generates no code for SSE).
6152     for (unsigned i = 0; i < NumElems; ++i) {
6153       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6154         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6155       else
6156         V[i] = DAG.getUNDEF(VT);
6157     }
6158
6159     // Next, we iteratively mix elements, e.g. for v4f32:
6160     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6161     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6162     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6163     unsigned EltStride = NumElems >> 1;
6164     while (EltStride != 0) {
6165       for (unsigned i = 0; i < EltStride; ++i) {
6166         // If V[i+EltStride] is undef and this is the first round of mixing,
6167         // then it is safe to just drop this shuffle: V[i] is already in the
6168         // right place, the one element (since it's the first round) being
6169         // inserted as undef can be dropped.  This isn't safe for successive
6170         // rounds because they will permute elements within both vectors.
6171         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6172             EltStride == NumElems/2)
6173           continue;
6174
6175         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6176       }
6177       EltStride >>= 1;
6178     }
6179     return V[0];
6180   }
6181   return SDValue();
6182 }
6183
6184 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6185 // to create 256-bit vectors from two other 128-bit ones.
6186 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6187   SDLoc dl(Op);
6188   MVT ResVT = Op.getSimpleValueType();
6189
6190   assert((ResVT.is256BitVector() ||
6191           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6192
6193   SDValue V1 = Op.getOperand(0);
6194   SDValue V2 = Op.getOperand(1);
6195   unsigned NumElems = ResVT.getVectorNumElements();
6196   if(ResVT.is256BitVector())
6197     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6198
6199   if (Op.getNumOperands() == 4) {
6200     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6201                                 ResVT.getVectorNumElements()/2);
6202     SDValue V3 = Op.getOperand(2);
6203     SDValue V4 = Op.getOperand(3);
6204     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6205       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6206   }
6207   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6208 }
6209
6210 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6211   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6212   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6213          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6214           Op.getNumOperands() == 4)));
6215
6216   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6217   // from two other 128-bit ones.
6218
6219   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6220   return LowerAVXCONCAT_VECTORS(Op, DAG);
6221 }
6222
6223 // Try to lower a shuffle node into a simple blend instruction.
6224 static SDValue
6225 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6226                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6227   SDValue V1 = SVOp->getOperand(0);
6228   SDValue V2 = SVOp->getOperand(1);
6229   SDLoc dl(SVOp);
6230   MVT VT = SVOp->getSimpleValueType(0);
6231   MVT EltVT = VT.getVectorElementType();
6232   unsigned NumElems = VT.getVectorNumElements();
6233
6234   // There is no blend with immediate in AVX-512.
6235   if (VT.is512BitVector())
6236     return SDValue();
6237
6238   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6239     return SDValue();
6240   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6241     return SDValue();
6242
6243   // Check the mask for BLEND and build the value.
6244   unsigned MaskValue = 0;
6245   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6246   unsigned NumLanes = (NumElems-1)/8 + 1;
6247   unsigned NumElemsInLane = NumElems / NumLanes;
6248
6249   // Blend for v16i16 should be symetric for the both lanes.
6250   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6251
6252     int SndLaneEltIdx = (NumLanes == 2) ?
6253       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6254     int EltIdx = SVOp->getMaskElt(i);
6255
6256     if ((EltIdx < 0 || EltIdx == (int)i) &&
6257         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6258       continue;
6259
6260     if (((unsigned)EltIdx == (i + NumElems)) &&
6261         (SndLaneEltIdx < 0 ||
6262          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6263       MaskValue |= (1<<i);
6264     else
6265       return SDValue();
6266   }
6267
6268   // Convert i32 vectors to floating point if it is not AVX2.
6269   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6270   MVT BlendVT = VT;
6271   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6272     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6273                                NumElems);
6274     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6275     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6276   }
6277
6278   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6279                             DAG.getConstant(MaskValue, MVT::i32));
6280   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6281 }
6282
6283 // v8i16 shuffles - Prefer shuffles in the following order:
6284 // 1. [all]   pshuflw, pshufhw, optional move
6285 // 2. [ssse3] 1 x pshufb
6286 // 3. [ssse3] 2 x pshufb + 1 x por
6287 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6288 static SDValue
6289 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6290                          SelectionDAG &DAG) {
6291   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6292   SDValue V1 = SVOp->getOperand(0);
6293   SDValue V2 = SVOp->getOperand(1);
6294   SDLoc dl(SVOp);
6295   SmallVector<int, 8> MaskVals;
6296
6297   // Determine if more than 1 of the words in each of the low and high quadwords
6298   // of the result come from the same quadword of one of the two inputs.  Undef
6299   // mask values count as coming from any quadword, for better codegen.
6300   unsigned LoQuad[] = { 0, 0, 0, 0 };
6301   unsigned HiQuad[] = { 0, 0, 0, 0 };
6302   std::bitset<4> InputQuads;
6303   for (unsigned i = 0; i < 8; ++i) {
6304     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6305     int EltIdx = SVOp->getMaskElt(i);
6306     MaskVals.push_back(EltIdx);
6307     if (EltIdx < 0) {
6308       ++Quad[0];
6309       ++Quad[1];
6310       ++Quad[2];
6311       ++Quad[3];
6312       continue;
6313     }
6314     ++Quad[EltIdx / 4];
6315     InputQuads.set(EltIdx / 4);
6316   }
6317
6318   int BestLoQuad = -1;
6319   unsigned MaxQuad = 1;
6320   for (unsigned i = 0; i < 4; ++i) {
6321     if (LoQuad[i] > MaxQuad) {
6322       BestLoQuad = i;
6323       MaxQuad = LoQuad[i];
6324     }
6325   }
6326
6327   int BestHiQuad = -1;
6328   MaxQuad = 1;
6329   for (unsigned i = 0; i < 4; ++i) {
6330     if (HiQuad[i] > MaxQuad) {
6331       BestHiQuad = i;
6332       MaxQuad = HiQuad[i];
6333     }
6334   }
6335
6336   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6337   // of the two input vectors, shuffle them into one input vector so only a
6338   // single pshufb instruction is necessary. If There are more than 2 input
6339   // quads, disable the next transformation since it does not help SSSE3.
6340   bool V1Used = InputQuads[0] || InputQuads[1];
6341   bool V2Used = InputQuads[2] || InputQuads[3];
6342   if (Subtarget->hasSSSE3()) {
6343     if (InputQuads.count() == 2 && V1Used && V2Used) {
6344       BestLoQuad = InputQuads[0] ? 0 : 1;
6345       BestHiQuad = InputQuads[2] ? 2 : 3;
6346     }
6347     if (InputQuads.count() > 2) {
6348       BestLoQuad = -1;
6349       BestHiQuad = -1;
6350     }
6351   }
6352
6353   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6354   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6355   // words from all 4 input quadwords.
6356   SDValue NewV;
6357   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6358     int MaskV[] = {
6359       BestLoQuad < 0 ? 0 : BestLoQuad,
6360       BestHiQuad < 0 ? 1 : BestHiQuad
6361     };
6362     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6363                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6364                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6365     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6366
6367     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6368     // source words for the shuffle, to aid later transformations.
6369     bool AllWordsInNewV = true;
6370     bool InOrder[2] = { true, true };
6371     for (unsigned i = 0; i != 8; ++i) {
6372       int idx = MaskVals[i];
6373       if (idx != (int)i)
6374         InOrder[i/4] = false;
6375       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6376         continue;
6377       AllWordsInNewV = false;
6378       break;
6379     }
6380
6381     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6382     if (AllWordsInNewV) {
6383       for (int i = 0; i != 8; ++i) {
6384         int idx = MaskVals[i];
6385         if (idx < 0)
6386           continue;
6387         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6388         if ((idx != i) && idx < 4)
6389           pshufhw = false;
6390         if ((idx != i) && idx > 3)
6391           pshuflw = false;
6392       }
6393       V1 = NewV;
6394       V2Used = false;
6395       BestLoQuad = 0;
6396       BestHiQuad = 1;
6397     }
6398
6399     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6400     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6401     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6402       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6403       unsigned TargetMask = 0;
6404       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6405                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6406       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6407       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6408                              getShufflePSHUFLWImmediate(SVOp);
6409       V1 = NewV.getOperand(0);
6410       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6411     }
6412   }
6413
6414   // Promote splats to a larger type which usually leads to more efficient code.
6415   // FIXME: Is this true if pshufb is available?
6416   if (SVOp->isSplat())
6417     return PromoteSplat(SVOp, DAG);
6418
6419   // If we have SSSE3, and all words of the result are from 1 input vector,
6420   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6421   // is present, fall back to case 4.
6422   if (Subtarget->hasSSSE3()) {
6423     SmallVector<SDValue,16> pshufbMask;
6424
6425     // If we have elements from both input vectors, set the high bit of the
6426     // shuffle mask element to zero out elements that come from V2 in the V1
6427     // mask, and elements that come from V1 in the V2 mask, so that the two
6428     // results can be OR'd together.
6429     bool TwoInputs = V1Used && V2Used;
6430     for (unsigned i = 0; i != 8; ++i) {
6431       int EltIdx = MaskVals[i] * 2;
6432       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6433       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6434       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6435       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6436     }
6437     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6438     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6439                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6440                                  MVT::v16i8, &pshufbMask[0], 16));
6441     if (!TwoInputs)
6442       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6443
6444     // Calculate the shuffle mask for the second input, shuffle it, and
6445     // OR it with the first shuffled input.
6446     pshufbMask.clear();
6447     for (unsigned i = 0; i != 8; ++i) {
6448       int EltIdx = MaskVals[i] * 2;
6449       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6450       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6451       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6452       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6453     }
6454     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6455     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6456                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6457                                  MVT::v16i8, &pshufbMask[0], 16));
6458     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6459     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6460   }
6461
6462   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6463   // and update MaskVals with new element order.
6464   std::bitset<8> InOrder;
6465   if (BestLoQuad >= 0) {
6466     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6467     for (int i = 0; i != 4; ++i) {
6468       int idx = MaskVals[i];
6469       if (idx < 0) {
6470         InOrder.set(i);
6471       } else if ((idx / 4) == BestLoQuad) {
6472         MaskV[i] = idx & 3;
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::PSHUFLW, dl, MVT::v8i16,
6482                                   NewV.getOperand(0),
6483                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6484     }
6485   }
6486
6487   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6488   // and update MaskVals with the new element order.
6489   if (BestHiQuad >= 0) {
6490     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6491     for (unsigned i = 4; i != 8; ++i) {
6492       int idx = MaskVals[i];
6493       if (idx < 0) {
6494         InOrder.set(i);
6495       } else if ((idx / 4) == BestHiQuad) {
6496         MaskV[i] = (idx & 3) + 4;
6497         InOrder.set(i);
6498       }
6499     }
6500     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6501                                 &MaskV[0]);
6502
6503     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6504       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6505       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6506                                   NewV.getOperand(0),
6507                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6508     }
6509   }
6510
6511   // In case BestHi & BestLo were both -1, which means each quadword has a word
6512   // from each of the four input quadwords, calculate the InOrder bitvector now
6513   // before falling through to the insert/extract cleanup.
6514   if (BestLoQuad == -1 && BestHiQuad == -1) {
6515     NewV = V1;
6516     for (int i = 0; i != 8; ++i)
6517       if (MaskVals[i] < 0 || MaskVals[i] == i)
6518         InOrder.set(i);
6519   }
6520
6521   // The other elements are put in the right place using pextrw and pinsrw.
6522   for (unsigned i = 0; i != 8; ++i) {
6523     if (InOrder[i])
6524       continue;
6525     int EltIdx = MaskVals[i];
6526     if (EltIdx < 0)
6527       continue;
6528     SDValue ExtOp = (EltIdx < 8) ?
6529       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6530                   DAG.getIntPtrConstant(EltIdx)) :
6531       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6532                   DAG.getIntPtrConstant(EltIdx - 8));
6533     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6534                        DAG.getIntPtrConstant(i));
6535   }
6536   return NewV;
6537 }
6538
6539 // v16i8 shuffles - Prefer shuffles in the following order:
6540 // 1. [ssse3] 1 x pshufb
6541 // 2. [ssse3] 2 x pshufb + 1 x por
6542 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6543 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6544                                         const X86Subtarget* Subtarget,
6545                                         SelectionDAG &DAG) {
6546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6547   SDValue V1 = SVOp->getOperand(0);
6548   SDValue V2 = SVOp->getOperand(1);
6549   SDLoc dl(SVOp);
6550   ArrayRef<int> MaskVals = SVOp->getMask();
6551
6552   // Promote splats to a larger type which usually leads to more efficient code.
6553   // FIXME: Is this true if pshufb is available?
6554   if (SVOp->isSplat())
6555     return PromoteSplat(SVOp, DAG);
6556
6557   // If we have SSSE3, case 1 is generated when all result bytes come from
6558   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6559   // present, fall back to case 3.
6560
6561   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6562   if (Subtarget->hasSSSE3()) {
6563     SmallVector<SDValue,16> pshufbMask;
6564
6565     // If all result elements are from one input vector, then only translate
6566     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6567     //
6568     // Otherwise, we have elements from both input vectors, and must zero out
6569     // elements that come from V2 in the first mask, and V1 in the second mask
6570     // so that we can OR them together.
6571     for (unsigned i = 0; i != 16; ++i) {
6572       int EltIdx = MaskVals[i];
6573       if (EltIdx < 0 || EltIdx >= 16)
6574         EltIdx = 0x80;
6575       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6576     }
6577     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6578                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6579                                  MVT::v16i8, &pshufbMask[0], 16));
6580
6581     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6582     // the 2nd operand if it's undefined or zero.
6583     if (V2.getOpcode() == ISD::UNDEF ||
6584         ISD::isBuildVectorAllZeros(V2.getNode()))
6585       return V1;
6586
6587     // Calculate the shuffle mask for the second input, shuffle it, and
6588     // OR it with the first shuffled input.
6589     pshufbMask.clear();
6590     for (unsigned i = 0; i != 16; ++i) {
6591       int EltIdx = MaskVals[i];
6592       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6593       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6594     }
6595     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6596                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6597                                  MVT::v16i8, &pshufbMask[0], 16));
6598     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6599   }
6600
6601   // No SSSE3 - Calculate in place words and then fix all out of place words
6602   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6603   // the 16 different words that comprise the two doublequadword input vectors.
6604   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6605   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6606   SDValue NewV = V1;
6607   for (int i = 0; i != 8; ++i) {
6608     int Elt0 = MaskVals[i*2];
6609     int Elt1 = MaskVals[i*2+1];
6610
6611     // This word of the result is all undef, skip it.
6612     if (Elt0 < 0 && Elt1 < 0)
6613       continue;
6614
6615     // This word of the result is already in the correct place, skip it.
6616     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6617       continue;
6618
6619     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6620     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6621     SDValue InsElt;
6622
6623     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6624     // using a single extract together, load it and store it.
6625     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6626       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6627                            DAG.getIntPtrConstant(Elt1 / 2));
6628       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6629                         DAG.getIntPtrConstant(i));
6630       continue;
6631     }
6632
6633     // If Elt1 is defined, extract it from the appropriate source.  If the
6634     // source byte is not also odd, shift the extracted word left 8 bits
6635     // otherwise clear the bottom 8 bits if we need to do an or.
6636     if (Elt1 >= 0) {
6637       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6638                            DAG.getIntPtrConstant(Elt1 / 2));
6639       if ((Elt1 & 1) == 0)
6640         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6641                              DAG.getConstant(8,
6642                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6643       else if (Elt0 >= 0)
6644         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6645                              DAG.getConstant(0xFF00, MVT::i16));
6646     }
6647     // If Elt0 is defined, extract it from the appropriate source.  If the
6648     // source byte is not also even, shift the extracted word right 8 bits. If
6649     // Elt1 was also defined, OR the extracted values together before
6650     // inserting them in the result.
6651     if (Elt0 >= 0) {
6652       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6653                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6654       if ((Elt0 & 1) != 0)
6655         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6656                               DAG.getConstant(8,
6657                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6658       else if (Elt1 >= 0)
6659         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6660                              DAG.getConstant(0x00FF, MVT::i16));
6661       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6662                          : InsElt0;
6663     }
6664     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6665                        DAG.getIntPtrConstant(i));
6666   }
6667   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6668 }
6669
6670 // v32i8 shuffles - Translate to VPSHUFB if possible.
6671 static
6672 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6673                                  const X86Subtarget *Subtarget,
6674                                  SelectionDAG &DAG) {
6675   MVT VT = SVOp->getSimpleValueType(0);
6676   SDValue V1 = SVOp->getOperand(0);
6677   SDValue V2 = SVOp->getOperand(1);
6678   SDLoc dl(SVOp);
6679   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6680
6681   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6682   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6683   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6684
6685   // VPSHUFB may be generated if
6686   // (1) one of input vector is undefined or zeroinitializer.
6687   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6688   // And (2) the mask indexes don't cross the 128-bit lane.
6689   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6690       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6691     return SDValue();
6692
6693   if (V1IsAllZero && !V2IsAllZero) {
6694     CommuteVectorShuffleMask(MaskVals, 32);
6695     V1 = V2;
6696   }
6697   SmallVector<SDValue, 32> pshufbMask;
6698   for (unsigned i = 0; i != 32; i++) {
6699     int EltIdx = MaskVals[i];
6700     if (EltIdx < 0 || EltIdx >= 32)
6701       EltIdx = 0x80;
6702     else {
6703       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6704         // Cross lane is not allowed.
6705         return SDValue();
6706       EltIdx &= 0xf;
6707     }
6708     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6709   }
6710   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6711                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6712                                   MVT::v32i8, &pshufbMask[0], 32));
6713 }
6714
6715 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6716 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6717 /// done when every pair / quad of shuffle mask elements point to elements in
6718 /// the right sequence. e.g.
6719 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6720 static
6721 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6722                                  SelectionDAG &DAG) {
6723   MVT VT = SVOp->getSimpleValueType(0);
6724   SDLoc dl(SVOp);
6725   unsigned NumElems = VT.getVectorNumElements();
6726   MVT NewVT;
6727   unsigned Scale;
6728   switch (VT.SimpleTy) {
6729   default: llvm_unreachable("Unexpected!");
6730   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6731   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6732   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6733   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6734   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6735   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6736   }
6737
6738   SmallVector<int, 8> MaskVec;
6739   for (unsigned i = 0; i != NumElems; i += Scale) {
6740     int StartIdx = -1;
6741     for (unsigned j = 0; j != Scale; ++j) {
6742       int EltIdx = SVOp->getMaskElt(i+j);
6743       if (EltIdx < 0)
6744         continue;
6745       if (StartIdx < 0)
6746         StartIdx = (EltIdx / Scale);
6747       if (EltIdx != (int)(StartIdx*Scale + j))
6748         return SDValue();
6749     }
6750     MaskVec.push_back(StartIdx);
6751   }
6752
6753   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6754   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6755   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6756 }
6757
6758 /// getVZextMovL - Return a zero-extending vector move low node.
6759 ///
6760 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6761                             SDValue SrcOp, SelectionDAG &DAG,
6762                             const X86Subtarget *Subtarget, SDLoc dl) {
6763   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6764     LoadSDNode *LD = NULL;
6765     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6766       LD = dyn_cast<LoadSDNode>(SrcOp);
6767     if (!LD) {
6768       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6769       // instead.
6770       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6771       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6772           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6773           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6774           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6775         // PR2108
6776         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6777         return DAG.getNode(ISD::BITCAST, dl, VT,
6778                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6779                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6780                                                    OpVT,
6781                                                    SrcOp.getOperand(0)
6782                                                           .getOperand(0))));
6783       }
6784     }
6785   }
6786
6787   return DAG.getNode(ISD::BITCAST, dl, VT,
6788                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6789                                  DAG.getNode(ISD::BITCAST, dl,
6790                                              OpVT, SrcOp)));
6791 }
6792
6793 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6794 /// which could not be matched by any known target speficic shuffle
6795 static SDValue
6796 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6797
6798   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6799   if (NewOp.getNode())
6800     return NewOp;
6801
6802   MVT VT = SVOp->getSimpleValueType(0);
6803
6804   unsigned NumElems = VT.getVectorNumElements();
6805   unsigned NumLaneElems = NumElems / 2;
6806
6807   SDLoc dl(SVOp);
6808   MVT EltVT = VT.getVectorElementType();
6809   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6810   SDValue Output[2];
6811
6812   SmallVector<int, 16> Mask;
6813   for (unsigned l = 0; l < 2; ++l) {
6814     // Build a shuffle mask for the output, discovering on the fly which
6815     // input vectors to use as shuffle operands (recorded in InputUsed).
6816     // If building a suitable shuffle vector proves too hard, then bail
6817     // out with UseBuildVector set.
6818     bool UseBuildVector = false;
6819     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6820     unsigned LaneStart = l * NumLaneElems;
6821     for (unsigned i = 0; i != NumLaneElems; ++i) {
6822       // The mask element.  This indexes into the input.
6823       int Idx = SVOp->getMaskElt(i+LaneStart);
6824       if (Idx < 0) {
6825         // the mask element does not index into any input vector.
6826         Mask.push_back(-1);
6827         continue;
6828       }
6829
6830       // The input vector this mask element indexes into.
6831       int Input = Idx / NumLaneElems;
6832
6833       // Turn the index into an offset from the start of the input vector.
6834       Idx -= Input * NumLaneElems;
6835
6836       // Find or create a shuffle vector operand to hold this input.
6837       unsigned OpNo;
6838       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6839         if (InputUsed[OpNo] == Input)
6840           // This input vector is already an operand.
6841           break;
6842         if (InputUsed[OpNo] < 0) {
6843           // Create a new operand for this input vector.
6844           InputUsed[OpNo] = Input;
6845           break;
6846         }
6847       }
6848
6849       if (OpNo >= array_lengthof(InputUsed)) {
6850         // More than two input vectors used!  Give up on trying to create a
6851         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6852         UseBuildVector = true;
6853         break;
6854       }
6855
6856       // Add the mask index for the new shuffle vector.
6857       Mask.push_back(Idx + OpNo * NumLaneElems);
6858     }
6859
6860     if (UseBuildVector) {
6861       SmallVector<SDValue, 16> SVOps;
6862       for (unsigned i = 0; i != NumLaneElems; ++i) {
6863         // The mask element.  This indexes into the input.
6864         int Idx = SVOp->getMaskElt(i+LaneStart);
6865         if (Idx < 0) {
6866           SVOps.push_back(DAG.getUNDEF(EltVT));
6867           continue;
6868         }
6869
6870         // The input vector this mask element indexes into.
6871         int Input = Idx / NumElems;
6872
6873         // Turn the index into an offset from the start of the input vector.
6874         Idx -= Input * NumElems;
6875
6876         // Extract the vector element by hand.
6877         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6878                                     SVOp->getOperand(Input),
6879                                     DAG.getIntPtrConstant(Idx)));
6880       }
6881
6882       // Construct the output using a BUILD_VECTOR.
6883       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6884                               SVOps.size());
6885     } else if (InputUsed[0] < 0) {
6886       // No input vectors were used! The result is undefined.
6887       Output[l] = DAG.getUNDEF(NVT);
6888     } else {
6889       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6890                                         (InputUsed[0] % 2) * NumLaneElems,
6891                                         DAG, dl);
6892       // If only one input was used, use an undefined vector for the other.
6893       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6894         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6895                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6896       // At least one input vector was used. Create a new shuffle vector.
6897       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6898     }
6899
6900     Mask.clear();
6901   }
6902
6903   // Concatenate the result back
6904   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6905 }
6906
6907 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6908 /// 4 elements, and match them with several different shuffle types.
6909 static SDValue
6910 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6911   SDValue V1 = SVOp->getOperand(0);
6912   SDValue V2 = SVOp->getOperand(1);
6913   SDLoc dl(SVOp);
6914   MVT VT = SVOp->getSimpleValueType(0);
6915
6916   assert(VT.is128BitVector() && "Unsupported vector size");
6917
6918   std::pair<int, int> Locs[4];
6919   int Mask1[] = { -1, -1, -1, -1 };
6920   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6921
6922   unsigned NumHi = 0;
6923   unsigned NumLo = 0;
6924   for (unsigned i = 0; i != 4; ++i) {
6925     int Idx = PermMask[i];
6926     if (Idx < 0) {
6927       Locs[i] = std::make_pair(-1, -1);
6928     } else {
6929       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6930       if (Idx < 4) {
6931         Locs[i] = std::make_pair(0, NumLo);
6932         Mask1[NumLo] = Idx;
6933         NumLo++;
6934       } else {
6935         Locs[i] = std::make_pair(1, NumHi);
6936         if (2+NumHi < 4)
6937           Mask1[2+NumHi] = Idx;
6938         NumHi++;
6939       }
6940     }
6941   }
6942
6943   if (NumLo <= 2 && NumHi <= 2) {
6944     // If no more than two elements come from either vector. This can be
6945     // implemented with two shuffles. First shuffle gather the elements.
6946     // The second shuffle, which takes the first shuffle as both of its
6947     // vector operands, put the elements into the right order.
6948     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6949
6950     int Mask2[] = { -1, -1, -1, -1 };
6951
6952     for (unsigned i = 0; i != 4; ++i)
6953       if (Locs[i].first != -1) {
6954         unsigned Idx = (i < 2) ? 0 : 4;
6955         Idx += Locs[i].first * 2 + Locs[i].second;
6956         Mask2[i] = Idx;
6957       }
6958
6959     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6960   }
6961
6962   if (NumLo == 3 || NumHi == 3) {
6963     // Otherwise, we must have three elements from one vector, call it X, and
6964     // one element from the other, call it Y.  First, use a shufps to build an
6965     // intermediate vector with the one element from Y and the element from X
6966     // that will be in the same half in the final destination (the indexes don't
6967     // matter). Then, use a shufps to build the final vector, taking the half
6968     // containing the element from Y from the intermediate, and the other half
6969     // from X.
6970     if (NumHi == 3) {
6971       // Normalize it so the 3 elements come from V1.
6972       CommuteVectorShuffleMask(PermMask, 4);
6973       std::swap(V1, V2);
6974     }
6975
6976     // Find the element from V2.
6977     unsigned HiIndex;
6978     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6979       int Val = PermMask[HiIndex];
6980       if (Val < 0)
6981         continue;
6982       if (Val >= 4)
6983         break;
6984     }
6985
6986     Mask1[0] = PermMask[HiIndex];
6987     Mask1[1] = -1;
6988     Mask1[2] = PermMask[HiIndex^1];
6989     Mask1[3] = -1;
6990     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6991
6992     if (HiIndex >= 2) {
6993       Mask1[0] = PermMask[0];
6994       Mask1[1] = PermMask[1];
6995       Mask1[2] = HiIndex & 1 ? 6 : 4;
6996       Mask1[3] = HiIndex & 1 ? 4 : 6;
6997       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6998     }
6999
7000     Mask1[0] = HiIndex & 1 ? 2 : 0;
7001     Mask1[1] = HiIndex & 1 ? 0 : 2;
7002     Mask1[2] = PermMask[2];
7003     Mask1[3] = PermMask[3];
7004     if (Mask1[2] >= 0)
7005       Mask1[2] += 4;
7006     if (Mask1[3] >= 0)
7007       Mask1[3] += 4;
7008     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7009   }
7010
7011   // Break it into (shuffle shuffle_hi, shuffle_lo).
7012   int LoMask[] = { -1, -1, -1, -1 };
7013   int HiMask[] = { -1, -1, -1, -1 };
7014
7015   int *MaskPtr = LoMask;
7016   unsigned MaskIdx = 0;
7017   unsigned LoIdx = 0;
7018   unsigned HiIdx = 2;
7019   for (unsigned i = 0; i != 4; ++i) {
7020     if (i == 2) {
7021       MaskPtr = HiMask;
7022       MaskIdx = 1;
7023       LoIdx = 0;
7024       HiIdx = 2;
7025     }
7026     int Idx = PermMask[i];
7027     if (Idx < 0) {
7028       Locs[i] = std::make_pair(-1, -1);
7029     } else if (Idx < 4) {
7030       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7031       MaskPtr[LoIdx] = Idx;
7032       LoIdx++;
7033     } else {
7034       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7035       MaskPtr[HiIdx] = Idx;
7036       HiIdx++;
7037     }
7038   }
7039
7040   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7041   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7042   int MaskOps[] = { -1, -1, -1, -1 };
7043   for (unsigned i = 0; i != 4; ++i)
7044     if (Locs[i].first != -1)
7045       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7046   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7047 }
7048
7049 static bool MayFoldVectorLoad(SDValue V) {
7050   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7051     V = V.getOperand(0);
7052
7053   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7054     V = V.getOperand(0);
7055   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7056       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7057     // BUILD_VECTOR (load), undef
7058     V = V.getOperand(0);
7059
7060   return MayFoldLoad(V);
7061 }
7062
7063 static
7064 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7065   MVT VT = Op.getSimpleValueType();
7066
7067   // Canonizalize to v2f64.
7068   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7069   return DAG.getNode(ISD::BITCAST, dl, VT,
7070                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7071                                           V1, DAG));
7072 }
7073
7074 static
7075 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7076                         bool HasSSE2) {
7077   SDValue V1 = Op.getOperand(0);
7078   SDValue V2 = Op.getOperand(1);
7079   MVT VT = Op.getSimpleValueType();
7080
7081   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7082
7083   if (HasSSE2 && VT == MVT::v2f64)
7084     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7085
7086   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7087   return DAG.getNode(ISD::BITCAST, dl, VT,
7088                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7089                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7090                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7091 }
7092
7093 static
7094 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7095   SDValue V1 = Op.getOperand(0);
7096   SDValue V2 = Op.getOperand(1);
7097   MVT VT = Op.getSimpleValueType();
7098
7099   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7100          "unsupported shuffle type");
7101
7102   if (V2.getOpcode() == ISD::UNDEF)
7103     V2 = V1;
7104
7105   // v4i32 or v4f32
7106   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7107 }
7108
7109 static
7110 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7111   SDValue V1 = Op.getOperand(0);
7112   SDValue V2 = Op.getOperand(1);
7113   MVT VT = Op.getSimpleValueType();
7114   unsigned NumElems = VT.getVectorNumElements();
7115
7116   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7117   // operand of these instructions is only memory, so check if there's a
7118   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7119   // same masks.
7120   bool CanFoldLoad = false;
7121
7122   // Trivial case, when V2 comes from a load.
7123   if (MayFoldVectorLoad(V2))
7124     CanFoldLoad = true;
7125
7126   // When V1 is a load, it can be folded later into a store in isel, example:
7127   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7128   //    turns into:
7129   //  (MOVLPSmr addr:$src1, VR128:$src2)
7130   // So, recognize this potential and also use MOVLPS or MOVLPD
7131   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7132     CanFoldLoad = true;
7133
7134   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7135   if (CanFoldLoad) {
7136     if (HasSSE2 && NumElems == 2)
7137       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7138
7139     if (NumElems == 4)
7140       // If we don't care about the second element, proceed to use movss.
7141       if (SVOp->getMaskElt(1) != -1)
7142         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7143   }
7144
7145   // movl and movlp will both match v2i64, but v2i64 is never matched by
7146   // movl earlier because we make it strict to avoid messing with the movlp load
7147   // folding logic (see the code above getMOVLP call). Match it here then,
7148   // this is horrible, but will stay like this until we move all shuffle
7149   // matching to x86 specific nodes. Note that for the 1st condition all
7150   // types are matched with movsd.
7151   if (HasSSE2) {
7152     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7153     // as to remove this logic from here, as much as possible
7154     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7155       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7156     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7157   }
7158
7159   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7160
7161   // Invert the operand order and use SHUFPS to match it.
7162   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7163                               getShuffleSHUFImmediate(SVOp), DAG);
7164 }
7165
7166 // Reduce a vector shuffle to zext.
7167 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7168                                     SelectionDAG &DAG) {
7169   // PMOVZX is only available from SSE41.
7170   if (!Subtarget->hasSSE41())
7171     return SDValue();
7172
7173   MVT VT = Op.getSimpleValueType();
7174
7175   // Only AVX2 support 256-bit vector integer extending.
7176   if (!Subtarget->hasInt256() && VT.is256BitVector())
7177     return SDValue();
7178
7179   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7180   SDLoc DL(Op);
7181   SDValue V1 = Op.getOperand(0);
7182   SDValue V2 = Op.getOperand(1);
7183   unsigned NumElems = VT.getVectorNumElements();
7184
7185   // Extending is an unary operation and the element type of the source vector
7186   // won't be equal to or larger than i64.
7187   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7188       VT.getVectorElementType() == MVT::i64)
7189     return SDValue();
7190
7191   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7192   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7193   while ((1U << Shift) < NumElems) {
7194     if (SVOp->getMaskElt(1U << Shift) == 1)
7195       break;
7196     Shift += 1;
7197     // The maximal ratio is 8, i.e. from i8 to i64.
7198     if (Shift > 3)
7199       return SDValue();
7200   }
7201
7202   // Check the shuffle mask.
7203   unsigned Mask = (1U << Shift) - 1;
7204   for (unsigned i = 0; i != NumElems; ++i) {
7205     int EltIdx = SVOp->getMaskElt(i);
7206     if ((i & Mask) != 0 && EltIdx != -1)
7207       return SDValue();
7208     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7209       return SDValue();
7210   }
7211
7212   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7213   MVT NeVT = MVT::getIntegerVT(NBits);
7214   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7215
7216   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7217     return SDValue();
7218
7219   // Simplify the operand as it's prepared to be fed into shuffle.
7220   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7221   if (V1.getOpcode() == ISD::BITCAST &&
7222       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7223       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7224       V1.getOperand(0).getOperand(0)
7225         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7226     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7227     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7228     ConstantSDNode *CIdx =
7229       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7230     // If it's foldable, i.e. normal load with single use, we will let code
7231     // selection to fold it. Otherwise, we will short the conversion sequence.
7232     if (CIdx && CIdx->getZExtValue() == 0 &&
7233         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7234       MVT FullVT = V.getSimpleValueType();
7235       MVT V1VT = V1.getSimpleValueType();
7236       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7237         // The "ext_vec_elt" node is wider than the result node.
7238         // In this case we should extract subvector from V.
7239         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7240         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7241         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7242                                         FullVT.getVectorNumElements()/Ratio);
7243         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7244                         DAG.getIntPtrConstant(0));
7245       }
7246       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7247     }
7248   }
7249
7250   return DAG.getNode(ISD::BITCAST, DL, VT,
7251                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7252 }
7253
7254 static SDValue
7255 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7256                        SelectionDAG &DAG) {
7257   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7258   MVT VT = Op.getSimpleValueType();
7259   SDLoc dl(Op);
7260   SDValue V1 = Op.getOperand(0);
7261   SDValue V2 = Op.getOperand(1);
7262
7263   if (isZeroShuffle(SVOp))
7264     return getZeroVector(VT, Subtarget, DAG, dl);
7265
7266   // Handle splat operations
7267   if (SVOp->isSplat()) {
7268     // Use vbroadcast whenever the splat comes from a foldable load
7269     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7270     if (Broadcast.getNode())
7271       return Broadcast;
7272   }
7273
7274   // Check integer expanding shuffles.
7275   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7276   if (NewOp.getNode())
7277     return NewOp;
7278
7279   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7280   // do it!
7281   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7282       VT == MVT::v16i16 || VT == MVT::v32i8) {
7283     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7284     if (NewOp.getNode())
7285       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7286   } else if ((VT == MVT::v4i32 ||
7287              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7288     // FIXME: Figure out a cleaner way to do this.
7289     // Try to make use of movq to zero out the top part.
7290     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7291       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7292       if (NewOp.getNode()) {
7293         MVT NewVT = NewOp.getSimpleValueType();
7294         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7295                                NewVT, true, false))
7296           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7297                               DAG, Subtarget, dl);
7298       }
7299     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7300       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7301       if (NewOp.getNode()) {
7302         MVT NewVT = NewOp.getSimpleValueType();
7303         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7304           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7305                               DAG, Subtarget, dl);
7306       }
7307     }
7308   }
7309   return SDValue();
7310 }
7311
7312 SDValue
7313 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7314   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7315   SDValue V1 = Op.getOperand(0);
7316   SDValue V2 = Op.getOperand(1);
7317   MVT VT = Op.getSimpleValueType();
7318   SDLoc dl(Op);
7319   unsigned NumElems = VT.getVectorNumElements();
7320   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7321   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7322   bool V1IsSplat = false;
7323   bool V2IsSplat = false;
7324   bool HasSSE2 = Subtarget->hasSSE2();
7325   bool HasFp256    = Subtarget->hasFp256();
7326   bool HasInt256   = Subtarget->hasInt256();
7327   MachineFunction &MF = DAG.getMachineFunction();
7328   bool OptForSize = MF.getFunction()->getAttributes().
7329     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7330
7331   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7332
7333   if (V1IsUndef && V2IsUndef)
7334     return DAG.getUNDEF(VT);
7335
7336   // When we create a shuffle node we put the UNDEF node to second operand,
7337   // but in some cases the first operand may be transformed to UNDEF.
7338   // In this case we should just commute the node.
7339   if (V1IsUndef)
7340     return CommuteVectorShuffle(SVOp, DAG);
7341
7342   // Vector shuffle lowering takes 3 steps:
7343   //
7344   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7345   //    narrowing and commutation of operands should be handled.
7346   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7347   //    shuffle nodes.
7348   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7349   //    so the shuffle can be broken into other shuffles and the legalizer can
7350   //    try the lowering again.
7351   //
7352   // The general idea is that no vector_shuffle operation should be left to
7353   // be matched during isel, all of them must be converted to a target specific
7354   // node here.
7355
7356   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7357   // narrowing and commutation of operands should be handled. The actual code
7358   // doesn't include all of those, work in progress...
7359   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7360   if (NewOp.getNode())
7361     return NewOp;
7362
7363   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7364
7365   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7366   // unpckh_undef). Only use pshufd if speed is more important than size.
7367   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7368     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7369   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7370     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7371
7372   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7373       V2IsUndef && MayFoldVectorLoad(V1))
7374     return getMOVDDup(Op, dl, V1, DAG);
7375
7376   if (isMOVHLPS_v_undef_Mask(M, VT))
7377     return getMOVHighToLow(Op, dl, DAG);
7378
7379   // Use to match splats
7380   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7381       (VT == MVT::v2f64 || VT == MVT::v2i64))
7382     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7383
7384   if (isPSHUFDMask(M, VT)) {
7385     // The actual implementation will match the mask in the if above and then
7386     // during isel it can match several different instructions, not only pshufd
7387     // as its name says, sad but true, emulate the behavior for now...
7388     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7389       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7390
7391     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7392
7393     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7394       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7395
7396     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7397       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7398                                   DAG);
7399
7400     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7401                                 TargetMask, DAG);
7402   }
7403
7404   if (isPALIGNRMask(M, VT, Subtarget))
7405     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7406                                 getShufflePALIGNRImmediate(SVOp),
7407                                 DAG);
7408
7409   // Check if this can be converted into a logical shift.
7410   bool isLeft = false;
7411   unsigned ShAmt = 0;
7412   SDValue ShVal;
7413   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7414   if (isShift && ShVal.hasOneUse()) {
7415     // If the shifted value has multiple uses, it may be cheaper to use
7416     // v_set0 + movlhps or movhlps, etc.
7417     MVT EltVT = VT.getVectorElementType();
7418     ShAmt *= EltVT.getSizeInBits();
7419     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7420   }
7421
7422   if (isMOVLMask(M, VT)) {
7423     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7424       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7425     if (!isMOVLPMask(M, VT)) {
7426       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7427         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7428
7429       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7430         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7431     }
7432   }
7433
7434   // FIXME: fold these into legal mask.
7435   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7436     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7437
7438   if (isMOVHLPSMask(M, VT))
7439     return getMOVHighToLow(Op, dl, DAG);
7440
7441   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7442     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7443
7444   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7445     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7446
7447   if (isMOVLPMask(M, VT))
7448     return getMOVLP(Op, dl, DAG, HasSSE2);
7449
7450   if (ShouldXformToMOVHLPS(M, VT) ||
7451       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7452     return CommuteVectorShuffle(SVOp, DAG);
7453
7454   if (isShift) {
7455     // No better options. Use a vshldq / vsrldq.
7456     MVT EltVT = VT.getVectorElementType();
7457     ShAmt *= EltVT.getSizeInBits();
7458     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7459   }
7460
7461   bool Commuted = false;
7462   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7463   // 1,1,1,1 -> v8i16 though.
7464   V1IsSplat = isSplatVector(V1.getNode());
7465   V2IsSplat = isSplatVector(V2.getNode());
7466
7467   // Canonicalize the splat or undef, if present, to be on the RHS.
7468   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7469     CommuteVectorShuffleMask(M, NumElems);
7470     std::swap(V1, V2);
7471     std::swap(V1IsSplat, V2IsSplat);
7472     Commuted = true;
7473   }
7474
7475   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7476     // Shuffling low element of v1 into undef, just return v1.
7477     if (V2IsUndef)
7478       return V1;
7479     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7480     // the instruction selector will not match, so get a canonical MOVL with
7481     // swapped operands to undo the commute.
7482     return getMOVL(DAG, dl, VT, V2, V1);
7483   }
7484
7485   if (isUNPCKLMask(M, VT, HasInt256))
7486     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7487
7488   if (isUNPCKHMask(M, VT, HasInt256))
7489     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7490
7491   if (V2IsSplat) {
7492     // Normalize mask so all entries that point to V2 points to its first
7493     // element then try to match unpck{h|l} again. If match, return a
7494     // new vector_shuffle with the corrected mask.p
7495     SmallVector<int, 8> NewMask(M.begin(), M.end());
7496     NormalizeMask(NewMask, NumElems);
7497     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7498       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7499     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7500       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7501   }
7502
7503   if (Commuted) {
7504     // Commute is back and try unpck* again.
7505     // FIXME: this seems wrong.
7506     CommuteVectorShuffleMask(M, NumElems);
7507     std::swap(V1, V2);
7508     std::swap(V1IsSplat, V2IsSplat);
7509
7510     if (isUNPCKLMask(M, VT, HasInt256))
7511       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7512
7513     if (isUNPCKHMask(M, VT, HasInt256))
7514       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7515   }
7516
7517   // Normalize the node to match x86 shuffle ops if needed
7518   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7519     return CommuteVectorShuffle(SVOp, DAG);
7520
7521   // The checks below are all present in isShuffleMaskLegal, but they are
7522   // inlined here right now to enable us to directly emit target specific
7523   // nodes, and remove one by one until they don't return Op anymore.
7524
7525   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7526       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7527     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7528       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7529   }
7530
7531   if (isPSHUFHWMask(M, VT, HasInt256))
7532     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7533                                 getShufflePSHUFHWImmediate(SVOp),
7534                                 DAG);
7535
7536   if (isPSHUFLWMask(M, VT, HasInt256))
7537     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7538                                 getShufflePSHUFLWImmediate(SVOp),
7539                                 DAG);
7540
7541   if (isSHUFPMask(M, VT))
7542     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7543                                 getShuffleSHUFImmediate(SVOp), DAG);
7544
7545   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7546     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7547   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7548     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7549
7550   //===--------------------------------------------------------------------===//
7551   // Generate target specific nodes for 128 or 256-bit shuffles only
7552   // supported in the AVX instruction set.
7553   //
7554
7555   // Handle VMOVDDUPY permutations
7556   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7557     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7558
7559   // Handle VPERMILPS/D* permutations
7560   if (isVPERMILPMask(M, VT)) {
7561     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7562       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7563                                   getShuffleSHUFImmediate(SVOp), DAG);
7564     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7565                                 getShuffleSHUFImmediate(SVOp), DAG);
7566   }
7567
7568   // Handle VPERM2F128/VPERM2I128 permutations
7569   if (isVPERM2X128Mask(M, VT, HasFp256))
7570     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7571                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7572
7573   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7574   if (BlendOp.getNode())
7575     return BlendOp;
7576
7577   unsigned Imm8;
7578   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7579     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7580
7581   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7582       VT.is512BitVector()) {
7583     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7584     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7585     SmallVector<SDValue, 16> permclMask;
7586     for (unsigned i = 0; i != NumElems; ++i) {
7587       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7588     }
7589
7590     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7591                                 &permclMask[0], NumElems);
7592     if (V2IsUndef)
7593       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7594       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7595                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7596     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7597                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7598   }
7599
7600   //===--------------------------------------------------------------------===//
7601   // Since no target specific shuffle was selected for this generic one,
7602   // lower it into other known shuffles. FIXME: this isn't true yet, but
7603   // this is the plan.
7604   //
7605
7606   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7607   if (VT == MVT::v8i16) {
7608     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7609     if (NewOp.getNode())
7610       return NewOp;
7611   }
7612
7613   if (VT == MVT::v16i8) {
7614     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7615     if (NewOp.getNode())
7616       return NewOp;
7617   }
7618
7619   if (VT == MVT::v32i8) {
7620     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7621     if (NewOp.getNode())
7622       return NewOp;
7623   }
7624
7625   // Handle all 128-bit wide vectors with 4 elements, and match them with
7626   // several different shuffle types.
7627   if (NumElems == 4 && VT.is128BitVector())
7628     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7629
7630   // Handle general 256-bit shuffles
7631   if (VT.is256BitVector())
7632     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7633
7634   return SDValue();
7635 }
7636
7637 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7638   MVT VT = Op.getSimpleValueType();
7639   SDLoc dl(Op);
7640
7641   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7642     return SDValue();
7643
7644   if (VT.getSizeInBits() == 8) {
7645     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7646                                   Op.getOperand(0), Op.getOperand(1));
7647     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7648                                   DAG.getValueType(VT));
7649     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7650   }
7651
7652   if (VT.getSizeInBits() == 16) {
7653     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7654     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7655     if (Idx == 0)
7656       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7657                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7658                                      DAG.getNode(ISD::BITCAST, dl,
7659                                                  MVT::v4i32,
7660                                                  Op.getOperand(0)),
7661                                      Op.getOperand(1)));
7662     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7663                                   Op.getOperand(0), Op.getOperand(1));
7664     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7665                                   DAG.getValueType(VT));
7666     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7667   }
7668
7669   if (VT == MVT::f32) {
7670     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7671     // the result back to FR32 register. It's only worth matching if the
7672     // result has a single use which is a store or a bitcast to i32.  And in
7673     // the case of a store, it's not worth it if the index is a constant 0,
7674     // because a MOVSSmr can be used instead, which is smaller and faster.
7675     if (!Op.hasOneUse())
7676       return SDValue();
7677     SDNode *User = *Op.getNode()->use_begin();
7678     if ((User->getOpcode() != ISD::STORE ||
7679          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7680           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7681         (User->getOpcode() != ISD::BITCAST ||
7682          User->getValueType(0) != MVT::i32))
7683       return SDValue();
7684     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7685                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7686                                               Op.getOperand(0)),
7687                                               Op.getOperand(1));
7688     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7689   }
7690
7691   if (VT == MVT::i32 || VT == MVT::i64) {
7692     // ExtractPS/pextrq works with constant index.
7693     if (isa<ConstantSDNode>(Op.getOperand(1)))
7694       return Op;
7695   }
7696   return SDValue();
7697 }
7698
7699 /// Extract one bit from mask vector, like v16i1 or v8i1.
7700 /// AVX-512 feature.
7701 SDValue
7702 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7703   SDValue Vec = Op.getOperand(0);
7704   SDLoc dl(Vec);
7705   MVT VecVT = Vec.getSimpleValueType();
7706   SDValue Idx = Op.getOperand(1);
7707   MVT EltVT = Op.getSimpleValueType();
7708
7709   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7710
7711   // variable index can't be handled in mask registers,
7712   // extend vector to VR512
7713   if (!isa<ConstantSDNode>(Idx)) {
7714     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7715     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7716     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7717                               ExtVT.getVectorElementType(), Ext, Idx);
7718     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7719   }
7720
7721   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7722   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7723   unsigned MaxSift = rc->getSize()*8 - 1;
7724   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7725                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7726   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7727                     DAG.getConstant(MaxSift, MVT::i8));
7728   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7729                        DAG.getIntPtrConstant(0));
7730 }
7731
7732 SDValue
7733 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7734                                            SelectionDAG &DAG) const {
7735   SDLoc dl(Op);
7736   SDValue Vec = Op.getOperand(0);
7737   MVT VecVT = Vec.getSimpleValueType();
7738   SDValue Idx = Op.getOperand(1);
7739
7740   if (Op.getSimpleValueType() == MVT::i1)
7741     return ExtractBitFromMaskVector(Op, DAG);
7742
7743   if (!isa<ConstantSDNode>(Idx)) {
7744     if (VecVT.is512BitVector() ||
7745         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7746          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7747
7748       MVT MaskEltVT =
7749         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7750       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7751                                     MaskEltVT.getSizeInBits());
7752
7753       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7754       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7755                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7756                                 Idx, DAG.getConstant(0, getPointerTy()));
7757       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7758       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7759                         Perm, DAG.getConstant(0, getPointerTy()));
7760     }
7761     return SDValue();
7762   }
7763
7764   // If this is a 256-bit vector result, first extract the 128-bit vector and
7765   // then extract the element from the 128-bit vector.
7766   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7767
7768     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7769     // Get the 128-bit vector.
7770     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7771     MVT EltVT = VecVT.getVectorElementType();
7772
7773     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7774
7775     //if (IdxVal >= NumElems/2)
7776     //  IdxVal -= NumElems/2;
7777     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7778     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7779                        DAG.getConstant(IdxVal, MVT::i32));
7780   }
7781
7782   assert(VecVT.is128BitVector() && "Unexpected vector length");
7783
7784   if (Subtarget->hasSSE41()) {
7785     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7786     if (Res.getNode())
7787       return Res;
7788   }
7789
7790   MVT VT = Op.getSimpleValueType();
7791   // TODO: handle v16i8.
7792   if (VT.getSizeInBits() == 16) {
7793     SDValue Vec = Op.getOperand(0);
7794     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7795     if (Idx == 0)
7796       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7797                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7798                                      DAG.getNode(ISD::BITCAST, dl,
7799                                                  MVT::v4i32, Vec),
7800                                      Op.getOperand(1)));
7801     // Transform it so it match pextrw which produces a 32-bit result.
7802     MVT EltVT = MVT::i32;
7803     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7804                                   Op.getOperand(0), Op.getOperand(1));
7805     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7806                                   DAG.getValueType(VT));
7807     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7808   }
7809
7810   if (VT.getSizeInBits() == 32) {
7811     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7812     if (Idx == 0)
7813       return Op;
7814
7815     // SHUFPS the element to the lowest double word, then movss.
7816     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7817     MVT VVT = Op.getOperand(0).getSimpleValueType();
7818     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7819                                        DAG.getUNDEF(VVT), Mask);
7820     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7821                        DAG.getIntPtrConstant(0));
7822   }
7823
7824   if (VT.getSizeInBits() == 64) {
7825     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7826     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7827     //        to match extract_elt for f64.
7828     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7829     if (Idx == 0)
7830       return Op;
7831
7832     // UNPCKHPD the element to the lowest double word, then movsd.
7833     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7834     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7835     int Mask[2] = { 1, -1 };
7836     MVT VVT = Op.getOperand(0).getSimpleValueType();
7837     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7838                                        DAG.getUNDEF(VVT), Mask);
7839     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7840                        DAG.getIntPtrConstant(0));
7841   }
7842
7843   return SDValue();
7844 }
7845
7846 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7847   MVT VT = Op.getSimpleValueType();
7848   MVT EltVT = VT.getVectorElementType();
7849   SDLoc dl(Op);
7850
7851   SDValue N0 = Op.getOperand(0);
7852   SDValue N1 = Op.getOperand(1);
7853   SDValue N2 = Op.getOperand(2);
7854
7855   if (!VT.is128BitVector())
7856     return SDValue();
7857
7858   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7859       isa<ConstantSDNode>(N2)) {
7860     unsigned Opc;
7861     if (VT == MVT::v8i16)
7862       Opc = X86ISD::PINSRW;
7863     else if (VT == MVT::v16i8)
7864       Opc = X86ISD::PINSRB;
7865     else
7866       Opc = X86ISD::PINSRB;
7867
7868     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7869     // argument.
7870     if (N1.getValueType() != MVT::i32)
7871       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7872     if (N2.getValueType() != MVT::i32)
7873       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7874     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7875   }
7876
7877   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7878     // Bits [7:6] of the constant are the source select.  This will always be
7879     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7880     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7881     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7882     // Bits [5:4] of the constant are the destination select.  This is the
7883     //  value of the incoming immediate.
7884     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7885     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7886     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7887     // Create this as a scalar to vector..
7888     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7889     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7890   }
7891
7892   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7893     // PINSR* works with constant index.
7894     return Op;
7895   }
7896   return SDValue();
7897 }
7898
7899 SDValue
7900 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7901   MVT VT = Op.getSimpleValueType();
7902   MVT EltVT = VT.getVectorElementType();
7903
7904   SDLoc dl(Op);
7905   SDValue N0 = Op.getOperand(0);
7906   SDValue N1 = Op.getOperand(1);
7907   SDValue N2 = Op.getOperand(2);
7908
7909   // If this is a 256-bit vector result, first extract the 128-bit vector,
7910   // insert the element into the extracted half and then place it back.
7911   if (VT.is256BitVector() || VT.is512BitVector()) {
7912     if (!isa<ConstantSDNode>(N2))
7913       return SDValue();
7914
7915     // Get the desired 128-bit vector half.
7916     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7917     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7918
7919     // Insert the element into the desired half.
7920     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7921     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7922
7923     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7924                     DAG.getConstant(IdxIn128, MVT::i32));
7925
7926     // Insert the changed part back to the 256-bit vector
7927     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7928   }
7929
7930   if (Subtarget->hasSSE41())
7931     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7932
7933   if (EltVT == MVT::i8)
7934     return SDValue();
7935
7936   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7937     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7938     // as its second argument.
7939     if (N1.getValueType() != MVT::i32)
7940       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7941     if (N2.getValueType() != MVT::i32)
7942       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7943     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7944   }
7945   return SDValue();
7946 }
7947
7948 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7949   SDLoc dl(Op);
7950   MVT OpVT = Op.getSimpleValueType();
7951
7952   // If this is a 256-bit vector result, first insert into a 128-bit
7953   // vector and then insert into the 256-bit vector.
7954   if (!OpVT.is128BitVector()) {
7955     // Insert into a 128-bit vector.
7956     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7957     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7958                                  OpVT.getVectorNumElements() / SizeFactor);
7959
7960     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7961
7962     // Insert the 128-bit vector.
7963     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7964   }
7965
7966   if (OpVT == MVT::v1i64 &&
7967       Op.getOperand(0).getValueType() == MVT::i64)
7968     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7969
7970   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7971   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7972   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7973                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7974 }
7975
7976 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7977 // a simple subregister reference or explicit instructions to grab
7978 // upper bits of a vector.
7979 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7980                                       SelectionDAG &DAG) {
7981   SDLoc dl(Op);
7982   SDValue In =  Op.getOperand(0);
7983   SDValue Idx = Op.getOperand(1);
7984   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7985   MVT ResVT   = Op.getSimpleValueType();
7986   MVT InVT    = In.getSimpleValueType();
7987
7988   if (Subtarget->hasFp256()) {
7989     if (ResVT.is128BitVector() &&
7990         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7991         isa<ConstantSDNode>(Idx)) {
7992       return Extract128BitVector(In, IdxVal, DAG, dl);
7993     }
7994     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7995         isa<ConstantSDNode>(Idx)) {
7996       return Extract256BitVector(In, IdxVal, DAG, dl);
7997     }
7998   }
7999   return SDValue();
8000 }
8001
8002 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8003 // simple superregister reference or explicit instructions to insert
8004 // the upper bits of a vector.
8005 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8006                                      SelectionDAG &DAG) {
8007   if (Subtarget->hasFp256()) {
8008     SDLoc dl(Op.getNode());
8009     SDValue Vec = Op.getNode()->getOperand(0);
8010     SDValue SubVec = Op.getNode()->getOperand(1);
8011     SDValue Idx = Op.getNode()->getOperand(2);
8012
8013     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8014          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8015         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8016         isa<ConstantSDNode>(Idx)) {
8017       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8018       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8019     }
8020
8021     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8022         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8023         isa<ConstantSDNode>(Idx)) {
8024       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8025       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8026     }
8027   }
8028   return SDValue();
8029 }
8030
8031 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8032 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8033 // one of the above mentioned nodes. It has to be wrapped because otherwise
8034 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8035 // be used to form addressing mode. These wrapped nodes will be selected
8036 // into MOV32ri.
8037 SDValue
8038 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8039   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8040
8041   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8042   // global base reg.
8043   unsigned char OpFlag = 0;
8044   unsigned WrapperKind = X86ISD::Wrapper;
8045   CodeModel::Model M = getTargetMachine().getCodeModel();
8046
8047   if (Subtarget->isPICStyleRIPRel() &&
8048       (M == CodeModel::Small || M == CodeModel::Kernel))
8049     WrapperKind = X86ISD::WrapperRIP;
8050   else if (Subtarget->isPICStyleGOT())
8051     OpFlag = X86II::MO_GOTOFF;
8052   else if (Subtarget->isPICStyleStubPIC())
8053     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8054
8055   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8056                                              CP->getAlignment(),
8057                                              CP->getOffset(), OpFlag);
8058   SDLoc DL(CP);
8059   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8060   // With PIC, the address is actually $g + Offset.
8061   if (OpFlag) {
8062     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8063                          DAG.getNode(X86ISD::GlobalBaseReg,
8064                                      SDLoc(), getPointerTy()),
8065                          Result);
8066   }
8067
8068   return Result;
8069 }
8070
8071 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8072   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8073
8074   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8075   // global base reg.
8076   unsigned char OpFlag = 0;
8077   unsigned WrapperKind = X86ISD::Wrapper;
8078   CodeModel::Model M = getTargetMachine().getCodeModel();
8079
8080   if (Subtarget->isPICStyleRIPRel() &&
8081       (M == CodeModel::Small || M == CodeModel::Kernel))
8082     WrapperKind = X86ISD::WrapperRIP;
8083   else if (Subtarget->isPICStyleGOT())
8084     OpFlag = X86II::MO_GOTOFF;
8085   else if (Subtarget->isPICStyleStubPIC())
8086     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8087
8088   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8089                                           OpFlag);
8090   SDLoc DL(JT);
8091   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8092
8093   // With PIC, the address is actually $g + Offset.
8094   if (OpFlag)
8095     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8096                          DAG.getNode(X86ISD::GlobalBaseReg,
8097                                      SDLoc(), getPointerTy()),
8098                          Result);
8099
8100   return Result;
8101 }
8102
8103 SDValue
8104 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8105   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8106
8107   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8108   // global base reg.
8109   unsigned char OpFlag = 0;
8110   unsigned WrapperKind = X86ISD::Wrapper;
8111   CodeModel::Model M = getTargetMachine().getCodeModel();
8112
8113   if (Subtarget->isPICStyleRIPRel() &&
8114       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8115     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8116       OpFlag = X86II::MO_GOTPCREL;
8117     WrapperKind = X86ISD::WrapperRIP;
8118   } else if (Subtarget->isPICStyleGOT()) {
8119     OpFlag = X86II::MO_GOT;
8120   } else if (Subtarget->isPICStyleStubPIC()) {
8121     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8122   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8123     OpFlag = X86II::MO_DARWIN_NONLAZY;
8124   }
8125
8126   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8127
8128   SDLoc DL(Op);
8129   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8130
8131   // With PIC, the address is actually $g + Offset.
8132   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8133       !Subtarget->is64Bit()) {
8134     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8135                          DAG.getNode(X86ISD::GlobalBaseReg,
8136                                      SDLoc(), getPointerTy()),
8137                          Result);
8138   }
8139
8140   // For symbols that require a load from a stub to get the address, emit the
8141   // load.
8142   if (isGlobalStubReference(OpFlag))
8143     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8144                          MachinePointerInfo::getGOT(), false, false, false, 0);
8145
8146   return Result;
8147 }
8148
8149 SDValue
8150 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8151   // Create the TargetBlockAddressAddress node.
8152   unsigned char OpFlags =
8153     Subtarget->ClassifyBlockAddressReference();
8154   CodeModel::Model M = getTargetMachine().getCodeModel();
8155   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8156   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8157   SDLoc dl(Op);
8158   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8159                                              OpFlags);
8160
8161   if (Subtarget->isPICStyleRIPRel() &&
8162       (M == CodeModel::Small || M == CodeModel::Kernel))
8163     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8164   else
8165     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8166
8167   // With PIC, the address is actually $g + Offset.
8168   if (isGlobalRelativeToPICBase(OpFlags)) {
8169     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8170                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8171                          Result);
8172   }
8173
8174   return Result;
8175 }
8176
8177 SDValue
8178 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8179                                       int64_t Offset, SelectionDAG &DAG) const {
8180   // Create the TargetGlobalAddress node, folding in the constant
8181   // offset if it is legal.
8182   unsigned char OpFlags =
8183     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8184   CodeModel::Model M = getTargetMachine().getCodeModel();
8185   SDValue Result;
8186   if (OpFlags == X86II::MO_NO_FLAG &&
8187       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8188     // A direct static reference to a global.
8189     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8190     Offset = 0;
8191   } else {
8192     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8193   }
8194
8195   if (Subtarget->isPICStyleRIPRel() &&
8196       (M == CodeModel::Small || M == CodeModel::Kernel))
8197     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8198   else
8199     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8200
8201   // With PIC, the address is actually $g + Offset.
8202   if (isGlobalRelativeToPICBase(OpFlags)) {
8203     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8204                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8205                          Result);
8206   }
8207
8208   // For globals that require a load from a stub to get the address, emit the
8209   // load.
8210   if (isGlobalStubReference(OpFlags))
8211     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8212                          MachinePointerInfo::getGOT(), false, false, false, 0);
8213
8214   // If there was a non-zero offset that we didn't fold, create an explicit
8215   // addition for it.
8216   if (Offset != 0)
8217     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8218                          DAG.getConstant(Offset, getPointerTy()));
8219
8220   return Result;
8221 }
8222
8223 SDValue
8224 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8225   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8226   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8227   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8228 }
8229
8230 static SDValue
8231 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8232            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8233            unsigned char OperandFlags, bool LocalDynamic = false) {
8234   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8235   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8236   SDLoc dl(GA);
8237   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8238                                            GA->getValueType(0),
8239                                            GA->getOffset(),
8240                                            OperandFlags);
8241
8242   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8243                                            : X86ISD::TLSADDR;
8244
8245   if (InFlag) {
8246     SDValue Ops[] = { Chain,  TGA, *InFlag };
8247     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8248   } else {
8249     SDValue Ops[]  = { Chain, TGA };
8250     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8251   }
8252
8253   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8254   MFI->setAdjustsStack(true);
8255
8256   SDValue Flag = Chain.getValue(1);
8257   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8258 }
8259
8260 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8261 static SDValue
8262 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8263                                 const EVT PtrVT) {
8264   SDValue InFlag;
8265   SDLoc dl(GA);  // ? function entry point might be better
8266   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8267                                    DAG.getNode(X86ISD::GlobalBaseReg,
8268                                                SDLoc(), PtrVT), InFlag);
8269   InFlag = Chain.getValue(1);
8270
8271   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8272 }
8273
8274 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8275 static SDValue
8276 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8277                                 const EVT PtrVT) {
8278   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8279                     X86::RAX, X86II::MO_TLSGD);
8280 }
8281
8282 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8283                                            SelectionDAG &DAG,
8284                                            const EVT PtrVT,
8285                                            bool is64Bit) {
8286   SDLoc dl(GA);
8287
8288   // Get the start address of the TLS block for this module.
8289   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8290       .getInfo<X86MachineFunctionInfo>();
8291   MFI->incNumLocalDynamicTLSAccesses();
8292
8293   SDValue Base;
8294   if (is64Bit) {
8295     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8296                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8297   } else {
8298     SDValue InFlag;
8299     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8300         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8301     InFlag = Chain.getValue(1);
8302     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8303                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8304   }
8305
8306   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8307   // of Base.
8308
8309   // Build x@dtpoff.
8310   unsigned char OperandFlags = X86II::MO_DTPOFF;
8311   unsigned WrapperKind = X86ISD::Wrapper;
8312   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8313                                            GA->getValueType(0),
8314                                            GA->getOffset(), OperandFlags);
8315   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8316
8317   // Add x@dtpoff with the base.
8318   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8319 }
8320
8321 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8322 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8323                                    const EVT PtrVT, TLSModel::Model model,
8324                                    bool is64Bit, bool isPIC) {
8325   SDLoc dl(GA);
8326
8327   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8328   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8329                                                          is64Bit ? 257 : 256));
8330
8331   SDValue ThreadPointer =
8332       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8333                   MachinePointerInfo(Ptr), false, false, false, 0);
8334
8335   unsigned char OperandFlags = 0;
8336   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8337   // initialexec.
8338   unsigned WrapperKind = X86ISD::Wrapper;
8339   if (model == TLSModel::LocalExec) {
8340     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8341   } else if (model == TLSModel::InitialExec) {
8342     if (is64Bit) {
8343       OperandFlags = X86II::MO_GOTTPOFF;
8344       WrapperKind = X86ISD::WrapperRIP;
8345     } else {
8346       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8347     }
8348   } else {
8349     llvm_unreachable("Unexpected model");
8350   }
8351
8352   // emit "addl x@ntpoff,%eax" (local exec)
8353   // or "addl x@indntpoff,%eax" (initial exec)
8354   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8355   SDValue TGA =
8356       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8357                                  GA->getOffset(), OperandFlags);
8358   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8359
8360   if (model == TLSModel::InitialExec) {
8361     if (isPIC && !is64Bit) {
8362       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8363                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8364                            Offset);
8365     }
8366
8367     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8368                          MachinePointerInfo::getGOT(), false, false, false, 0);
8369   }
8370
8371   // The address of the thread local variable is the add of the thread
8372   // pointer with the offset of the variable.
8373   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8374 }
8375
8376 SDValue
8377 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8378
8379   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8380   const GlobalValue *GV = GA->getGlobal();
8381
8382   if (Subtarget->isTargetELF()) {
8383     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8384
8385     switch (model) {
8386       case TLSModel::GeneralDynamic:
8387         if (Subtarget->is64Bit())
8388           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8389         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8390       case TLSModel::LocalDynamic:
8391         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8392                                            Subtarget->is64Bit());
8393       case TLSModel::InitialExec:
8394       case TLSModel::LocalExec:
8395         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8396                                    Subtarget->is64Bit(),
8397                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8398     }
8399     llvm_unreachable("Unknown TLS model.");
8400   }
8401
8402   if (Subtarget->isTargetDarwin()) {
8403     // Darwin only has one model of TLS.  Lower to that.
8404     unsigned char OpFlag = 0;
8405     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8406                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8407
8408     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8409     // global base reg.
8410     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8411                   !Subtarget->is64Bit();
8412     if (PIC32)
8413       OpFlag = X86II::MO_TLVP_PIC_BASE;
8414     else
8415       OpFlag = X86II::MO_TLVP;
8416     SDLoc DL(Op);
8417     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8418                                                 GA->getValueType(0),
8419                                                 GA->getOffset(), OpFlag);
8420     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8421
8422     // With PIC32, the address is actually $g + Offset.
8423     if (PIC32)
8424       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8425                            DAG.getNode(X86ISD::GlobalBaseReg,
8426                                        SDLoc(), getPointerTy()),
8427                            Offset);
8428
8429     // Lowering the machine isd will make sure everything is in the right
8430     // location.
8431     SDValue Chain = DAG.getEntryNode();
8432     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8433     SDValue Args[] = { Chain, Offset };
8434     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8435
8436     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8437     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8438     MFI->setAdjustsStack(true);
8439
8440     // And our return value (tls address) is in the standard call return value
8441     // location.
8442     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8443     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8444                               Chain.getValue(1));
8445   }
8446
8447   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8448     // Just use the implicit TLS architecture
8449     // Need to generate someting similar to:
8450     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8451     //                                  ; from TEB
8452     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8453     //   mov     rcx, qword [rdx+rcx*8]
8454     //   mov     eax, .tls$:tlsvar
8455     //   [rax+rcx] contains the address
8456     // Windows 64bit: gs:0x58
8457     // Windows 32bit: fs:__tls_array
8458
8459     // If GV is an alias then use the aliasee for determining
8460     // thread-localness.
8461     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8462       GV = GA->resolveAliasedGlobal(false);
8463     SDLoc dl(GA);
8464     SDValue Chain = DAG.getEntryNode();
8465
8466     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8467     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8468     // use its literal value of 0x2C.
8469     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8470                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8471                                                              256)
8472                                         : Type::getInt32PtrTy(*DAG.getContext(),
8473                                                               257));
8474
8475     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8476       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8477         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8478
8479     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8480                                         MachinePointerInfo(Ptr),
8481                                         false, false, false, 0);
8482
8483     // Load the _tls_index variable
8484     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8485     if (Subtarget->is64Bit())
8486       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8487                            IDX, MachinePointerInfo(), MVT::i32,
8488                            false, false, 0);
8489     else
8490       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8491                         false, false, false, 0);
8492
8493     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8494                                     getPointerTy());
8495     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8496
8497     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8498     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8499                       false, false, false, 0);
8500
8501     // Get the offset of start of .tls section
8502     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8503                                              GA->getValueType(0),
8504                                              GA->getOffset(), X86II::MO_SECREL);
8505     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8506
8507     // The address of the thread local variable is the add of the thread
8508     // pointer with the offset of the variable.
8509     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8510   }
8511
8512   llvm_unreachable("TLS not implemented for this target.");
8513 }
8514
8515 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8516 /// and take a 2 x i32 value to shift plus a shift amount.
8517 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8518   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8519   MVT VT = Op.getSimpleValueType();
8520   unsigned VTBits = VT.getSizeInBits();
8521   SDLoc dl(Op);
8522   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8523   SDValue ShOpLo = Op.getOperand(0);
8524   SDValue ShOpHi = Op.getOperand(1);
8525   SDValue ShAmt  = Op.getOperand(2);
8526   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8527   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8528   // during isel.
8529   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8530                                   DAG.getConstant(VTBits - 1, MVT::i8));
8531   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8532                                      DAG.getConstant(VTBits - 1, MVT::i8))
8533                        : DAG.getConstant(0, VT);
8534
8535   SDValue Tmp2, Tmp3;
8536   if (Op.getOpcode() == ISD::SHL_PARTS) {
8537     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8538     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8539   } else {
8540     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8541     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8542   }
8543
8544   // If the shift amount is larger or equal than the width of a part we can't
8545   // rely on the results of shld/shrd. Insert a test and select the appropriate
8546   // values for large shift amounts.
8547   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8548                                 DAG.getConstant(VTBits, MVT::i8));
8549   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8550                              AndNode, DAG.getConstant(0, MVT::i8));
8551
8552   SDValue Hi, Lo;
8553   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8554   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8555   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8556
8557   if (Op.getOpcode() == ISD::SHL_PARTS) {
8558     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8559     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8560   } else {
8561     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8562     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8563   }
8564
8565   SDValue Ops[2] = { Lo, Hi };
8566   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8567 }
8568
8569 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8570                                            SelectionDAG &DAG) const {
8571   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8572
8573   if (SrcVT.isVector())
8574     return SDValue();
8575
8576   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8577          "Unknown SINT_TO_FP to lower!");
8578
8579   // These are really Legal; return the operand so the caller accepts it as
8580   // Legal.
8581   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8582     return Op;
8583   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8584       Subtarget->is64Bit()) {
8585     return Op;
8586   }
8587
8588   SDLoc dl(Op);
8589   unsigned Size = SrcVT.getSizeInBits()/8;
8590   MachineFunction &MF = DAG.getMachineFunction();
8591   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8592   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8593   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8594                                StackSlot,
8595                                MachinePointerInfo::getFixedStack(SSFI),
8596                                false, false, 0);
8597   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8598 }
8599
8600 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8601                                      SDValue StackSlot,
8602                                      SelectionDAG &DAG) const {
8603   // Build the FILD
8604   SDLoc DL(Op);
8605   SDVTList Tys;
8606   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8607   if (useSSE)
8608     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8609   else
8610     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8611
8612   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8613
8614   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8615   MachineMemOperand *MMO;
8616   if (FI) {
8617     int SSFI = FI->getIndex();
8618     MMO =
8619       DAG.getMachineFunction()
8620       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8621                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8622   } else {
8623     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8624     StackSlot = StackSlot.getOperand(1);
8625   }
8626   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8627   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8628                                            X86ISD::FILD, DL,
8629                                            Tys, Ops, array_lengthof(Ops),
8630                                            SrcVT, MMO);
8631
8632   if (useSSE) {
8633     Chain = Result.getValue(1);
8634     SDValue InFlag = Result.getValue(2);
8635
8636     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8637     // shouldn't be necessary except that RFP cannot be live across
8638     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8639     MachineFunction &MF = DAG.getMachineFunction();
8640     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8641     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8642     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8643     Tys = DAG.getVTList(MVT::Other);
8644     SDValue Ops[] = {
8645       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8646     };
8647     MachineMemOperand *MMO =
8648       DAG.getMachineFunction()
8649       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8650                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8651
8652     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8653                                     Ops, array_lengthof(Ops),
8654                                     Op.getValueType(), MMO);
8655     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8656                          MachinePointerInfo::getFixedStack(SSFI),
8657                          false, false, false, 0);
8658   }
8659
8660   return Result;
8661 }
8662
8663 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8664 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8665                                                SelectionDAG &DAG) const {
8666   // This algorithm is not obvious. Here it is what we're trying to output:
8667   /*
8668      movq       %rax,  %xmm0
8669      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8670      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8671      #ifdef __SSE3__
8672        haddpd   %xmm0, %xmm0
8673      #else
8674        pshufd   $0x4e, %xmm0, %xmm1
8675        addpd    %xmm1, %xmm0
8676      #endif
8677   */
8678
8679   SDLoc dl(Op);
8680   LLVMContext *Context = DAG.getContext();
8681
8682   // Build some magic constants.
8683   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8684   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8685   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8686
8687   SmallVector<Constant*,2> CV1;
8688   CV1.push_back(
8689     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8690                                       APInt(64, 0x4330000000000000ULL))));
8691   CV1.push_back(
8692     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8693                                       APInt(64, 0x4530000000000000ULL))));
8694   Constant *C1 = ConstantVector::get(CV1);
8695   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8696
8697   // Load the 64-bit value into an XMM register.
8698   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8699                             Op.getOperand(0));
8700   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8701                               MachinePointerInfo::getConstantPool(),
8702                               false, false, false, 16);
8703   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8704                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8705                               CLod0);
8706
8707   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8708                               MachinePointerInfo::getConstantPool(),
8709                               false, false, false, 16);
8710   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8711   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8712   SDValue Result;
8713
8714   if (Subtarget->hasSSE3()) {
8715     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8716     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8717   } else {
8718     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8719     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8720                                            S2F, 0x4E, DAG);
8721     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8722                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8723                          Sub);
8724   }
8725
8726   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8727                      DAG.getIntPtrConstant(0));
8728 }
8729
8730 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8731 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8732                                                SelectionDAG &DAG) const {
8733   SDLoc dl(Op);
8734   // FP constant to bias correct the final result.
8735   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8736                                    MVT::f64);
8737
8738   // Load the 32-bit value into an XMM register.
8739   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8740                              Op.getOperand(0));
8741
8742   // Zero out the upper parts of the register.
8743   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8744
8745   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8746                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8747                      DAG.getIntPtrConstant(0));
8748
8749   // Or the load with the bias.
8750   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8751                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8752                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8753                                                    MVT::v2f64, Load)),
8754                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8755                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8756                                                    MVT::v2f64, Bias)));
8757   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8758                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8759                    DAG.getIntPtrConstant(0));
8760
8761   // Subtract the bias.
8762   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8763
8764   // Handle final rounding.
8765   EVT DestVT = Op.getValueType();
8766
8767   if (DestVT.bitsLT(MVT::f64))
8768     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8769                        DAG.getIntPtrConstant(0));
8770   if (DestVT.bitsGT(MVT::f64))
8771     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8772
8773   // Handle final rounding.
8774   return Sub;
8775 }
8776
8777 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8778                                                SelectionDAG &DAG) const {
8779   SDValue N0 = Op.getOperand(0);
8780   MVT SVT = N0.getSimpleValueType();
8781   SDLoc dl(Op);
8782
8783   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8784           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8785          "Custom UINT_TO_FP is not supported!");
8786
8787   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8788   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8789                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8790 }
8791
8792 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8793                                            SelectionDAG &DAG) const {
8794   SDValue N0 = Op.getOperand(0);
8795   SDLoc dl(Op);
8796
8797   if (Op.getValueType().isVector())
8798     return lowerUINT_TO_FP_vec(Op, DAG);
8799
8800   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8801   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8802   // the optimization here.
8803   if (DAG.SignBitIsZero(N0))
8804     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8805
8806   MVT SrcVT = N0.getSimpleValueType();
8807   MVT DstVT = Op.getSimpleValueType();
8808   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8809     return LowerUINT_TO_FP_i64(Op, DAG);
8810   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8811     return LowerUINT_TO_FP_i32(Op, DAG);
8812   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8813     return SDValue();
8814
8815   // Make a 64-bit buffer, and use it to build an FILD.
8816   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8817   if (SrcVT == MVT::i32) {
8818     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8819     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8820                                      getPointerTy(), StackSlot, WordOff);
8821     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8822                                   StackSlot, MachinePointerInfo(),
8823                                   false, false, 0);
8824     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8825                                   OffsetSlot, MachinePointerInfo(),
8826                                   false, false, 0);
8827     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8828     return Fild;
8829   }
8830
8831   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8832   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8833                                StackSlot, MachinePointerInfo(),
8834                                false, false, 0);
8835   // For i64 source, we need to add the appropriate power of 2 if the input
8836   // was negative.  This is the same as the optimization in
8837   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8838   // we must be careful to do the computation in x87 extended precision, not
8839   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8840   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8841   MachineMemOperand *MMO =
8842     DAG.getMachineFunction()
8843     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8844                           MachineMemOperand::MOLoad, 8, 8);
8845
8846   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8847   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8848   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8849                                          array_lengthof(Ops), MVT::i64, MMO);
8850
8851   APInt FF(32, 0x5F800000ULL);
8852
8853   // Check whether the sign bit is set.
8854   SDValue SignSet = DAG.getSetCC(dl,
8855                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8856                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8857                                  ISD::SETLT);
8858
8859   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8860   SDValue FudgePtr = DAG.getConstantPool(
8861                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8862                                          getPointerTy());
8863
8864   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8865   SDValue Zero = DAG.getIntPtrConstant(0);
8866   SDValue Four = DAG.getIntPtrConstant(4);
8867   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8868                                Zero, Four);
8869   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8870
8871   // Load the value out, extending it from f32 to f80.
8872   // FIXME: Avoid the extend by constructing the right constant pool?
8873   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8874                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8875                                  MVT::f32, false, false, 4);
8876   // Extend everything to 80 bits to force it to be done on x87.
8877   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8878   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8879 }
8880
8881 std::pair<SDValue,SDValue>
8882 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8883                                     bool IsSigned, bool IsReplace) const {
8884   SDLoc DL(Op);
8885
8886   EVT DstTy = Op.getValueType();
8887
8888   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8889     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8890     DstTy = MVT::i64;
8891   }
8892
8893   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8894          DstTy.getSimpleVT() >= MVT::i16 &&
8895          "Unknown FP_TO_INT to lower!");
8896
8897   // These are really Legal.
8898   if (DstTy == MVT::i32 &&
8899       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8900     return std::make_pair(SDValue(), SDValue());
8901   if (Subtarget->is64Bit() &&
8902       DstTy == MVT::i64 &&
8903       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8904     return std::make_pair(SDValue(), SDValue());
8905
8906   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8907   // stack slot, or into the FTOL runtime function.
8908   MachineFunction &MF = DAG.getMachineFunction();
8909   unsigned MemSize = DstTy.getSizeInBits()/8;
8910   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8911   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8912
8913   unsigned Opc;
8914   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8915     Opc = X86ISD::WIN_FTOL;
8916   else
8917     switch (DstTy.getSimpleVT().SimpleTy) {
8918     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8919     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8920     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8921     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8922     }
8923
8924   SDValue Chain = DAG.getEntryNode();
8925   SDValue Value = Op.getOperand(0);
8926   EVT TheVT = Op.getOperand(0).getValueType();
8927   // FIXME This causes a redundant load/store if the SSE-class value is already
8928   // in memory, such as if it is on the callstack.
8929   if (isScalarFPTypeInSSEReg(TheVT)) {
8930     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8931     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8932                          MachinePointerInfo::getFixedStack(SSFI),
8933                          false, false, 0);
8934     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8935     SDValue Ops[] = {
8936       Chain, StackSlot, DAG.getValueType(TheVT)
8937     };
8938
8939     MachineMemOperand *MMO =
8940       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8941                               MachineMemOperand::MOLoad, MemSize, MemSize);
8942     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8943                                     array_lengthof(Ops), DstTy, MMO);
8944     Chain = Value.getValue(1);
8945     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8946     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8947   }
8948
8949   MachineMemOperand *MMO =
8950     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8951                             MachineMemOperand::MOStore, MemSize, MemSize);
8952
8953   if (Opc != X86ISD::WIN_FTOL) {
8954     // Build the FP_TO_INT*_IN_MEM
8955     SDValue Ops[] = { Chain, Value, StackSlot };
8956     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8957                                            Ops, array_lengthof(Ops), DstTy,
8958                                            MMO);
8959     return std::make_pair(FIST, StackSlot);
8960   } else {
8961     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8962       DAG.getVTList(MVT::Other, MVT::Glue),
8963       Chain, Value);
8964     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8965       MVT::i32, ftol.getValue(1));
8966     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8967       MVT::i32, eax.getValue(2));
8968     SDValue Ops[] = { eax, edx };
8969     SDValue pair = IsReplace
8970       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8971       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8972     return std::make_pair(pair, SDValue());
8973   }
8974 }
8975
8976 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8977                               const X86Subtarget *Subtarget) {
8978   MVT VT = Op->getSimpleValueType(0);
8979   SDValue In = Op->getOperand(0);
8980   MVT InVT = In.getSimpleValueType();
8981   SDLoc dl(Op);
8982
8983   // Optimize vectors in AVX mode:
8984   //
8985   //   v8i16 -> v8i32
8986   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8987   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8988   //   Concat upper and lower parts.
8989   //
8990   //   v4i32 -> v4i64
8991   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8992   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8993   //   Concat upper and lower parts.
8994   //
8995
8996   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
8997       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8998       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8999     return SDValue();
9000
9001   if (Subtarget->hasInt256())
9002     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9003
9004   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9005   SDValue Undef = DAG.getUNDEF(InVT);
9006   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9007   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9008   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9009
9010   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9011                              VT.getVectorNumElements()/2);
9012
9013   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9014   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9015
9016   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9017 }
9018
9019 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9020                                         SelectionDAG &DAG) {
9021   MVT VT = Op->getSimpleValueType(0);
9022   SDValue In = Op->getOperand(0);
9023   MVT InVT = In.getSimpleValueType();
9024   SDLoc DL(Op);
9025   unsigned int NumElts = VT.getVectorNumElements();
9026   if (NumElts != 8 && NumElts != 16)
9027     return SDValue();
9028
9029   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9030     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9031
9032   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9034   // Now we have only mask extension
9035   assert(InVT.getVectorElementType() == MVT::i1);
9036   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9037   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9038   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9039   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9040   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9041                            MachinePointerInfo::getConstantPool(),
9042                            false, false, false, Alignment);
9043
9044   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9045   if (VT.is512BitVector())
9046     return Brcst;
9047   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9048 }
9049
9050 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9051                                SelectionDAG &DAG) {
9052   if (Subtarget->hasFp256()) {
9053     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9054     if (Res.getNode())
9055       return Res;
9056   }
9057
9058   return SDValue();
9059 }
9060
9061 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9062                                 SelectionDAG &DAG) {
9063   SDLoc DL(Op);
9064   MVT VT = Op.getSimpleValueType();
9065   SDValue In = Op.getOperand(0);
9066   MVT SVT = In.getSimpleValueType();
9067
9068   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9069     return LowerZERO_EXTEND_AVX512(Op, DAG);
9070
9071   if (Subtarget->hasFp256()) {
9072     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9073     if (Res.getNode())
9074       return Res;
9075   }
9076
9077   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9078          VT.getVectorNumElements() != SVT.getVectorNumElements());
9079   return SDValue();
9080 }
9081
9082 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9083   SDLoc DL(Op);
9084   MVT VT = Op.getSimpleValueType();
9085   SDValue In = Op.getOperand(0);
9086   MVT InVT = In.getSimpleValueType();
9087
9088   if (VT == MVT::i1) {
9089     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9090            "Invalid scalar TRUNCATE operation");
9091     if (InVT == MVT::i32)
9092       return SDValue();
9093     if (InVT.getSizeInBits() == 64)
9094       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9095     else if (InVT.getSizeInBits() < 32)
9096       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9097     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9098   }
9099   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9100          "Invalid TRUNCATE operation");
9101
9102   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9103     if (VT.getVectorElementType().getSizeInBits() >=8)
9104       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9105
9106     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9107     unsigned NumElts = InVT.getVectorNumElements();
9108     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9109     if (InVT.getSizeInBits() < 512) {
9110       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9111       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9112       InVT = ExtVT;
9113     }
9114     
9115     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9116     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9117     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9118     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9119     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9120                            MachinePointerInfo::getConstantPool(),
9121                            false, false, false, Alignment);
9122     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9123     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9124     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9125   }
9126
9127   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9128     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9129     if (Subtarget->hasInt256()) {
9130       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9131       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9132       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9133                                 ShufMask);
9134       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9135                          DAG.getIntPtrConstant(0));
9136     }
9137
9138     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9139                                DAG.getIntPtrConstant(0));
9140     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9141                                DAG.getIntPtrConstant(2));
9142     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9143     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9144     static const int ShufMask[] = {0, 2, 4, 6};
9145     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9146   }
9147
9148   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9149     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9150     if (Subtarget->hasInt256()) {
9151       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9152
9153       SmallVector<SDValue,32> pshufbMask;
9154       for (unsigned i = 0; i < 2; ++i) {
9155         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9156         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9157         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9158         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9159         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9160         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9161         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9162         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9163         for (unsigned j = 0; j < 8; ++j)
9164           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9165       }
9166       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9167                                &pshufbMask[0], 32);
9168       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9169       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9170
9171       static const int ShufMask[] = {0,  2,  -1,  -1};
9172       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9173                                 &ShufMask[0]);
9174       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9175                        DAG.getIntPtrConstant(0));
9176       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9177     }
9178
9179     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9180                                DAG.getIntPtrConstant(0));
9181
9182     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9183                                DAG.getIntPtrConstant(4));
9184
9185     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9186     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9187
9188     // The PSHUFB mask:
9189     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9190                                    -1, -1, -1, -1, -1, -1, -1, -1};
9191
9192     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9193     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9194     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9195
9196     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9197     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9198
9199     // The MOVLHPS Mask:
9200     static const int ShufMask2[] = {0, 1, 4, 5};
9201     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9202     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9203   }
9204
9205   // Handle truncation of V256 to V128 using shuffles.
9206   if (!VT.is128BitVector() || !InVT.is256BitVector())
9207     return SDValue();
9208
9209   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9210
9211   unsigned NumElems = VT.getVectorNumElements();
9212   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9213
9214   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9215   // Prepare truncation shuffle mask
9216   for (unsigned i = 0; i != NumElems; ++i)
9217     MaskVec[i] = i * 2;
9218   SDValue V = DAG.getVectorShuffle(NVT, DL,
9219                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9220                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9221   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9222                      DAG.getIntPtrConstant(0));
9223 }
9224
9225 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9226                                            SelectionDAG &DAG) const {
9227   MVT VT = Op.getSimpleValueType();
9228   if (VT.isVector()) {
9229     if (VT == MVT::v8i16)
9230       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9231                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9232                                      MVT::v8i32, Op.getOperand(0)));
9233     return SDValue();
9234   }
9235
9236   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9237     /*IsSigned=*/ true, /*IsReplace=*/ false);
9238   SDValue FIST = Vals.first, StackSlot = Vals.second;
9239   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9240   if (FIST.getNode() == 0) return Op;
9241
9242   if (StackSlot.getNode())
9243     // Load the result.
9244     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9245                        FIST, StackSlot, MachinePointerInfo(),
9246                        false, false, false, 0);
9247
9248   // The node is the result.
9249   return FIST;
9250 }
9251
9252 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9253                                            SelectionDAG &DAG) const {
9254   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9255     /*IsSigned=*/ false, /*IsReplace=*/ false);
9256   SDValue FIST = Vals.first, StackSlot = Vals.second;
9257   assert(FIST.getNode() && "Unexpected failure");
9258
9259   if (StackSlot.getNode())
9260     // Load the result.
9261     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9262                        FIST, StackSlot, MachinePointerInfo(),
9263                        false, false, false, 0);
9264
9265   // The node is the result.
9266   return FIST;
9267 }
9268
9269 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9270   SDLoc DL(Op);
9271   MVT VT = Op.getSimpleValueType();
9272   SDValue In = Op.getOperand(0);
9273   MVT SVT = In.getSimpleValueType();
9274
9275   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9276
9277   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9278                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9279                                  In, DAG.getUNDEF(SVT)));
9280 }
9281
9282 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9283   LLVMContext *Context = DAG.getContext();
9284   SDLoc dl(Op);
9285   MVT VT = Op.getSimpleValueType();
9286   MVT EltVT = VT;
9287   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9288   if (VT.isVector()) {
9289     EltVT = VT.getVectorElementType();
9290     NumElts = VT.getVectorNumElements();
9291   }
9292   Constant *C;
9293   if (EltVT == MVT::f64)
9294     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9295                                           APInt(64, ~(1ULL << 63))));
9296   else
9297     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9298                                           APInt(32, ~(1U << 31))));
9299   C = ConstantVector::getSplat(NumElts, C);
9300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9301   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9302   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9303   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9304                              MachinePointerInfo::getConstantPool(),
9305                              false, false, false, Alignment);
9306   if (VT.isVector()) {
9307     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9308     return DAG.getNode(ISD::BITCAST, dl, VT,
9309                        DAG.getNode(ISD::AND, dl, ANDVT,
9310                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9311                                                Op.getOperand(0)),
9312                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9313   }
9314   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9315 }
9316
9317 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9318   LLVMContext *Context = DAG.getContext();
9319   SDLoc dl(Op);
9320   MVT VT = Op.getSimpleValueType();
9321   MVT EltVT = VT;
9322   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9323   if (VT.isVector()) {
9324     EltVT = VT.getVectorElementType();
9325     NumElts = VT.getVectorNumElements();
9326   }
9327   Constant *C;
9328   if (EltVT == MVT::f64)
9329     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9330                                           APInt(64, 1ULL << 63)));
9331   else
9332     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9333                                           APInt(32, 1U << 31)));
9334   C = ConstantVector::getSplat(NumElts, C);
9335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9336   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9337   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9338   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9339                              MachinePointerInfo::getConstantPool(),
9340                              false, false, false, Alignment);
9341   if (VT.isVector()) {
9342     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9343     return DAG.getNode(ISD::BITCAST, dl, VT,
9344                        DAG.getNode(ISD::XOR, dl, XORVT,
9345                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9346                                                Op.getOperand(0)),
9347                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9348   }
9349
9350   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9351 }
9352
9353 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9355   LLVMContext *Context = DAG.getContext();
9356   SDValue Op0 = Op.getOperand(0);
9357   SDValue Op1 = Op.getOperand(1);
9358   SDLoc dl(Op);
9359   MVT VT = Op.getSimpleValueType();
9360   MVT SrcVT = Op1.getSimpleValueType();
9361
9362   // If second operand is smaller, extend it first.
9363   if (SrcVT.bitsLT(VT)) {
9364     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9365     SrcVT = VT;
9366   }
9367   // And if it is bigger, shrink it first.
9368   if (SrcVT.bitsGT(VT)) {
9369     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9370     SrcVT = VT;
9371   }
9372
9373   // At this point the operands and the result should have the same
9374   // type, and that won't be f80 since that is not custom lowered.
9375
9376   // First get the sign bit of second operand.
9377   SmallVector<Constant*,4> CV;
9378   if (SrcVT == MVT::f64) {
9379     const fltSemantics &Sem = APFloat::IEEEdouble;
9380     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9381     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9382   } else {
9383     const fltSemantics &Sem = APFloat::IEEEsingle;
9384     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9385     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9386     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9387     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9388   }
9389   Constant *C = ConstantVector::get(CV);
9390   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9391   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9392                               MachinePointerInfo::getConstantPool(),
9393                               false, false, false, 16);
9394   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9395
9396   // Shift sign bit right or left if the two operands have different types.
9397   if (SrcVT.bitsGT(VT)) {
9398     // Op0 is MVT::f32, Op1 is MVT::f64.
9399     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9400     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9401                           DAG.getConstant(32, MVT::i32));
9402     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9403     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9404                           DAG.getIntPtrConstant(0));
9405   }
9406
9407   // Clear first operand sign bit.
9408   CV.clear();
9409   if (VT == MVT::f64) {
9410     const fltSemantics &Sem = APFloat::IEEEdouble;
9411     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9412                                                    APInt(64, ~(1ULL << 63)))));
9413     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9414   } else {
9415     const fltSemantics &Sem = APFloat::IEEEsingle;
9416     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9417                                                    APInt(32, ~(1U << 31)))));
9418     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9419     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9420     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9421   }
9422   C = ConstantVector::get(CV);
9423   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9424   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9425                               MachinePointerInfo::getConstantPool(),
9426                               false, false, false, 16);
9427   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9428
9429   // Or the value with the sign bit.
9430   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9431 }
9432
9433 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9434   SDValue N0 = Op.getOperand(0);
9435   SDLoc dl(Op);
9436   MVT VT = Op.getSimpleValueType();
9437
9438   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9439   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9440                                   DAG.getConstant(1, VT));
9441   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9442 }
9443
9444 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9445 //
9446 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9447                                       SelectionDAG &DAG) {
9448   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9449
9450   if (!Subtarget->hasSSE41())
9451     return SDValue();
9452
9453   if (!Op->hasOneUse())
9454     return SDValue();
9455
9456   SDNode *N = Op.getNode();
9457   SDLoc DL(N);
9458
9459   SmallVector<SDValue, 8> Opnds;
9460   DenseMap<SDValue, unsigned> VecInMap;
9461   EVT VT = MVT::Other;
9462
9463   // Recognize a special case where a vector is casted into wide integer to
9464   // test all 0s.
9465   Opnds.push_back(N->getOperand(0));
9466   Opnds.push_back(N->getOperand(1));
9467
9468   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9469     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9470     // BFS traverse all OR'd operands.
9471     if (I->getOpcode() == ISD::OR) {
9472       Opnds.push_back(I->getOperand(0));
9473       Opnds.push_back(I->getOperand(1));
9474       // Re-evaluate the number of nodes to be traversed.
9475       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9476       continue;
9477     }
9478
9479     // Quit if a non-EXTRACT_VECTOR_ELT
9480     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9481       return SDValue();
9482
9483     // Quit if without a constant index.
9484     SDValue Idx = I->getOperand(1);
9485     if (!isa<ConstantSDNode>(Idx))
9486       return SDValue();
9487
9488     SDValue ExtractedFromVec = I->getOperand(0);
9489     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9490     if (M == VecInMap.end()) {
9491       VT = ExtractedFromVec.getValueType();
9492       // Quit if not 128/256-bit vector.
9493       if (!VT.is128BitVector() && !VT.is256BitVector())
9494         return SDValue();
9495       // Quit if not the same type.
9496       if (VecInMap.begin() != VecInMap.end() &&
9497           VT != VecInMap.begin()->first.getValueType())
9498         return SDValue();
9499       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9500     }
9501     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9502   }
9503
9504   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9505          "Not extracted from 128-/256-bit vector.");
9506
9507   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9508   SmallVector<SDValue, 8> VecIns;
9509
9510   for (DenseMap<SDValue, unsigned>::const_iterator
9511         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9512     // Quit if not all elements are used.
9513     if (I->second != FullMask)
9514       return SDValue();
9515     VecIns.push_back(I->first);
9516   }
9517
9518   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9519
9520   // Cast all vectors into TestVT for PTEST.
9521   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9522     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9523
9524   // If more than one full vectors are evaluated, OR them first before PTEST.
9525   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9526     // Each iteration will OR 2 nodes and append the result until there is only
9527     // 1 node left, i.e. the final OR'd value of all vectors.
9528     SDValue LHS = VecIns[Slot];
9529     SDValue RHS = VecIns[Slot + 1];
9530     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9531   }
9532
9533   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9534                      VecIns.back(), VecIns.back());
9535 }
9536
9537 /// Emit nodes that will be selected as "test Op0,Op0", or something
9538 /// equivalent.
9539 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9540                                     SelectionDAG &DAG) const {
9541   SDLoc dl(Op);
9542
9543   if (Op.getValueType() == MVT::i1)
9544     // KORTEST instruction should be selected
9545     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9546                        DAG.getConstant(0, Op.getValueType()));
9547
9548   // CF and OF aren't always set the way we want. Determine which
9549   // of these we need.
9550   bool NeedCF = false;
9551   bool NeedOF = false;
9552   switch (X86CC) {
9553   default: break;
9554   case X86::COND_A: case X86::COND_AE:
9555   case X86::COND_B: case X86::COND_BE:
9556     NeedCF = true;
9557     break;
9558   case X86::COND_G: case X86::COND_GE:
9559   case X86::COND_L: case X86::COND_LE:
9560   case X86::COND_O: case X86::COND_NO:
9561     NeedOF = true;
9562     break;
9563   }
9564   // See if we can use the EFLAGS value from the operand instead of
9565   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9566   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9567   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9568     // Emit a CMP with 0, which is the TEST pattern.
9569     //if (Op.getValueType() == MVT::i1)
9570     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9571     //                     DAG.getConstant(0, MVT::i1));
9572     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9573                        DAG.getConstant(0, Op.getValueType()));
9574   }
9575   unsigned Opcode = 0;
9576   unsigned NumOperands = 0;
9577
9578   // Truncate operations may prevent the merge of the SETCC instruction
9579   // and the arithmetic instruction before it. Attempt to truncate the operands
9580   // of the arithmetic instruction and use a reduced bit-width instruction.
9581   bool NeedTruncation = false;
9582   SDValue ArithOp = Op;
9583   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9584     SDValue Arith = Op->getOperand(0);
9585     // Both the trunc and the arithmetic op need to have one user each.
9586     if (Arith->hasOneUse())
9587       switch (Arith.getOpcode()) {
9588         default: break;
9589         case ISD::ADD:
9590         case ISD::SUB:
9591         case ISD::AND:
9592         case ISD::OR:
9593         case ISD::XOR: {
9594           NeedTruncation = true;
9595           ArithOp = Arith;
9596         }
9597       }
9598   }
9599
9600   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9601   // which may be the result of a CAST.  We use the variable 'Op', which is the
9602   // non-casted variable when we check for possible users.
9603   switch (ArithOp.getOpcode()) {
9604   case ISD::ADD:
9605     // Due to an isel shortcoming, be conservative if this add is likely to be
9606     // selected as part of a load-modify-store instruction. When the root node
9607     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9608     // uses of other nodes in the match, such as the ADD in this case. This
9609     // leads to the ADD being left around and reselected, with the result being
9610     // two adds in the output.  Alas, even if none our users are stores, that
9611     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9612     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9613     // climbing the DAG back to the root, and it doesn't seem to be worth the
9614     // effort.
9615     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9616          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9617       if (UI->getOpcode() != ISD::CopyToReg &&
9618           UI->getOpcode() != ISD::SETCC &&
9619           UI->getOpcode() != ISD::STORE)
9620         goto default_case;
9621
9622     if (ConstantSDNode *C =
9623         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9624       // An add of one will be selected as an INC.
9625       if (C->getAPIntValue() == 1) {
9626         Opcode = X86ISD::INC;
9627         NumOperands = 1;
9628         break;
9629       }
9630
9631       // An add of negative one (subtract of one) will be selected as a DEC.
9632       if (C->getAPIntValue().isAllOnesValue()) {
9633         Opcode = X86ISD::DEC;
9634         NumOperands = 1;
9635         break;
9636       }
9637     }
9638
9639     // Otherwise use a regular EFLAGS-setting add.
9640     Opcode = X86ISD::ADD;
9641     NumOperands = 2;
9642     break;
9643   case ISD::AND: {
9644     // If the primary and result isn't used, don't bother using X86ISD::AND,
9645     // because a TEST instruction will be better.
9646     bool NonFlagUse = false;
9647     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9648            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9649       SDNode *User = *UI;
9650       unsigned UOpNo = UI.getOperandNo();
9651       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9652         // Look pass truncate.
9653         UOpNo = User->use_begin().getOperandNo();
9654         User = *User->use_begin();
9655       }
9656
9657       if (User->getOpcode() != ISD::BRCOND &&
9658           User->getOpcode() != ISD::SETCC &&
9659           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9660         NonFlagUse = true;
9661         break;
9662       }
9663     }
9664
9665     if (!NonFlagUse)
9666       break;
9667   }
9668     // FALL THROUGH
9669   case ISD::SUB:
9670   case ISD::OR:
9671   case ISD::XOR:
9672     // Due to the ISEL shortcoming noted above, be conservative if this op is
9673     // likely to be selected as part of a load-modify-store instruction.
9674     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9675            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9676       if (UI->getOpcode() == ISD::STORE)
9677         goto default_case;
9678
9679     // Otherwise use a regular EFLAGS-setting instruction.
9680     switch (ArithOp.getOpcode()) {
9681     default: llvm_unreachable("unexpected operator!");
9682     case ISD::SUB: Opcode = X86ISD::SUB; break;
9683     case ISD::XOR: Opcode = X86ISD::XOR; break;
9684     case ISD::AND: Opcode = X86ISD::AND; break;
9685     case ISD::OR: {
9686       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9687         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9688         if (EFLAGS.getNode())
9689           return EFLAGS;
9690       }
9691       Opcode = X86ISD::OR;
9692       break;
9693     }
9694     }
9695
9696     NumOperands = 2;
9697     break;
9698   case X86ISD::ADD:
9699   case X86ISD::SUB:
9700   case X86ISD::INC:
9701   case X86ISD::DEC:
9702   case X86ISD::OR:
9703   case X86ISD::XOR:
9704   case X86ISD::AND:
9705     return SDValue(Op.getNode(), 1);
9706   default:
9707   default_case:
9708     break;
9709   }
9710
9711   // If we found that truncation is beneficial, perform the truncation and
9712   // update 'Op'.
9713   if (NeedTruncation) {
9714     EVT VT = Op.getValueType();
9715     SDValue WideVal = Op->getOperand(0);
9716     EVT WideVT = WideVal.getValueType();
9717     unsigned ConvertedOp = 0;
9718     // Use a target machine opcode to prevent further DAGCombine
9719     // optimizations that may separate the arithmetic operations
9720     // from the setcc node.
9721     switch (WideVal.getOpcode()) {
9722       default: break;
9723       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9724       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9725       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9726       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9727       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9728     }
9729
9730     if (ConvertedOp) {
9731       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9732       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9733         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9734         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9735         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9736       }
9737     }
9738   }
9739
9740   if (Opcode == 0)
9741     // Emit a CMP with 0, which is the TEST pattern.
9742     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9743                        DAG.getConstant(0, Op.getValueType()));
9744
9745   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9746   SmallVector<SDValue, 4> Ops;
9747   for (unsigned i = 0; i != NumOperands; ++i)
9748     Ops.push_back(Op.getOperand(i));
9749
9750   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9751   DAG.ReplaceAllUsesWith(Op, New);
9752   return SDValue(New.getNode(), 1);
9753 }
9754
9755 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9756 /// equivalent.
9757 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9758                                    SelectionDAG &DAG) const {
9759   SDLoc dl(Op0);
9760   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9761     if (C->getAPIntValue() == 0)
9762       return EmitTest(Op0, X86CC, DAG);
9763
9764      if (Op0.getValueType() == MVT::i1)
9765        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9766   }
9767  
9768   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9769        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9770     // Do the comparison at i32 if it's smaller. This avoids subregister
9771     // aliasing issues. Keep the smaller reference if we're optimizing for
9772     // size, however, as that'll allow better folding of memory operations.
9773     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9774         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9775              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9776       unsigned ExtendOp =
9777           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9778       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9779       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9780     }
9781     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9782     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9783     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9784                               Op0, Op1);
9785     return SDValue(Sub.getNode(), 1);
9786   }
9787   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9788 }
9789
9790 /// Convert a comparison if required by the subtarget.
9791 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9792                                                  SelectionDAG &DAG) const {
9793   // If the subtarget does not support the FUCOMI instruction, floating-point
9794   // comparisons have to be converted.
9795   if (Subtarget->hasCMov() ||
9796       Cmp.getOpcode() != X86ISD::CMP ||
9797       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9798       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9799     return Cmp;
9800
9801   // The instruction selector will select an FUCOM instruction instead of
9802   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9803   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9804   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9805   SDLoc dl(Cmp);
9806   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9807   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9808   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9809                             DAG.getConstant(8, MVT::i8));
9810   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9811   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9812 }
9813
9814 static bool isAllOnes(SDValue V) {
9815   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9816   return C && C->isAllOnesValue();
9817 }
9818
9819 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9820 /// if it's possible.
9821 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9822                                      SDLoc dl, SelectionDAG &DAG) const {
9823   SDValue Op0 = And.getOperand(0);
9824   SDValue Op1 = And.getOperand(1);
9825   if (Op0.getOpcode() == ISD::TRUNCATE)
9826     Op0 = Op0.getOperand(0);
9827   if (Op1.getOpcode() == ISD::TRUNCATE)
9828     Op1 = Op1.getOperand(0);
9829
9830   SDValue LHS, RHS;
9831   if (Op1.getOpcode() == ISD::SHL)
9832     std::swap(Op0, Op1);
9833   if (Op0.getOpcode() == ISD::SHL) {
9834     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9835       if (And00C->getZExtValue() == 1) {
9836         // If we looked past a truncate, check that it's only truncating away
9837         // known zeros.
9838         unsigned BitWidth = Op0.getValueSizeInBits();
9839         unsigned AndBitWidth = And.getValueSizeInBits();
9840         if (BitWidth > AndBitWidth) {
9841           APInt Zeros, Ones;
9842           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9843           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9844             return SDValue();
9845         }
9846         LHS = Op1;
9847         RHS = Op0.getOperand(1);
9848       }
9849   } else if (Op1.getOpcode() == ISD::Constant) {
9850     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9851     uint64_t AndRHSVal = AndRHS->getZExtValue();
9852     SDValue AndLHS = Op0;
9853
9854     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9855       LHS = AndLHS.getOperand(0);
9856       RHS = AndLHS.getOperand(1);
9857     }
9858
9859     // Use BT if the immediate can't be encoded in a TEST instruction.
9860     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9861       LHS = AndLHS;
9862       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9863     }
9864   }
9865
9866   if (LHS.getNode()) {
9867     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9868     // instruction.  Since the shift amount is in-range-or-undefined, we know
9869     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9870     // the encoding for the i16 version is larger than the i32 version.
9871     // Also promote i16 to i32 for performance / code size reason.
9872     if (LHS.getValueType() == MVT::i8 ||
9873         LHS.getValueType() == MVT::i16)
9874       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9875
9876     // If the operand types disagree, extend the shift amount to match.  Since
9877     // BT ignores high bits (like shifts) we can use anyextend.
9878     if (LHS.getValueType() != RHS.getValueType())
9879       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9880
9881     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9882     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9883     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9884                        DAG.getConstant(Cond, MVT::i8), BT);
9885   }
9886
9887   return SDValue();
9888 }
9889
9890 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9891 /// mask CMPs.
9892 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9893                               SDValue &Op1) {
9894   unsigned SSECC;
9895   bool Swap = false;
9896
9897   // SSE Condition code mapping:
9898   //  0 - EQ
9899   //  1 - LT
9900   //  2 - LE
9901   //  3 - UNORD
9902   //  4 - NEQ
9903   //  5 - NLT
9904   //  6 - NLE
9905   //  7 - ORD
9906   switch (SetCCOpcode) {
9907   default: llvm_unreachable("Unexpected SETCC condition");
9908   case ISD::SETOEQ:
9909   case ISD::SETEQ:  SSECC = 0; break;
9910   case ISD::SETOGT:
9911   case ISD::SETGT:  Swap = true; // Fallthrough
9912   case ISD::SETLT:
9913   case ISD::SETOLT: SSECC = 1; break;
9914   case ISD::SETOGE:
9915   case ISD::SETGE:  Swap = true; // Fallthrough
9916   case ISD::SETLE:
9917   case ISD::SETOLE: SSECC = 2; break;
9918   case ISD::SETUO:  SSECC = 3; break;
9919   case ISD::SETUNE:
9920   case ISD::SETNE:  SSECC = 4; break;
9921   case ISD::SETULE: Swap = true; // Fallthrough
9922   case ISD::SETUGE: SSECC = 5; break;
9923   case ISD::SETULT: Swap = true; // Fallthrough
9924   case ISD::SETUGT: SSECC = 6; break;
9925   case ISD::SETO:   SSECC = 7; break;
9926   case ISD::SETUEQ:
9927   case ISD::SETONE: SSECC = 8; break;
9928   }
9929   if (Swap)
9930     std::swap(Op0, Op1);
9931
9932   return SSECC;
9933 }
9934
9935 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9936 // ones, and then concatenate the result back.
9937 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9938   MVT VT = Op.getSimpleValueType();
9939
9940   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9941          "Unsupported value type for operation");
9942
9943   unsigned NumElems = VT.getVectorNumElements();
9944   SDLoc dl(Op);
9945   SDValue CC = Op.getOperand(2);
9946
9947   // Extract the LHS vectors
9948   SDValue LHS = Op.getOperand(0);
9949   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9950   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9951
9952   // Extract the RHS vectors
9953   SDValue RHS = Op.getOperand(1);
9954   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9955   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9956
9957   // Issue the operation on the smaller types and concatenate the result back
9958   MVT EltVT = VT.getVectorElementType();
9959   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9960   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9961                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9962                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9963 }
9964
9965 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
9966                                      const X86Subtarget *Subtarget) {
9967   SDValue Op0 = Op.getOperand(0);
9968   SDValue Op1 = Op.getOperand(1);
9969   SDValue CC = Op.getOperand(2);
9970   MVT VT = Op.getSimpleValueType();
9971   SDLoc dl(Op);
9972
9973   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9974          Op.getValueType().getScalarType() == MVT::i1 &&
9975          "Cannot set masked compare for this operation");
9976
9977   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9978   unsigned  Opc = 0;
9979   bool Unsigned = false;
9980   bool Swap = false;
9981   unsigned SSECC;
9982   switch (SetCCOpcode) {
9983   default: llvm_unreachable("Unexpected SETCC condition");
9984   case ISD::SETNE:  SSECC = 4; break;
9985   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
9986   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
9987   case ISD::SETLT:  Swap = true; //fall-through
9988   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
9989   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
9990   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
9991   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
9992   case ISD::SETULE: Unsigned = true; //fall-through
9993   case ISD::SETLE:  SSECC = 2; break;
9994   }
9995
9996   if (Swap)
9997     std::swap(Op0, Op1);
9998   if (Opc)
9999     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10000   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10001   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10002                      DAG.getConstant(SSECC, MVT::i8));
10003 }
10004
10005 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10006 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10007 /// return an empty value.
10008 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10009 {
10010   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10011   if (!BV)
10012     return SDValue();
10013
10014   MVT VT = Op1.getSimpleValueType();
10015   MVT EVT = VT.getVectorElementType();
10016   unsigned n = VT.getVectorNumElements();
10017   SmallVector<SDValue, 8> ULTOp1;
10018
10019   for (unsigned i = 0; i < n; ++i) {
10020     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10021     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10022       return SDValue();
10023
10024     // Avoid underflow.
10025     APInt Val = Elt->getAPIntValue();
10026     if (Val == 0)
10027       return SDValue();
10028
10029     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10030   }
10031
10032   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10033                      ULTOp1.size());
10034 }
10035
10036 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10037                            SelectionDAG &DAG) {
10038   SDValue Op0 = Op.getOperand(0);
10039   SDValue Op1 = Op.getOperand(1);
10040   SDValue CC = Op.getOperand(2);
10041   MVT VT = Op.getSimpleValueType();
10042   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10043   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10044   SDLoc dl(Op);
10045
10046   if (isFP) {
10047 #ifndef NDEBUG
10048     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10049     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10050 #endif
10051
10052     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10053     unsigned Opc = X86ISD::CMPP;
10054     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10055       assert(VT.getVectorNumElements() <= 16);
10056       Opc = X86ISD::CMPM;
10057     }
10058     // In the two special cases we can't handle, emit two comparisons.
10059     if (SSECC == 8) {
10060       unsigned CC0, CC1;
10061       unsigned CombineOpc;
10062       if (SetCCOpcode == ISD::SETUEQ) {
10063         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10064       } else {
10065         assert(SetCCOpcode == ISD::SETONE);
10066         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10067       }
10068
10069       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10070                                  DAG.getConstant(CC0, MVT::i8));
10071       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10072                                  DAG.getConstant(CC1, MVT::i8));
10073       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10074     }
10075     // Handle all other FP comparisons here.
10076     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10077                        DAG.getConstant(SSECC, MVT::i8));
10078   }
10079
10080   // Break 256-bit integer vector compare into smaller ones.
10081   if (VT.is256BitVector() && !Subtarget->hasInt256())
10082     return Lower256IntVSETCC(Op, DAG);
10083
10084   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10085   EVT OpVT = Op1.getValueType();
10086   if (Subtarget->hasAVX512()) {
10087     if (Op1.getValueType().is512BitVector() ||
10088         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10089       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10090
10091     // In AVX-512 architecture setcc returns mask with i1 elements,
10092     // But there is no compare instruction for i8 and i16 elements.
10093     // We are not talking about 512-bit operands in this case, these
10094     // types are illegal.
10095     if (MaskResult &&
10096         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10097          OpVT.getVectorElementType().getSizeInBits() >= 8))
10098       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10099                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10100   }
10101
10102   // We are handling one of the integer comparisons here.  Since SSE only has
10103   // GT and EQ comparisons for integer, swapping operands and multiple
10104   // operations may be required for some comparisons.
10105   unsigned Opc;
10106   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10107   bool Subus = false;
10108
10109   switch (SetCCOpcode) {
10110   default: llvm_unreachable("Unexpected SETCC condition");
10111   case ISD::SETNE:  Invert = true;
10112   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10113   case ISD::SETLT:  Swap = true;
10114   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10115   case ISD::SETGE:  Swap = true;
10116   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10117                     Invert = true; break;
10118   case ISD::SETULT: Swap = true;
10119   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10120                     FlipSigns = true; break;
10121   case ISD::SETUGE: Swap = true;
10122   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10123                     FlipSigns = true; Invert = true; break;
10124   }
10125
10126   // Special case: Use min/max operations for SETULE/SETUGE
10127   MVT VET = VT.getVectorElementType();
10128   bool hasMinMax =
10129        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10130     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10131
10132   if (hasMinMax) {
10133     switch (SetCCOpcode) {
10134     default: break;
10135     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10136     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10137     }
10138
10139     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10140   }
10141
10142   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10143   if (!MinMax && hasSubus) {
10144     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10145     // Op0 u<= Op1:
10146     //   t = psubus Op0, Op1
10147     //   pcmpeq t, <0..0>
10148     switch (SetCCOpcode) {
10149     default: break;
10150     case ISD::SETULT: {
10151       // If the comparison is against a constant we can turn this into a
10152       // setule.  With psubus, setule does not require a swap.  This is
10153       // beneficial because the constant in the register is no longer
10154       // destructed as the destination so it can be hoisted out of a loop.
10155       // Only do this pre-AVX since vpcmp* is no longer destructive.
10156       if (Subtarget->hasAVX())
10157         break;
10158       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10159       if (ULEOp1.getNode()) {
10160         Op1 = ULEOp1;
10161         Subus = true; Invert = false; Swap = false;
10162       }
10163       break;
10164     }
10165     // Psubus is better than flip-sign because it requires no inversion.
10166     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10167     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10168     }
10169
10170     if (Subus) {
10171       Opc = X86ISD::SUBUS;
10172       FlipSigns = false;
10173     }
10174   }
10175
10176   if (Swap)
10177     std::swap(Op0, Op1);
10178
10179   // Check that the operation in question is available (most are plain SSE2,
10180   // but PCMPGTQ and PCMPEQQ have different requirements).
10181   if (VT == MVT::v2i64) {
10182     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10183       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10184
10185       // First cast everything to the right type.
10186       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10187       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10188
10189       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10190       // bits of the inputs before performing those operations. The lower
10191       // compare is always unsigned.
10192       SDValue SB;
10193       if (FlipSigns) {
10194         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10195       } else {
10196         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10197         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10198         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10199                          Sign, Zero, Sign, Zero);
10200       }
10201       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10202       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10203
10204       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10205       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10206       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10207
10208       // Create masks for only the low parts/high parts of the 64 bit integers.
10209       static const int MaskHi[] = { 1, 1, 3, 3 };
10210       static const int MaskLo[] = { 0, 0, 2, 2 };
10211       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10212       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10213       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10214
10215       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10216       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10217
10218       if (Invert)
10219         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10220
10221       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10222     }
10223
10224     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10225       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10226       // pcmpeqd + pshufd + pand.
10227       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10228
10229       // First cast everything to the right type.
10230       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10231       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10232
10233       // Do the compare.
10234       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10235
10236       // Make sure the lower and upper halves are both all-ones.
10237       static const int Mask[] = { 1, 0, 3, 2 };
10238       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10239       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10240
10241       if (Invert)
10242         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10243
10244       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10245     }
10246   }
10247
10248   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10249   // bits of the inputs before performing those operations.
10250   if (FlipSigns) {
10251     EVT EltVT = VT.getVectorElementType();
10252     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10253     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10254     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10255   }
10256
10257   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10258
10259   // If the logical-not of the result is required, perform that now.
10260   if (Invert)
10261     Result = DAG.getNOT(dl, Result, VT);
10262
10263   if (MinMax)
10264     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10265
10266   if (Subus)
10267     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10268                          getZeroVector(VT, Subtarget, DAG, dl));
10269
10270   return Result;
10271 }
10272
10273 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10274
10275   MVT VT = Op.getSimpleValueType();
10276
10277   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10278
10279   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10280          && "SetCC type must be 8-bit or 1-bit integer");
10281   SDValue Op0 = Op.getOperand(0);
10282   SDValue Op1 = Op.getOperand(1);
10283   SDLoc dl(Op);
10284   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10285
10286   // Optimize to BT if possible.
10287   // Lower (X & (1 << N)) == 0 to BT(X, N).
10288   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10289   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10290   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10291       Op1.getOpcode() == ISD::Constant &&
10292       cast<ConstantSDNode>(Op1)->isNullValue() &&
10293       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10294     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10295     if (NewSetCC.getNode())
10296       return NewSetCC;
10297   }
10298
10299   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10300   // these.
10301   if (Op1.getOpcode() == ISD::Constant &&
10302       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10303        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10304       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10305
10306     // If the input is a setcc, then reuse the input setcc or use a new one with
10307     // the inverted condition.
10308     if (Op0.getOpcode() == X86ISD::SETCC) {
10309       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10310       bool Invert = (CC == ISD::SETNE) ^
10311         cast<ConstantSDNode>(Op1)->isNullValue();
10312       if (!Invert)
10313         return Op0;
10314
10315       CCode = X86::GetOppositeBranchCondition(CCode);
10316       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10317                                   DAG.getConstant(CCode, MVT::i8),
10318                                   Op0.getOperand(1));
10319       if (VT == MVT::i1)
10320         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10321       return SetCC;
10322     }
10323   }
10324   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10325       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10326       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10327
10328     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10329     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10330   }
10331
10332   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10333   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10334   if (X86CC == X86::COND_INVALID)
10335     return SDValue();
10336
10337   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10338   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10339   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10340                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10341   if (VT == MVT::i1)
10342     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10343   return SetCC;
10344 }
10345
10346 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10347 static bool isX86LogicalCmp(SDValue Op) {
10348   unsigned Opc = Op.getNode()->getOpcode();
10349   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10350       Opc == X86ISD::SAHF)
10351     return true;
10352   if (Op.getResNo() == 1 &&
10353       (Opc == X86ISD::ADD ||
10354        Opc == X86ISD::SUB ||
10355        Opc == X86ISD::ADC ||
10356        Opc == X86ISD::SBB ||
10357        Opc == X86ISD::SMUL ||
10358        Opc == X86ISD::UMUL ||
10359        Opc == X86ISD::INC ||
10360        Opc == X86ISD::DEC ||
10361        Opc == X86ISD::OR ||
10362        Opc == X86ISD::XOR ||
10363        Opc == X86ISD::AND))
10364     return true;
10365
10366   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10367     return true;
10368
10369   return false;
10370 }
10371
10372 static bool isZero(SDValue V) {
10373   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10374   return C && C->isNullValue();
10375 }
10376
10377 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10378   if (V.getOpcode() != ISD::TRUNCATE)
10379     return false;
10380
10381   SDValue VOp0 = V.getOperand(0);
10382   unsigned InBits = VOp0.getValueSizeInBits();
10383   unsigned Bits = V.getValueSizeInBits();
10384   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10385 }
10386
10387 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10388   bool addTest = true;
10389   SDValue Cond  = Op.getOperand(0);
10390   SDValue Op1 = Op.getOperand(1);
10391   SDValue Op2 = Op.getOperand(2);
10392   SDLoc DL(Op);
10393   EVT VT = Op1.getValueType();
10394   SDValue CC;
10395
10396   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10397   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10398   // sequence later on.
10399   if (Cond.getOpcode() == ISD::SETCC &&
10400       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10401        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10402       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10403     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10404     int SSECC = translateX86FSETCC(
10405         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10406
10407     if (SSECC != 8) {
10408       if (Subtarget->hasAVX512()) {
10409         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10410                                   DAG.getConstant(SSECC, MVT::i8));
10411         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10412       }
10413       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10414                                 DAG.getConstant(SSECC, MVT::i8));
10415       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10416       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10417       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10418     }
10419   }
10420
10421   if (Cond.getOpcode() == ISD::SETCC) {
10422     SDValue NewCond = LowerSETCC(Cond, DAG);
10423     if (NewCond.getNode())
10424       Cond = NewCond;
10425   }
10426
10427   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10428   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10429   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10430   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10431   if (Cond.getOpcode() == X86ISD::SETCC &&
10432       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10433       isZero(Cond.getOperand(1).getOperand(1))) {
10434     SDValue Cmp = Cond.getOperand(1);
10435
10436     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10437
10438     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10439         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10440       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10441
10442       SDValue CmpOp0 = Cmp.getOperand(0);
10443       // Apply further optimizations for special cases
10444       // (select (x != 0), -1, 0) -> neg & sbb
10445       // (select (x == 0), 0, -1) -> neg & sbb
10446       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10447         if (YC->isNullValue() &&
10448             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10449           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10450           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10451                                     DAG.getConstant(0, CmpOp0.getValueType()),
10452                                     CmpOp0);
10453           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10454                                     DAG.getConstant(X86::COND_B, MVT::i8),
10455                                     SDValue(Neg.getNode(), 1));
10456           return Res;
10457         }
10458
10459       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10460                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10461       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10462
10463       SDValue Res =   // Res = 0 or -1.
10464         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10465                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10466
10467       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10468         Res = DAG.getNOT(DL, Res, Res.getValueType());
10469
10470       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10471       if (N2C == 0 || !N2C->isNullValue())
10472         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10473       return Res;
10474     }
10475   }
10476
10477   // Look past (and (setcc_carry (cmp ...)), 1).
10478   if (Cond.getOpcode() == ISD::AND &&
10479       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10480     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10481     if (C && C->getAPIntValue() == 1)
10482       Cond = Cond.getOperand(0);
10483   }
10484
10485   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10486   // setting operand in place of the X86ISD::SETCC.
10487   unsigned CondOpcode = Cond.getOpcode();
10488   if (CondOpcode == X86ISD::SETCC ||
10489       CondOpcode == X86ISD::SETCC_CARRY) {
10490     CC = Cond.getOperand(0);
10491
10492     SDValue Cmp = Cond.getOperand(1);
10493     unsigned Opc = Cmp.getOpcode();
10494     MVT VT = Op.getSimpleValueType();
10495
10496     bool IllegalFPCMov = false;
10497     if (VT.isFloatingPoint() && !VT.isVector() &&
10498         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10499       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10500
10501     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10502         Opc == X86ISD::BT) { // FIXME
10503       Cond = Cmp;
10504       addTest = false;
10505     }
10506   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10507              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10508              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10509               Cond.getOperand(0).getValueType() != MVT::i8)) {
10510     SDValue LHS = Cond.getOperand(0);
10511     SDValue RHS = Cond.getOperand(1);
10512     unsigned X86Opcode;
10513     unsigned X86Cond;
10514     SDVTList VTs;
10515     switch (CondOpcode) {
10516     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10517     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10518     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10519     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10520     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10521     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10522     default: llvm_unreachable("unexpected overflowing operator");
10523     }
10524     if (CondOpcode == ISD::UMULO)
10525       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10526                           MVT::i32);
10527     else
10528       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10529
10530     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10531
10532     if (CondOpcode == ISD::UMULO)
10533       Cond = X86Op.getValue(2);
10534     else
10535       Cond = X86Op.getValue(1);
10536
10537     CC = DAG.getConstant(X86Cond, MVT::i8);
10538     addTest = false;
10539   }
10540
10541   if (addTest) {
10542     // Look pass the truncate if the high bits are known zero.
10543     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10544         Cond = Cond.getOperand(0);
10545
10546     // We know the result of AND is compared against zero. Try to match
10547     // it to BT.
10548     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10549       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10550       if (NewSetCC.getNode()) {
10551         CC = NewSetCC.getOperand(0);
10552         Cond = NewSetCC.getOperand(1);
10553         addTest = false;
10554       }
10555     }
10556   }
10557
10558   if (addTest) {
10559     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10560     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10561   }
10562
10563   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10564   // a <  b ?  0 : -1 -> RES = setcc_carry
10565   // a >= b ? -1 :  0 -> RES = setcc_carry
10566   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10567   if (Cond.getOpcode() == X86ISD::SUB) {
10568     Cond = ConvertCmpIfNecessary(Cond, DAG);
10569     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10570
10571     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10572         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10573       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10574                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10575       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10576         return DAG.getNOT(DL, Res, Res.getValueType());
10577       return Res;
10578     }
10579   }
10580
10581   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10582   // widen the cmov and push the truncate through. This avoids introducing a new
10583   // branch during isel and doesn't add any extensions.
10584   if (Op.getValueType() == MVT::i8 &&
10585       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10586     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10587     if (T1.getValueType() == T2.getValueType() &&
10588         // Blacklist CopyFromReg to avoid partial register stalls.
10589         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10590       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10591       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10592       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10593     }
10594   }
10595
10596   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10597   // condition is true.
10598   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10599   SDValue Ops[] = { Op2, Op1, CC, Cond };
10600   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10601 }
10602
10603 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10604   MVT VT = Op->getSimpleValueType(0);
10605   SDValue In = Op->getOperand(0);
10606   MVT InVT = In.getSimpleValueType();
10607   SDLoc dl(Op);
10608
10609   unsigned int NumElts = VT.getVectorNumElements();
10610   if (NumElts != 8 && NumElts != 16)
10611     return SDValue();
10612
10613   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10614     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10615
10616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10617   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10618
10619   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10620   Constant *C = ConstantInt::get(*DAG.getContext(),
10621     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10622
10623   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10624   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10625   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10626                           MachinePointerInfo::getConstantPool(),
10627                           false, false, false, Alignment);
10628   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10629   if (VT.is512BitVector())
10630     return Brcst;
10631   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10632 }
10633
10634 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10635                                 SelectionDAG &DAG) {
10636   MVT VT = Op->getSimpleValueType(0);
10637   SDValue In = Op->getOperand(0);
10638   MVT InVT = In.getSimpleValueType();
10639   SDLoc dl(Op);
10640
10641   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10642     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10643
10644   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10645       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10646       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10647     return SDValue();
10648
10649   if (Subtarget->hasInt256())
10650     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10651
10652   // Optimize vectors in AVX mode
10653   // Sign extend  v8i16 to v8i32 and
10654   //              v4i32 to v4i64
10655   //
10656   // Divide input vector into two parts
10657   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10658   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10659   // concat the vectors to original VT
10660
10661   unsigned NumElems = InVT.getVectorNumElements();
10662   SDValue Undef = DAG.getUNDEF(InVT);
10663
10664   SmallVector<int,8> ShufMask1(NumElems, -1);
10665   for (unsigned i = 0; i != NumElems/2; ++i)
10666     ShufMask1[i] = i;
10667
10668   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10669
10670   SmallVector<int,8> ShufMask2(NumElems, -1);
10671   for (unsigned i = 0; i != NumElems/2; ++i)
10672     ShufMask2[i] = i + NumElems/2;
10673
10674   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10675
10676   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10677                                 VT.getVectorNumElements()/2);
10678
10679   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10680   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10681
10682   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10683 }
10684
10685 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10686 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10687 // from the AND / OR.
10688 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10689   Opc = Op.getOpcode();
10690   if (Opc != ISD::OR && Opc != ISD::AND)
10691     return false;
10692   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10693           Op.getOperand(0).hasOneUse() &&
10694           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10695           Op.getOperand(1).hasOneUse());
10696 }
10697
10698 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10699 // 1 and that the SETCC node has a single use.
10700 static bool isXor1OfSetCC(SDValue Op) {
10701   if (Op.getOpcode() != ISD::XOR)
10702     return false;
10703   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10704   if (N1C && N1C->getAPIntValue() == 1) {
10705     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10706       Op.getOperand(0).hasOneUse();
10707   }
10708   return false;
10709 }
10710
10711 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10712   bool addTest = true;
10713   SDValue Chain = Op.getOperand(0);
10714   SDValue Cond  = Op.getOperand(1);
10715   SDValue Dest  = Op.getOperand(2);
10716   SDLoc dl(Op);
10717   SDValue CC;
10718   bool Inverted = false;
10719
10720   if (Cond.getOpcode() == ISD::SETCC) {
10721     // Check for setcc([su]{add,sub,mul}o == 0).
10722     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10723         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10724         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10725         Cond.getOperand(0).getResNo() == 1 &&
10726         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10727          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10728          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10729          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10730          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10731          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10732       Inverted = true;
10733       Cond = Cond.getOperand(0);
10734     } else {
10735       SDValue NewCond = LowerSETCC(Cond, DAG);
10736       if (NewCond.getNode())
10737         Cond = NewCond;
10738     }
10739   }
10740 #if 0
10741   // FIXME: LowerXALUO doesn't handle these!!
10742   else if (Cond.getOpcode() == X86ISD::ADD  ||
10743            Cond.getOpcode() == X86ISD::SUB  ||
10744            Cond.getOpcode() == X86ISD::SMUL ||
10745            Cond.getOpcode() == X86ISD::UMUL)
10746     Cond = LowerXALUO(Cond, DAG);
10747 #endif
10748
10749   // Look pass (and (setcc_carry (cmp ...)), 1).
10750   if (Cond.getOpcode() == ISD::AND &&
10751       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10752     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10753     if (C && C->getAPIntValue() == 1)
10754       Cond = Cond.getOperand(0);
10755   }
10756
10757   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10758   // setting operand in place of the X86ISD::SETCC.
10759   unsigned CondOpcode = Cond.getOpcode();
10760   if (CondOpcode == X86ISD::SETCC ||
10761       CondOpcode == X86ISD::SETCC_CARRY) {
10762     CC = Cond.getOperand(0);
10763
10764     SDValue Cmp = Cond.getOperand(1);
10765     unsigned Opc = Cmp.getOpcode();
10766     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10767     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10768       Cond = Cmp;
10769       addTest = false;
10770     } else {
10771       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10772       default: break;
10773       case X86::COND_O:
10774       case X86::COND_B:
10775         // These can only come from an arithmetic instruction with overflow,
10776         // e.g. SADDO, UADDO.
10777         Cond = Cond.getNode()->getOperand(1);
10778         addTest = false;
10779         break;
10780       }
10781     }
10782   }
10783   CondOpcode = Cond.getOpcode();
10784   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10785       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10786       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10787        Cond.getOperand(0).getValueType() != MVT::i8)) {
10788     SDValue LHS = Cond.getOperand(0);
10789     SDValue RHS = Cond.getOperand(1);
10790     unsigned X86Opcode;
10791     unsigned X86Cond;
10792     SDVTList VTs;
10793     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10794     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10795     // X86ISD::INC).
10796     switch (CondOpcode) {
10797     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10798     case ISD::SADDO:
10799       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10800         if (C->isOne()) {
10801           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10802           break;
10803         }
10804       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10805     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10806     case ISD::SSUBO:
10807       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10808         if (C->isOne()) {
10809           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10810           break;
10811         }
10812       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10813     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10814     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10815     default: llvm_unreachable("unexpected overflowing operator");
10816     }
10817     if (Inverted)
10818       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10819     if (CondOpcode == ISD::UMULO)
10820       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10821                           MVT::i32);
10822     else
10823       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10824
10825     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10826
10827     if (CondOpcode == ISD::UMULO)
10828       Cond = X86Op.getValue(2);
10829     else
10830       Cond = X86Op.getValue(1);
10831
10832     CC = DAG.getConstant(X86Cond, MVT::i8);
10833     addTest = false;
10834   } else {
10835     unsigned CondOpc;
10836     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10837       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10838       if (CondOpc == ISD::OR) {
10839         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10840         // two branches instead of an explicit OR instruction with a
10841         // separate test.
10842         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10843             isX86LogicalCmp(Cmp)) {
10844           CC = Cond.getOperand(0).getOperand(0);
10845           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10846                               Chain, Dest, CC, Cmp);
10847           CC = Cond.getOperand(1).getOperand(0);
10848           Cond = Cmp;
10849           addTest = false;
10850         }
10851       } else { // ISD::AND
10852         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10853         // two branches instead of an explicit AND instruction with a
10854         // separate test. However, we only do this if this block doesn't
10855         // have a fall-through edge, because this requires an explicit
10856         // jmp when the condition is false.
10857         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10858             isX86LogicalCmp(Cmp) &&
10859             Op.getNode()->hasOneUse()) {
10860           X86::CondCode CCode =
10861             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10862           CCode = X86::GetOppositeBranchCondition(CCode);
10863           CC = DAG.getConstant(CCode, MVT::i8);
10864           SDNode *User = *Op.getNode()->use_begin();
10865           // Look for an unconditional branch following this conditional branch.
10866           // We need this because we need to reverse the successors in order
10867           // to implement FCMP_OEQ.
10868           if (User->getOpcode() == ISD::BR) {
10869             SDValue FalseBB = User->getOperand(1);
10870             SDNode *NewBR =
10871               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10872             assert(NewBR == User);
10873             (void)NewBR;
10874             Dest = FalseBB;
10875
10876             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10877                                 Chain, Dest, CC, Cmp);
10878             X86::CondCode CCode =
10879               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10880             CCode = X86::GetOppositeBranchCondition(CCode);
10881             CC = DAG.getConstant(CCode, MVT::i8);
10882             Cond = Cmp;
10883             addTest = false;
10884           }
10885         }
10886       }
10887     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10888       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10889       // It should be transformed during dag combiner except when the condition
10890       // is set by a arithmetics with overflow node.
10891       X86::CondCode CCode =
10892         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10893       CCode = X86::GetOppositeBranchCondition(CCode);
10894       CC = DAG.getConstant(CCode, MVT::i8);
10895       Cond = Cond.getOperand(0).getOperand(1);
10896       addTest = false;
10897     } else if (Cond.getOpcode() == ISD::SETCC &&
10898                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10899       // For FCMP_OEQ, we can emit
10900       // two branches instead of an explicit AND instruction with a
10901       // separate test. However, we only do this if this block doesn't
10902       // have a fall-through edge, because this requires an explicit
10903       // jmp when the condition is false.
10904       if (Op.getNode()->hasOneUse()) {
10905         SDNode *User = *Op.getNode()->use_begin();
10906         // Look for an unconditional branch following this conditional branch.
10907         // We need this because we need to reverse the successors in order
10908         // to implement FCMP_OEQ.
10909         if (User->getOpcode() == ISD::BR) {
10910           SDValue FalseBB = User->getOperand(1);
10911           SDNode *NewBR =
10912             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10913           assert(NewBR == User);
10914           (void)NewBR;
10915           Dest = FalseBB;
10916
10917           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10918                                     Cond.getOperand(0), Cond.getOperand(1));
10919           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10920           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10921           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10922                               Chain, Dest, CC, Cmp);
10923           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10924           Cond = Cmp;
10925           addTest = false;
10926         }
10927       }
10928     } else if (Cond.getOpcode() == ISD::SETCC &&
10929                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10930       // For FCMP_UNE, we can emit
10931       // two branches instead of an explicit AND instruction with a
10932       // separate test. However, we only do this if this block doesn't
10933       // have a fall-through edge, because this requires an explicit
10934       // jmp when the condition is false.
10935       if (Op.getNode()->hasOneUse()) {
10936         SDNode *User = *Op.getNode()->use_begin();
10937         // Look for an unconditional branch following this conditional branch.
10938         // We need this because we need to reverse the successors in order
10939         // to implement FCMP_UNE.
10940         if (User->getOpcode() == ISD::BR) {
10941           SDValue FalseBB = User->getOperand(1);
10942           SDNode *NewBR =
10943             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10944           assert(NewBR == User);
10945           (void)NewBR;
10946
10947           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10948                                     Cond.getOperand(0), Cond.getOperand(1));
10949           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10950           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10951           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10952                               Chain, Dest, CC, Cmp);
10953           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10954           Cond = Cmp;
10955           addTest = false;
10956           Dest = FalseBB;
10957         }
10958       }
10959     }
10960   }
10961
10962   if (addTest) {
10963     // Look pass the truncate if the high bits are known zero.
10964     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10965         Cond = Cond.getOperand(0);
10966
10967     // We know the result of AND is compared against zero. Try to match
10968     // it to BT.
10969     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10970       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10971       if (NewSetCC.getNode()) {
10972         CC = NewSetCC.getOperand(0);
10973         Cond = NewSetCC.getOperand(1);
10974         addTest = false;
10975       }
10976     }
10977   }
10978
10979   if (addTest) {
10980     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10981     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10982   }
10983   Cond = ConvertCmpIfNecessary(Cond, DAG);
10984   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10985                      Chain, Dest, CC, Cond);
10986 }
10987
10988 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10989 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10990 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10991 // that the guard pages used by the OS virtual memory manager are allocated in
10992 // correct sequence.
10993 SDValue
10994 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10995                                            SelectionDAG &DAG) const {
10996   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10997           getTargetMachine().Options.EnableSegmentedStacks) &&
10998          "This should be used only on Windows targets or when segmented stacks "
10999          "are being used");
11000   assert(!Subtarget->isTargetMacho() && "Not implemented");
11001   SDLoc dl(Op);
11002
11003   // Get the inputs.
11004   SDValue Chain = Op.getOperand(0);
11005   SDValue Size  = Op.getOperand(1);
11006   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11007   EVT VT = Op.getNode()->getValueType(0);
11008
11009   bool Is64Bit = Subtarget->is64Bit();
11010   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11011
11012   if (getTargetMachine().Options.EnableSegmentedStacks) {
11013     MachineFunction &MF = DAG.getMachineFunction();
11014     MachineRegisterInfo &MRI = MF.getRegInfo();
11015
11016     if (Is64Bit) {
11017       // The 64 bit implementation of segmented stacks needs to clobber both r10
11018       // r11. This makes it impossible to use it along with nested parameters.
11019       const Function *F = MF.getFunction();
11020
11021       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11022            I != E; ++I)
11023         if (I->hasNestAttr())
11024           report_fatal_error("Cannot use segmented stacks with functions that "
11025                              "have nested arguments.");
11026     }
11027
11028     const TargetRegisterClass *AddrRegClass =
11029       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11030     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11031     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11032     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11033                                 DAG.getRegister(Vreg, SPTy));
11034     SDValue Ops1[2] = { Value, Chain };
11035     return DAG.getMergeValues(Ops1, 2, dl);
11036   } else {
11037     SDValue Flag;
11038     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11039
11040     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11041     Flag = Chain.getValue(1);
11042     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11043
11044     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11045
11046     const X86RegisterInfo *RegInfo =
11047       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11048     unsigned SPReg = RegInfo->getStackRegister();
11049     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11050     Chain = SP.getValue(1);
11051
11052     if (Align) {
11053       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11054                        DAG.getConstant(-(uint64_t)Align, VT));
11055       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11056     }
11057
11058     SDValue Ops1[2] = { SP, Chain };
11059     return DAG.getMergeValues(Ops1, 2, dl);
11060   }
11061 }
11062
11063 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11064   MachineFunction &MF = DAG.getMachineFunction();
11065   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11066
11067   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11068   SDLoc DL(Op);
11069
11070   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11071     // vastart just stores the address of the VarArgsFrameIndex slot into the
11072     // memory location argument.
11073     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11074                                    getPointerTy());
11075     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11076                         MachinePointerInfo(SV), false, false, 0);
11077   }
11078
11079   // __va_list_tag:
11080   //   gp_offset         (0 - 6 * 8)
11081   //   fp_offset         (48 - 48 + 8 * 16)
11082   //   overflow_arg_area (point to parameters coming in memory).
11083   //   reg_save_area
11084   SmallVector<SDValue, 8> MemOps;
11085   SDValue FIN = Op.getOperand(1);
11086   // Store gp_offset
11087   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11088                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11089                                                MVT::i32),
11090                                FIN, MachinePointerInfo(SV), false, false, 0);
11091   MemOps.push_back(Store);
11092
11093   // Store fp_offset
11094   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11095                     FIN, DAG.getIntPtrConstant(4));
11096   Store = DAG.getStore(Op.getOperand(0), DL,
11097                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11098                                        MVT::i32),
11099                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11100   MemOps.push_back(Store);
11101
11102   // Store ptr to overflow_arg_area
11103   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11104                     FIN, DAG.getIntPtrConstant(4));
11105   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11106                                     getPointerTy());
11107   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11108                        MachinePointerInfo(SV, 8),
11109                        false, false, 0);
11110   MemOps.push_back(Store);
11111
11112   // Store ptr to reg_save_area.
11113   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11114                     FIN, DAG.getIntPtrConstant(8));
11115   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11116                                     getPointerTy());
11117   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11118                        MachinePointerInfo(SV, 16), false, false, 0);
11119   MemOps.push_back(Store);
11120   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11121                      &MemOps[0], MemOps.size());
11122 }
11123
11124 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11125   assert(Subtarget->is64Bit() &&
11126          "LowerVAARG only handles 64-bit va_arg!");
11127   assert((Subtarget->isTargetLinux() ||
11128           Subtarget->isTargetDarwin()) &&
11129           "Unhandled target in LowerVAARG");
11130   assert(Op.getNode()->getNumOperands() == 4);
11131   SDValue Chain = Op.getOperand(0);
11132   SDValue SrcPtr = Op.getOperand(1);
11133   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11134   unsigned Align = Op.getConstantOperandVal(3);
11135   SDLoc dl(Op);
11136
11137   EVT ArgVT = Op.getNode()->getValueType(0);
11138   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11139   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11140   uint8_t ArgMode;
11141
11142   // Decide which area this value should be read from.
11143   // TODO: Implement the AMD64 ABI in its entirety. This simple
11144   // selection mechanism works only for the basic types.
11145   if (ArgVT == MVT::f80) {
11146     llvm_unreachable("va_arg for f80 not yet implemented");
11147   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11148     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11149   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11150     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11151   } else {
11152     llvm_unreachable("Unhandled argument type in LowerVAARG");
11153   }
11154
11155   if (ArgMode == 2) {
11156     // Sanity Check: Make sure using fp_offset makes sense.
11157     assert(!getTargetMachine().Options.UseSoftFloat &&
11158            !(DAG.getMachineFunction()
11159                 .getFunction()->getAttributes()
11160                 .hasAttribute(AttributeSet::FunctionIndex,
11161                               Attribute::NoImplicitFloat)) &&
11162            Subtarget->hasSSE1());
11163   }
11164
11165   // Insert VAARG_64 node into the DAG
11166   // VAARG_64 returns two values: Variable Argument Address, Chain
11167   SmallVector<SDValue, 11> InstOps;
11168   InstOps.push_back(Chain);
11169   InstOps.push_back(SrcPtr);
11170   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11171   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11172   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11173   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11174   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11175                                           VTs, &InstOps[0], InstOps.size(),
11176                                           MVT::i64,
11177                                           MachinePointerInfo(SV),
11178                                           /*Align=*/0,
11179                                           /*Volatile=*/false,
11180                                           /*ReadMem=*/true,
11181                                           /*WriteMem=*/true);
11182   Chain = VAARG.getValue(1);
11183
11184   // Load the next argument and return it
11185   return DAG.getLoad(ArgVT, dl,
11186                      Chain,
11187                      VAARG,
11188                      MachinePointerInfo(),
11189                      false, false, false, 0);
11190 }
11191
11192 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11193                            SelectionDAG &DAG) {
11194   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11195   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11196   SDValue Chain = Op.getOperand(0);
11197   SDValue DstPtr = Op.getOperand(1);
11198   SDValue SrcPtr = Op.getOperand(2);
11199   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11200   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11201   SDLoc DL(Op);
11202
11203   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11204                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11205                        false,
11206                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11207 }
11208
11209 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11210 // amount is a constant. Takes immediate version of shift as input.
11211 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11212                                           SDValue SrcOp, uint64_t ShiftAmt,
11213                                           SelectionDAG &DAG) {
11214   MVT ElementType = VT.getVectorElementType();
11215
11216   // Check for ShiftAmt >= element width
11217   if (ShiftAmt >= ElementType.getSizeInBits()) {
11218     if (Opc == X86ISD::VSRAI)
11219       ShiftAmt = ElementType.getSizeInBits() - 1;
11220     else
11221       return DAG.getConstant(0, VT);
11222   }
11223
11224   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11225          && "Unknown target vector shift-by-constant node");
11226
11227   // Fold this packed vector shift into a build vector if SrcOp is a
11228   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11229   if (VT == SrcOp.getSimpleValueType() &&
11230       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11231     SmallVector<SDValue, 8> Elts;
11232     unsigned NumElts = SrcOp->getNumOperands();
11233     ConstantSDNode *ND;
11234
11235     switch(Opc) {
11236     default: llvm_unreachable(0);
11237     case X86ISD::VSHLI:
11238       for (unsigned i=0; i!=NumElts; ++i) {
11239         SDValue CurrentOp = SrcOp->getOperand(i);
11240         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11241           Elts.push_back(CurrentOp);
11242           continue;
11243         }
11244         ND = cast<ConstantSDNode>(CurrentOp);
11245         const APInt &C = ND->getAPIntValue();
11246         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11247       }
11248       break;
11249     case X86ISD::VSRLI:
11250       for (unsigned i=0; i!=NumElts; ++i) {
11251         SDValue CurrentOp = SrcOp->getOperand(i);
11252         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11253           Elts.push_back(CurrentOp);
11254           continue;
11255         }
11256         ND = cast<ConstantSDNode>(CurrentOp);
11257         const APInt &C = ND->getAPIntValue();
11258         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11259       }
11260       break;
11261     case X86ISD::VSRAI:
11262       for (unsigned i=0; i!=NumElts; ++i) {
11263         SDValue CurrentOp = SrcOp->getOperand(i);
11264         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11265           Elts.push_back(CurrentOp);
11266           continue;
11267         }
11268         ND = cast<ConstantSDNode>(CurrentOp);
11269         const APInt &C = ND->getAPIntValue();
11270         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11271       }
11272       break;
11273     }
11274
11275     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11276   }
11277
11278   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11279 }
11280
11281 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11282 // may or may not be a constant. Takes immediate version of shift as input.
11283 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11284                                    SDValue SrcOp, SDValue ShAmt,
11285                                    SelectionDAG &DAG) {
11286   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11287
11288   // Catch shift-by-constant.
11289   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11290     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11291                                       CShAmt->getZExtValue(), DAG);
11292
11293   // Change opcode to non-immediate version
11294   switch (Opc) {
11295     default: llvm_unreachable("Unknown target vector shift node");
11296     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11297     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11298     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11299   }
11300
11301   // Need to build a vector containing shift amount
11302   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11303   SDValue ShOps[4];
11304   ShOps[0] = ShAmt;
11305   ShOps[1] = DAG.getConstant(0, MVT::i32);
11306   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11307   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11308
11309   // The return type has to be a 128-bit type with the same element
11310   // type as the input type.
11311   MVT EltVT = VT.getVectorElementType();
11312   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11313
11314   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11315   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11316 }
11317
11318 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11319   SDLoc dl(Op);
11320   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11321   switch (IntNo) {
11322   default: return SDValue();    // Don't custom lower most intrinsics.
11323   // Comparison intrinsics.
11324   case Intrinsic::x86_sse_comieq_ss:
11325   case Intrinsic::x86_sse_comilt_ss:
11326   case Intrinsic::x86_sse_comile_ss:
11327   case Intrinsic::x86_sse_comigt_ss:
11328   case Intrinsic::x86_sse_comige_ss:
11329   case Intrinsic::x86_sse_comineq_ss:
11330   case Intrinsic::x86_sse_ucomieq_ss:
11331   case Intrinsic::x86_sse_ucomilt_ss:
11332   case Intrinsic::x86_sse_ucomile_ss:
11333   case Intrinsic::x86_sse_ucomigt_ss:
11334   case Intrinsic::x86_sse_ucomige_ss:
11335   case Intrinsic::x86_sse_ucomineq_ss:
11336   case Intrinsic::x86_sse2_comieq_sd:
11337   case Intrinsic::x86_sse2_comilt_sd:
11338   case Intrinsic::x86_sse2_comile_sd:
11339   case Intrinsic::x86_sse2_comigt_sd:
11340   case Intrinsic::x86_sse2_comige_sd:
11341   case Intrinsic::x86_sse2_comineq_sd:
11342   case Intrinsic::x86_sse2_ucomieq_sd:
11343   case Intrinsic::x86_sse2_ucomilt_sd:
11344   case Intrinsic::x86_sse2_ucomile_sd:
11345   case Intrinsic::x86_sse2_ucomigt_sd:
11346   case Intrinsic::x86_sse2_ucomige_sd:
11347   case Intrinsic::x86_sse2_ucomineq_sd: {
11348     unsigned Opc;
11349     ISD::CondCode CC;
11350     switch (IntNo) {
11351     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11352     case Intrinsic::x86_sse_comieq_ss:
11353     case Intrinsic::x86_sse2_comieq_sd:
11354       Opc = X86ISD::COMI;
11355       CC = ISD::SETEQ;
11356       break;
11357     case Intrinsic::x86_sse_comilt_ss:
11358     case Intrinsic::x86_sse2_comilt_sd:
11359       Opc = X86ISD::COMI;
11360       CC = ISD::SETLT;
11361       break;
11362     case Intrinsic::x86_sse_comile_ss:
11363     case Intrinsic::x86_sse2_comile_sd:
11364       Opc = X86ISD::COMI;
11365       CC = ISD::SETLE;
11366       break;
11367     case Intrinsic::x86_sse_comigt_ss:
11368     case Intrinsic::x86_sse2_comigt_sd:
11369       Opc = X86ISD::COMI;
11370       CC = ISD::SETGT;
11371       break;
11372     case Intrinsic::x86_sse_comige_ss:
11373     case Intrinsic::x86_sse2_comige_sd:
11374       Opc = X86ISD::COMI;
11375       CC = ISD::SETGE;
11376       break;
11377     case Intrinsic::x86_sse_comineq_ss:
11378     case Intrinsic::x86_sse2_comineq_sd:
11379       Opc = X86ISD::COMI;
11380       CC = ISD::SETNE;
11381       break;
11382     case Intrinsic::x86_sse_ucomieq_ss:
11383     case Intrinsic::x86_sse2_ucomieq_sd:
11384       Opc = X86ISD::UCOMI;
11385       CC = ISD::SETEQ;
11386       break;
11387     case Intrinsic::x86_sse_ucomilt_ss:
11388     case Intrinsic::x86_sse2_ucomilt_sd:
11389       Opc = X86ISD::UCOMI;
11390       CC = ISD::SETLT;
11391       break;
11392     case Intrinsic::x86_sse_ucomile_ss:
11393     case Intrinsic::x86_sse2_ucomile_sd:
11394       Opc = X86ISD::UCOMI;
11395       CC = ISD::SETLE;
11396       break;
11397     case Intrinsic::x86_sse_ucomigt_ss:
11398     case Intrinsic::x86_sse2_ucomigt_sd:
11399       Opc = X86ISD::UCOMI;
11400       CC = ISD::SETGT;
11401       break;
11402     case Intrinsic::x86_sse_ucomige_ss:
11403     case Intrinsic::x86_sse2_ucomige_sd:
11404       Opc = X86ISD::UCOMI;
11405       CC = ISD::SETGE;
11406       break;
11407     case Intrinsic::x86_sse_ucomineq_ss:
11408     case Intrinsic::x86_sse2_ucomineq_sd:
11409       Opc = X86ISD::UCOMI;
11410       CC = ISD::SETNE;
11411       break;
11412     }
11413
11414     SDValue LHS = Op.getOperand(1);
11415     SDValue RHS = Op.getOperand(2);
11416     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11417     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11418     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11419     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11420                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11421     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11422   }
11423
11424   // Arithmetic intrinsics.
11425   case Intrinsic::x86_sse2_pmulu_dq:
11426   case Intrinsic::x86_avx2_pmulu_dq:
11427     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11428                        Op.getOperand(1), Op.getOperand(2));
11429
11430   // SSE2/AVX2 sub with unsigned saturation intrinsics
11431   case Intrinsic::x86_sse2_psubus_b:
11432   case Intrinsic::x86_sse2_psubus_w:
11433   case Intrinsic::x86_avx2_psubus_b:
11434   case Intrinsic::x86_avx2_psubus_w:
11435     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11436                        Op.getOperand(1), Op.getOperand(2));
11437
11438   // SSE3/AVX horizontal add/sub intrinsics
11439   case Intrinsic::x86_sse3_hadd_ps:
11440   case Intrinsic::x86_sse3_hadd_pd:
11441   case Intrinsic::x86_avx_hadd_ps_256:
11442   case Intrinsic::x86_avx_hadd_pd_256:
11443   case Intrinsic::x86_sse3_hsub_ps:
11444   case Intrinsic::x86_sse3_hsub_pd:
11445   case Intrinsic::x86_avx_hsub_ps_256:
11446   case Intrinsic::x86_avx_hsub_pd_256:
11447   case Intrinsic::x86_ssse3_phadd_w_128:
11448   case Intrinsic::x86_ssse3_phadd_d_128:
11449   case Intrinsic::x86_avx2_phadd_w:
11450   case Intrinsic::x86_avx2_phadd_d:
11451   case Intrinsic::x86_ssse3_phsub_w_128:
11452   case Intrinsic::x86_ssse3_phsub_d_128:
11453   case Intrinsic::x86_avx2_phsub_w:
11454   case Intrinsic::x86_avx2_phsub_d: {
11455     unsigned Opcode;
11456     switch (IntNo) {
11457     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11458     case Intrinsic::x86_sse3_hadd_ps:
11459     case Intrinsic::x86_sse3_hadd_pd:
11460     case Intrinsic::x86_avx_hadd_ps_256:
11461     case Intrinsic::x86_avx_hadd_pd_256:
11462       Opcode = X86ISD::FHADD;
11463       break;
11464     case Intrinsic::x86_sse3_hsub_ps:
11465     case Intrinsic::x86_sse3_hsub_pd:
11466     case Intrinsic::x86_avx_hsub_ps_256:
11467     case Intrinsic::x86_avx_hsub_pd_256:
11468       Opcode = X86ISD::FHSUB;
11469       break;
11470     case Intrinsic::x86_ssse3_phadd_w_128:
11471     case Intrinsic::x86_ssse3_phadd_d_128:
11472     case Intrinsic::x86_avx2_phadd_w:
11473     case Intrinsic::x86_avx2_phadd_d:
11474       Opcode = X86ISD::HADD;
11475       break;
11476     case Intrinsic::x86_ssse3_phsub_w_128:
11477     case Intrinsic::x86_ssse3_phsub_d_128:
11478     case Intrinsic::x86_avx2_phsub_w:
11479     case Intrinsic::x86_avx2_phsub_d:
11480       Opcode = X86ISD::HSUB;
11481       break;
11482     }
11483     return DAG.getNode(Opcode, dl, Op.getValueType(),
11484                        Op.getOperand(1), Op.getOperand(2));
11485   }
11486
11487   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11488   case Intrinsic::x86_sse2_pmaxu_b:
11489   case Intrinsic::x86_sse41_pmaxuw:
11490   case Intrinsic::x86_sse41_pmaxud:
11491   case Intrinsic::x86_avx2_pmaxu_b:
11492   case Intrinsic::x86_avx2_pmaxu_w:
11493   case Intrinsic::x86_avx2_pmaxu_d:
11494   case Intrinsic::x86_sse2_pminu_b:
11495   case Intrinsic::x86_sse41_pminuw:
11496   case Intrinsic::x86_sse41_pminud:
11497   case Intrinsic::x86_avx2_pminu_b:
11498   case Intrinsic::x86_avx2_pminu_w:
11499   case Intrinsic::x86_avx2_pminu_d:
11500   case Intrinsic::x86_sse41_pmaxsb:
11501   case Intrinsic::x86_sse2_pmaxs_w:
11502   case Intrinsic::x86_sse41_pmaxsd:
11503   case Intrinsic::x86_avx2_pmaxs_b:
11504   case Intrinsic::x86_avx2_pmaxs_w:
11505   case Intrinsic::x86_avx2_pmaxs_d:
11506   case Intrinsic::x86_sse41_pminsb:
11507   case Intrinsic::x86_sse2_pmins_w:
11508   case Intrinsic::x86_sse41_pminsd:
11509   case Intrinsic::x86_avx2_pmins_b:
11510   case Intrinsic::x86_avx2_pmins_w:
11511   case Intrinsic::x86_avx2_pmins_d: {
11512     unsigned Opcode;
11513     switch (IntNo) {
11514     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11515     case Intrinsic::x86_sse2_pmaxu_b:
11516     case Intrinsic::x86_sse41_pmaxuw:
11517     case Intrinsic::x86_sse41_pmaxud:
11518     case Intrinsic::x86_avx2_pmaxu_b:
11519     case Intrinsic::x86_avx2_pmaxu_w:
11520     case Intrinsic::x86_avx2_pmaxu_d:
11521       Opcode = X86ISD::UMAX;
11522       break;
11523     case Intrinsic::x86_sse2_pminu_b:
11524     case Intrinsic::x86_sse41_pminuw:
11525     case Intrinsic::x86_sse41_pminud:
11526     case Intrinsic::x86_avx2_pminu_b:
11527     case Intrinsic::x86_avx2_pminu_w:
11528     case Intrinsic::x86_avx2_pminu_d:
11529       Opcode = X86ISD::UMIN;
11530       break;
11531     case Intrinsic::x86_sse41_pmaxsb:
11532     case Intrinsic::x86_sse2_pmaxs_w:
11533     case Intrinsic::x86_sse41_pmaxsd:
11534     case Intrinsic::x86_avx2_pmaxs_b:
11535     case Intrinsic::x86_avx2_pmaxs_w:
11536     case Intrinsic::x86_avx2_pmaxs_d:
11537       Opcode = X86ISD::SMAX;
11538       break;
11539     case Intrinsic::x86_sse41_pminsb:
11540     case Intrinsic::x86_sse2_pmins_w:
11541     case Intrinsic::x86_sse41_pminsd:
11542     case Intrinsic::x86_avx2_pmins_b:
11543     case Intrinsic::x86_avx2_pmins_w:
11544     case Intrinsic::x86_avx2_pmins_d:
11545       Opcode = X86ISD::SMIN;
11546       break;
11547     }
11548     return DAG.getNode(Opcode, dl, Op.getValueType(),
11549                        Op.getOperand(1), Op.getOperand(2));
11550   }
11551
11552   // SSE/SSE2/AVX floating point max/min intrinsics.
11553   case Intrinsic::x86_sse_max_ps:
11554   case Intrinsic::x86_sse2_max_pd:
11555   case Intrinsic::x86_avx_max_ps_256:
11556   case Intrinsic::x86_avx_max_pd_256:
11557   case Intrinsic::x86_sse_min_ps:
11558   case Intrinsic::x86_sse2_min_pd:
11559   case Intrinsic::x86_avx_min_ps_256:
11560   case Intrinsic::x86_avx_min_pd_256: {
11561     unsigned Opcode;
11562     switch (IntNo) {
11563     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11564     case Intrinsic::x86_sse_max_ps:
11565     case Intrinsic::x86_sse2_max_pd:
11566     case Intrinsic::x86_avx_max_ps_256:
11567     case Intrinsic::x86_avx_max_pd_256:
11568       Opcode = X86ISD::FMAX;
11569       break;
11570     case Intrinsic::x86_sse_min_ps:
11571     case Intrinsic::x86_sse2_min_pd:
11572     case Intrinsic::x86_avx_min_ps_256:
11573     case Intrinsic::x86_avx_min_pd_256:
11574       Opcode = X86ISD::FMIN;
11575       break;
11576     }
11577     return DAG.getNode(Opcode, dl, Op.getValueType(),
11578                        Op.getOperand(1), Op.getOperand(2));
11579   }
11580
11581   // AVX2 variable shift intrinsics
11582   case Intrinsic::x86_avx2_psllv_d:
11583   case Intrinsic::x86_avx2_psllv_q:
11584   case Intrinsic::x86_avx2_psllv_d_256:
11585   case Intrinsic::x86_avx2_psllv_q_256:
11586   case Intrinsic::x86_avx2_psrlv_d:
11587   case Intrinsic::x86_avx2_psrlv_q:
11588   case Intrinsic::x86_avx2_psrlv_d_256:
11589   case Intrinsic::x86_avx2_psrlv_q_256:
11590   case Intrinsic::x86_avx2_psrav_d:
11591   case Intrinsic::x86_avx2_psrav_d_256: {
11592     unsigned Opcode;
11593     switch (IntNo) {
11594     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11595     case Intrinsic::x86_avx2_psllv_d:
11596     case Intrinsic::x86_avx2_psllv_q:
11597     case Intrinsic::x86_avx2_psllv_d_256:
11598     case Intrinsic::x86_avx2_psllv_q_256:
11599       Opcode = ISD::SHL;
11600       break;
11601     case Intrinsic::x86_avx2_psrlv_d:
11602     case Intrinsic::x86_avx2_psrlv_q:
11603     case Intrinsic::x86_avx2_psrlv_d_256:
11604     case Intrinsic::x86_avx2_psrlv_q_256:
11605       Opcode = ISD::SRL;
11606       break;
11607     case Intrinsic::x86_avx2_psrav_d:
11608     case Intrinsic::x86_avx2_psrav_d_256:
11609       Opcode = ISD::SRA;
11610       break;
11611     }
11612     return DAG.getNode(Opcode, dl, Op.getValueType(),
11613                        Op.getOperand(1), Op.getOperand(2));
11614   }
11615
11616   case Intrinsic::x86_ssse3_pshuf_b_128:
11617   case Intrinsic::x86_avx2_pshuf_b:
11618     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11619                        Op.getOperand(1), Op.getOperand(2));
11620
11621   case Intrinsic::x86_ssse3_psign_b_128:
11622   case Intrinsic::x86_ssse3_psign_w_128:
11623   case Intrinsic::x86_ssse3_psign_d_128:
11624   case Intrinsic::x86_avx2_psign_b:
11625   case Intrinsic::x86_avx2_psign_w:
11626   case Intrinsic::x86_avx2_psign_d:
11627     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11628                        Op.getOperand(1), Op.getOperand(2));
11629
11630   case Intrinsic::x86_sse41_insertps:
11631     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11632                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11633
11634   case Intrinsic::x86_avx_vperm2f128_ps_256:
11635   case Intrinsic::x86_avx_vperm2f128_pd_256:
11636   case Intrinsic::x86_avx_vperm2f128_si_256:
11637   case Intrinsic::x86_avx2_vperm2i128:
11638     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11639                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11640
11641   case Intrinsic::x86_avx2_permd:
11642   case Intrinsic::x86_avx2_permps:
11643     // Operands intentionally swapped. Mask is last operand to intrinsic,
11644     // but second operand for node/instruction.
11645     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11646                        Op.getOperand(2), Op.getOperand(1));
11647
11648   case Intrinsic::x86_sse_sqrt_ps:
11649   case Intrinsic::x86_sse2_sqrt_pd:
11650   case Intrinsic::x86_avx_sqrt_ps_256:
11651   case Intrinsic::x86_avx_sqrt_pd_256:
11652     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11653
11654   // ptest and testp intrinsics. The intrinsic these come from are designed to
11655   // return an integer value, not just an instruction so lower it to the ptest
11656   // or testp pattern and a setcc for the result.
11657   case Intrinsic::x86_sse41_ptestz:
11658   case Intrinsic::x86_sse41_ptestc:
11659   case Intrinsic::x86_sse41_ptestnzc:
11660   case Intrinsic::x86_avx_ptestz_256:
11661   case Intrinsic::x86_avx_ptestc_256:
11662   case Intrinsic::x86_avx_ptestnzc_256:
11663   case Intrinsic::x86_avx_vtestz_ps:
11664   case Intrinsic::x86_avx_vtestc_ps:
11665   case Intrinsic::x86_avx_vtestnzc_ps:
11666   case Intrinsic::x86_avx_vtestz_pd:
11667   case Intrinsic::x86_avx_vtestc_pd:
11668   case Intrinsic::x86_avx_vtestnzc_pd:
11669   case Intrinsic::x86_avx_vtestz_ps_256:
11670   case Intrinsic::x86_avx_vtestc_ps_256:
11671   case Intrinsic::x86_avx_vtestnzc_ps_256:
11672   case Intrinsic::x86_avx_vtestz_pd_256:
11673   case Intrinsic::x86_avx_vtestc_pd_256:
11674   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11675     bool IsTestPacked = false;
11676     unsigned X86CC;
11677     switch (IntNo) {
11678     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11679     case Intrinsic::x86_avx_vtestz_ps:
11680     case Intrinsic::x86_avx_vtestz_pd:
11681     case Intrinsic::x86_avx_vtestz_ps_256:
11682     case Intrinsic::x86_avx_vtestz_pd_256:
11683       IsTestPacked = true; // Fallthrough
11684     case Intrinsic::x86_sse41_ptestz:
11685     case Intrinsic::x86_avx_ptestz_256:
11686       // ZF = 1
11687       X86CC = X86::COND_E;
11688       break;
11689     case Intrinsic::x86_avx_vtestc_ps:
11690     case Intrinsic::x86_avx_vtestc_pd:
11691     case Intrinsic::x86_avx_vtestc_ps_256:
11692     case Intrinsic::x86_avx_vtestc_pd_256:
11693       IsTestPacked = true; // Fallthrough
11694     case Intrinsic::x86_sse41_ptestc:
11695     case Intrinsic::x86_avx_ptestc_256:
11696       // CF = 1
11697       X86CC = X86::COND_B;
11698       break;
11699     case Intrinsic::x86_avx_vtestnzc_ps:
11700     case Intrinsic::x86_avx_vtestnzc_pd:
11701     case Intrinsic::x86_avx_vtestnzc_ps_256:
11702     case Intrinsic::x86_avx_vtestnzc_pd_256:
11703       IsTestPacked = true; // Fallthrough
11704     case Intrinsic::x86_sse41_ptestnzc:
11705     case Intrinsic::x86_avx_ptestnzc_256:
11706       // ZF and CF = 0
11707       X86CC = X86::COND_A;
11708       break;
11709     }
11710
11711     SDValue LHS = Op.getOperand(1);
11712     SDValue RHS = Op.getOperand(2);
11713     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11714     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11715     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11716     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11717     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11718   }
11719   case Intrinsic::x86_avx512_kortestz_w:
11720   case Intrinsic::x86_avx512_kortestc_w: {
11721     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11722     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11723     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11724     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11725     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11726     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11727     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11728   }
11729
11730   // SSE/AVX shift intrinsics
11731   case Intrinsic::x86_sse2_psll_w:
11732   case Intrinsic::x86_sse2_psll_d:
11733   case Intrinsic::x86_sse2_psll_q:
11734   case Intrinsic::x86_avx2_psll_w:
11735   case Intrinsic::x86_avx2_psll_d:
11736   case Intrinsic::x86_avx2_psll_q:
11737   case Intrinsic::x86_sse2_psrl_w:
11738   case Intrinsic::x86_sse2_psrl_d:
11739   case Intrinsic::x86_sse2_psrl_q:
11740   case Intrinsic::x86_avx2_psrl_w:
11741   case Intrinsic::x86_avx2_psrl_d:
11742   case Intrinsic::x86_avx2_psrl_q:
11743   case Intrinsic::x86_sse2_psra_w:
11744   case Intrinsic::x86_sse2_psra_d:
11745   case Intrinsic::x86_avx2_psra_w:
11746   case Intrinsic::x86_avx2_psra_d: {
11747     unsigned Opcode;
11748     switch (IntNo) {
11749     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11750     case Intrinsic::x86_sse2_psll_w:
11751     case Intrinsic::x86_sse2_psll_d:
11752     case Intrinsic::x86_sse2_psll_q:
11753     case Intrinsic::x86_avx2_psll_w:
11754     case Intrinsic::x86_avx2_psll_d:
11755     case Intrinsic::x86_avx2_psll_q:
11756       Opcode = X86ISD::VSHL;
11757       break;
11758     case Intrinsic::x86_sse2_psrl_w:
11759     case Intrinsic::x86_sse2_psrl_d:
11760     case Intrinsic::x86_sse2_psrl_q:
11761     case Intrinsic::x86_avx2_psrl_w:
11762     case Intrinsic::x86_avx2_psrl_d:
11763     case Intrinsic::x86_avx2_psrl_q:
11764       Opcode = X86ISD::VSRL;
11765       break;
11766     case Intrinsic::x86_sse2_psra_w:
11767     case Intrinsic::x86_sse2_psra_d:
11768     case Intrinsic::x86_avx2_psra_w:
11769     case Intrinsic::x86_avx2_psra_d:
11770       Opcode = X86ISD::VSRA;
11771       break;
11772     }
11773     return DAG.getNode(Opcode, dl, Op.getValueType(),
11774                        Op.getOperand(1), Op.getOperand(2));
11775   }
11776
11777   // SSE/AVX immediate shift intrinsics
11778   case Intrinsic::x86_sse2_pslli_w:
11779   case Intrinsic::x86_sse2_pslli_d:
11780   case Intrinsic::x86_sse2_pslli_q:
11781   case Intrinsic::x86_avx2_pslli_w:
11782   case Intrinsic::x86_avx2_pslli_d:
11783   case Intrinsic::x86_avx2_pslli_q:
11784   case Intrinsic::x86_sse2_psrli_w:
11785   case Intrinsic::x86_sse2_psrli_d:
11786   case Intrinsic::x86_sse2_psrli_q:
11787   case Intrinsic::x86_avx2_psrli_w:
11788   case Intrinsic::x86_avx2_psrli_d:
11789   case Intrinsic::x86_avx2_psrli_q:
11790   case Intrinsic::x86_sse2_psrai_w:
11791   case Intrinsic::x86_sse2_psrai_d:
11792   case Intrinsic::x86_avx2_psrai_w:
11793   case Intrinsic::x86_avx2_psrai_d: {
11794     unsigned Opcode;
11795     switch (IntNo) {
11796     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11797     case Intrinsic::x86_sse2_pslli_w:
11798     case Intrinsic::x86_sse2_pslli_d:
11799     case Intrinsic::x86_sse2_pslli_q:
11800     case Intrinsic::x86_avx2_pslli_w:
11801     case Intrinsic::x86_avx2_pslli_d:
11802     case Intrinsic::x86_avx2_pslli_q:
11803       Opcode = X86ISD::VSHLI;
11804       break;
11805     case Intrinsic::x86_sse2_psrli_w:
11806     case Intrinsic::x86_sse2_psrli_d:
11807     case Intrinsic::x86_sse2_psrli_q:
11808     case Intrinsic::x86_avx2_psrli_w:
11809     case Intrinsic::x86_avx2_psrli_d:
11810     case Intrinsic::x86_avx2_psrli_q:
11811       Opcode = X86ISD::VSRLI;
11812       break;
11813     case Intrinsic::x86_sse2_psrai_w:
11814     case Intrinsic::x86_sse2_psrai_d:
11815     case Intrinsic::x86_avx2_psrai_w:
11816     case Intrinsic::x86_avx2_psrai_d:
11817       Opcode = X86ISD::VSRAI;
11818       break;
11819     }
11820     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11821                                Op.getOperand(1), Op.getOperand(2), DAG);
11822   }
11823
11824   case Intrinsic::x86_sse42_pcmpistria128:
11825   case Intrinsic::x86_sse42_pcmpestria128:
11826   case Intrinsic::x86_sse42_pcmpistric128:
11827   case Intrinsic::x86_sse42_pcmpestric128:
11828   case Intrinsic::x86_sse42_pcmpistrio128:
11829   case Intrinsic::x86_sse42_pcmpestrio128:
11830   case Intrinsic::x86_sse42_pcmpistris128:
11831   case Intrinsic::x86_sse42_pcmpestris128:
11832   case Intrinsic::x86_sse42_pcmpistriz128:
11833   case Intrinsic::x86_sse42_pcmpestriz128: {
11834     unsigned Opcode;
11835     unsigned X86CC;
11836     switch (IntNo) {
11837     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11838     case Intrinsic::x86_sse42_pcmpistria128:
11839       Opcode = X86ISD::PCMPISTRI;
11840       X86CC = X86::COND_A;
11841       break;
11842     case Intrinsic::x86_sse42_pcmpestria128:
11843       Opcode = X86ISD::PCMPESTRI;
11844       X86CC = X86::COND_A;
11845       break;
11846     case Intrinsic::x86_sse42_pcmpistric128:
11847       Opcode = X86ISD::PCMPISTRI;
11848       X86CC = X86::COND_B;
11849       break;
11850     case Intrinsic::x86_sse42_pcmpestric128:
11851       Opcode = X86ISD::PCMPESTRI;
11852       X86CC = X86::COND_B;
11853       break;
11854     case Intrinsic::x86_sse42_pcmpistrio128:
11855       Opcode = X86ISD::PCMPISTRI;
11856       X86CC = X86::COND_O;
11857       break;
11858     case Intrinsic::x86_sse42_pcmpestrio128:
11859       Opcode = X86ISD::PCMPESTRI;
11860       X86CC = X86::COND_O;
11861       break;
11862     case Intrinsic::x86_sse42_pcmpistris128:
11863       Opcode = X86ISD::PCMPISTRI;
11864       X86CC = X86::COND_S;
11865       break;
11866     case Intrinsic::x86_sse42_pcmpestris128:
11867       Opcode = X86ISD::PCMPESTRI;
11868       X86CC = X86::COND_S;
11869       break;
11870     case Intrinsic::x86_sse42_pcmpistriz128:
11871       Opcode = X86ISD::PCMPISTRI;
11872       X86CC = X86::COND_E;
11873       break;
11874     case Intrinsic::x86_sse42_pcmpestriz128:
11875       Opcode = X86ISD::PCMPESTRI;
11876       X86CC = X86::COND_E;
11877       break;
11878     }
11879     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11880     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11881     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11882     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11883                                 DAG.getConstant(X86CC, MVT::i8),
11884                                 SDValue(PCMP.getNode(), 1));
11885     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11886   }
11887
11888   case Intrinsic::x86_sse42_pcmpistri128:
11889   case Intrinsic::x86_sse42_pcmpestri128: {
11890     unsigned Opcode;
11891     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11892       Opcode = X86ISD::PCMPISTRI;
11893     else
11894       Opcode = X86ISD::PCMPESTRI;
11895
11896     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11897     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11898     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11899   }
11900   case Intrinsic::x86_fma_vfmadd_ps:
11901   case Intrinsic::x86_fma_vfmadd_pd:
11902   case Intrinsic::x86_fma_vfmsub_ps:
11903   case Intrinsic::x86_fma_vfmsub_pd:
11904   case Intrinsic::x86_fma_vfnmadd_ps:
11905   case Intrinsic::x86_fma_vfnmadd_pd:
11906   case Intrinsic::x86_fma_vfnmsub_ps:
11907   case Intrinsic::x86_fma_vfnmsub_pd:
11908   case Intrinsic::x86_fma_vfmaddsub_ps:
11909   case Intrinsic::x86_fma_vfmaddsub_pd:
11910   case Intrinsic::x86_fma_vfmsubadd_ps:
11911   case Intrinsic::x86_fma_vfmsubadd_pd:
11912   case Intrinsic::x86_fma_vfmadd_ps_256:
11913   case Intrinsic::x86_fma_vfmadd_pd_256:
11914   case Intrinsic::x86_fma_vfmsub_ps_256:
11915   case Intrinsic::x86_fma_vfmsub_pd_256:
11916   case Intrinsic::x86_fma_vfnmadd_ps_256:
11917   case Intrinsic::x86_fma_vfnmadd_pd_256:
11918   case Intrinsic::x86_fma_vfnmsub_ps_256:
11919   case Intrinsic::x86_fma_vfnmsub_pd_256:
11920   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11921   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11922   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11923   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11924   case Intrinsic::x86_fma_vfmadd_ps_512:
11925   case Intrinsic::x86_fma_vfmadd_pd_512:
11926   case Intrinsic::x86_fma_vfmsub_ps_512:
11927   case Intrinsic::x86_fma_vfmsub_pd_512:
11928   case Intrinsic::x86_fma_vfnmadd_ps_512:
11929   case Intrinsic::x86_fma_vfnmadd_pd_512:
11930   case Intrinsic::x86_fma_vfnmsub_ps_512:
11931   case Intrinsic::x86_fma_vfnmsub_pd_512:
11932   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11933   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11934   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11935   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11936     unsigned Opc;
11937     switch (IntNo) {
11938     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11939     case Intrinsic::x86_fma_vfmadd_ps:
11940     case Intrinsic::x86_fma_vfmadd_pd:
11941     case Intrinsic::x86_fma_vfmadd_ps_256:
11942     case Intrinsic::x86_fma_vfmadd_pd_256:
11943     case Intrinsic::x86_fma_vfmadd_ps_512:
11944     case Intrinsic::x86_fma_vfmadd_pd_512:
11945       Opc = X86ISD::FMADD;
11946       break;
11947     case Intrinsic::x86_fma_vfmsub_ps:
11948     case Intrinsic::x86_fma_vfmsub_pd:
11949     case Intrinsic::x86_fma_vfmsub_ps_256:
11950     case Intrinsic::x86_fma_vfmsub_pd_256:
11951     case Intrinsic::x86_fma_vfmsub_ps_512:
11952     case Intrinsic::x86_fma_vfmsub_pd_512:
11953       Opc = X86ISD::FMSUB;
11954       break;
11955     case Intrinsic::x86_fma_vfnmadd_ps:
11956     case Intrinsic::x86_fma_vfnmadd_pd:
11957     case Intrinsic::x86_fma_vfnmadd_ps_256:
11958     case Intrinsic::x86_fma_vfnmadd_pd_256:
11959     case Intrinsic::x86_fma_vfnmadd_ps_512:
11960     case Intrinsic::x86_fma_vfnmadd_pd_512:
11961       Opc = X86ISD::FNMADD;
11962       break;
11963     case Intrinsic::x86_fma_vfnmsub_ps:
11964     case Intrinsic::x86_fma_vfnmsub_pd:
11965     case Intrinsic::x86_fma_vfnmsub_ps_256:
11966     case Intrinsic::x86_fma_vfnmsub_pd_256:
11967     case Intrinsic::x86_fma_vfnmsub_ps_512:
11968     case Intrinsic::x86_fma_vfnmsub_pd_512:
11969       Opc = X86ISD::FNMSUB;
11970       break;
11971     case Intrinsic::x86_fma_vfmaddsub_ps:
11972     case Intrinsic::x86_fma_vfmaddsub_pd:
11973     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11974     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11975     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11976     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11977       Opc = X86ISD::FMADDSUB;
11978       break;
11979     case Intrinsic::x86_fma_vfmsubadd_ps:
11980     case Intrinsic::x86_fma_vfmsubadd_pd:
11981     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11982     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11983     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11984     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11985       Opc = X86ISD::FMSUBADD;
11986       break;
11987     }
11988
11989     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11990                        Op.getOperand(2), Op.getOperand(3));
11991   }
11992   }
11993 }
11994
11995 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11996                              SDValue Base, SDValue Index,
11997                              SDValue ScaleOp, SDValue Chain,
11998                              const X86Subtarget * Subtarget) {
11999   SDLoc dl(Op);
12000   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12001   assert(C && "Invalid scale type");
12002   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12003   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12004   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12005                              Index.getSimpleValueType().getVectorNumElements());
12006   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12007   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12008   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12009   SDValue Segment = DAG.getRegister(0, MVT::i32);
12010   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12011   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12012   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12013   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12014 }
12015
12016 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12017                               SDValue Src, SDValue Mask, SDValue Base,
12018                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12019                               const X86Subtarget * Subtarget) {
12020   SDLoc dl(Op);
12021   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12022   assert(C && "Invalid scale type");
12023   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12024   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12025                              Index.getSimpleValueType().getVectorNumElements());
12026   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12027   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12028   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12029   SDValue Segment = DAG.getRegister(0, MVT::i32);
12030   if (Src.getOpcode() == ISD::UNDEF)
12031     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12032   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12033   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12034   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12035   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12036 }
12037
12038 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12039                               SDValue Src, SDValue Base, SDValue Index,
12040                               SDValue ScaleOp, SDValue Chain) {
12041   SDLoc dl(Op);
12042   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12043   assert(C && "Invalid scale type");
12044   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12045   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12046   SDValue Segment = DAG.getRegister(0, MVT::i32);
12047   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12048                              Index.getSimpleValueType().getVectorNumElements());
12049   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12050   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12051   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12052   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12053   return SDValue(Res, 1);
12054 }
12055
12056 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12057                                SDValue Src, SDValue Mask, SDValue Base,
12058                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12059   SDLoc dl(Op);
12060   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12061   assert(C && "Invalid scale type");
12062   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12063   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12064   SDValue Segment = DAG.getRegister(0, MVT::i32);
12065   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12066                              Index.getSimpleValueType().getVectorNumElements());
12067   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12068   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12069   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12070   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12071   return SDValue(Res, 1);
12072 }
12073
12074 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12075                                       SelectionDAG &DAG) {
12076   SDLoc dl(Op);
12077   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12078   switch (IntNo) {
12079   default: return SDValue();    // Don't custom lower most intrinsics.
12080
12081   // RDRAND/RDSEED intrinsics.
12082   case Intrinsic::x86_rdrand_16:
12083   case Intrinsic::x86_rdrand_32:
12084   case Intrinsic::x86_rdrand_64:
12085   case Intrinsic::x86_rdseed_16:
12086   case Intrinsic::x86_rdseed_32:
12087   case Intrinsic::x86_rdseed_64: {
12088     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12089                        IntNo == Intrinsic::x86_rdseed_32 ||
12090                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12091                                                             X86ISD::RDRAND;
12092     // Emit the node with the right value type.
12093     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12094     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12095
12096     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12097     // Otherwise return the value from Rand, which is always 0, casted to i32.
12098     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12099                       DAG.getConstant(1, Op->getValueType(1)),
12100                       DAG.getConstant(X86::COND_B, MVT::i32),
12101                       SDValue(Result.getNode(), 1) };
12102     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12103                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12104                                   Ops, array_lengthof(Ops));
12105
12106     // Return { result, isValid, chain }.
12107     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12108                        SDValue(Result.getNode(), 2));
12109   }
12110   //int_gather(index, base, scale);
12111   case Intrinsic::x86_avx512_gather_qpd_512:
12112   case Intrinsic::x86_avx512_gather_qps_512:
12113   case Intrinsic::x86_avx512_gather_dpd_512:
12114   case Intrinsic::x86_avx512_gather_qpi_512:
12115   case Intrinsic::x86_avx512_gather_qpq_512:
12116   case Intrinsic::x86_avx512_gather_dpq_512:
12117   case Intrinsic::x86_avx512_gather_dps_512:
12118   case Intrinsic::x86_avx512_gather_dpi_512: {
12119     unsigned Opc;
12120     switch (IntNo) {
12121     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12122     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12123     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12124     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12125     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12126     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12127     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12128     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12129     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12130     }
12131     SDValue Chain = Op.getOperand(0);
12132     SDValue Index = Op.getOperand(2);
12133     SDValue Base  = Op.getOperand(3);
12134     SDValue Scale = Op.getOperand(4);
12135     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12136   }
12137   //int_gather_mask(v1, mask, index, base, scale);
12138   case Intrinsic::x86_avx512_gather_qps_mask_512:
12139   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12140   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12141   case Intrinsic::x86_avx512_gather_dps_mask_512:
12142   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12143   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12144   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12145   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12146     unsigned Opc;
12147     switch (IntNo) {
12148     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12149     case Intrinsic::x86_avx512_gather_qps_mask_512:
12150       Opc = X86::VGATHERQPSZrm; break;
12151     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12152       Opc = X86::VGATHERQPDZrm; break;
12153     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12154       Opc = X86::VGATHERDPDZrm; break;
12155     case Intrinsic::x86_avx512_gather_dps_mask_512:
12156       Opc = X86::VGATHERDPSZrm; break;
12157     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12158       Opc = X86::VPGATHERQDZrm; break;
12159     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12160       Opc = X86::VPGATHERQQZrm; break;
12161     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12162       Opc = X86::VPGATHERDDZrm; break;
12163     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12164       Opc = X86::VPGATHERDQZrm; break;
12165     }
12166     SDValue Chain = Op.getOperand(0);
12167     SDValue Src   = Op.getOperand(2);
12168     SDValue Mask  = Op.getOperand(3);
12169     SDValue Index = Op.getOperand(4);
12170     SDValue Base  = Op.getOperand(5);
12171     SDValue Scale = Op.getOperand(6);
12172     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12173                           Subtarget);
12174   }
12175   //int_scatter(base, index, v1, scale);
12176   case Intrinsic::x86_avx512_scatter_qpd_512:
12177   case Intrinsic::x86_avx512_scatter_qps_512:
12178   case Intrinsic::x86_avx512_scatter_dpd_512:
12179   case Intrinsic::x86_avx512_scatter_qpi_512:
12180   case Intrinsic::x86_avx512_scatter_qpq_512:
12181   case Intrinsic::x86_avx512_scatter_dpq_512:
12182   case Intrinsic::x86_avx512_scatter_dps_512:
12183   case Intrinsic::x86_avx512_scatter_dpi_512: {
12184     unsigned Opc;
12185     switch (IntNo) {
12186     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12187     case Intrinsic::x86_avx512_scatter_qpd_512:
12188       Opc = X86::VSCATTERQPDZmr; break;
12189     case Intrinsic::x86_avx512_scatter_qps_512:
12190       Opc = X86::VSCATTERQPSZmr; break;
12191     case Intrinsic::x86_avx512_scatter_dpd_512:
12192       Opc = X86::VSCATTERDPDZmr; break;
12193     case Intrinsic::x86_avx512_scatter_dps_512:
12194       Opc = X86::VSCATTERDPSZmr; break;
12195     case Intrinsic::x86_avx512_scatter_qpi_512:
12196       Opc = X86::VPSCATTERQDZmr; break;
12197     case Intrinsic::x86_avx512_scatter_qpq_512:
12198       Opc = X86::VPSCATTERQQZmr; break;
12199     case Intrinsic::x86_avx512_scatter_dpq_512:
12200       Opc = X86::VPSCATTERDQZmr; break;
12201     case Intrinsic::x86_avx512_scatter_dpi_512:
12202       Opc = X86::VPSCATTERDDZmr; break;
12203     }
12204     SDValue Chain = Op.getOperand(0);
12205     SDValue Base  = Op.getOperand(2);
12206     SDValue Index = Op.getOperand(3);
12207     SDValue Src   = Op.getOperand(4);
12208     SDValue Scale = Op.getOperand(5);
12209     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12210   }
12211   //int_scatter_mask(base, mask, index, v1, scale);
12212   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12213   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12214   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12215   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12216   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12217   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12218   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12219   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12220     unsigned Opc;
12221     switch (IntNo) {
12222     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12223     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12224       Opc = X86::VSCATTERQPDZmr; break;
12225     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12226       Opc = X86::VSCATTERQPSZmr; break;
12227     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12228       Opc = X86::VSCATTERDPDZmr; break;
12229     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12230       Opc = X86::VSCATTERDPSZmr; break;
12231     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12232       Opc = X86::VPSCATTERQDZmr; break;
12233     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12234       Opc = X86::VPSCATTERQQZmr; break;
12235     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12236       Opc = X86::VPSCATTERDQZmr; break;
12237     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12238       Opc = X86::VPSCATTERDDZmr; break;
12239     }
12240     SDValue Chain = Op.getOperand(0);
12241     SDValue Base  = Op.getOperand(2);
12242     SDValue Mask  = Op.getOperand(3);
12243     SDValue Index = Op.getOperand(4);
12244     SDValue Src   = Op.getOperand(5);
12245     SDValue Scale = Op.getOperand(6);
12246     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12247   }
12248   // XTEST intrinsics.
12249   case Intrinsic::x86_xtest: {
12250     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12251     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12252     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12253                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12254                                 InTrans);
12255     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12256     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12257                        Ret, SDValue(InTrans.getNode(), 1));
12258   }
12259   }
12260 }
12261
12262 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12263                                            SelectionDAG &DAG) const {
12264   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12265   MFI->setReturnAddressIsTaken(true);
12266
12267   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12268     return SDValue();
12269
12270   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12271   SDLoc dl(Op);
12272   EVT PtrVT = getPointerTy();
12273
12274   if (Depth > 0) {
12275     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12276     const X86RegisterInfo *RegInfo =
12277       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12278     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12279     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12280                        DAG.getNode(ISD::ADD, dl, PtrVT,
12281                                    FrameAddr, Offset),
12282                        MachinePointerInfo(), false, false, false, 0);
12283   }
12284
12285   // Just load the return address.
12286   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12287   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12288                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12289 }
12290
12291 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12292   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12293   MFI->setFrameAddressIsTaken(true);
12294
12295   EVT VT = Op.getValueType();
12296   SDLoc dl(Op);  // FIXME probably not meaningful
12297   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12298   const X86RegisterInfo *RegInfo =
12299     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12300   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12301   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12302           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12303          "Invalid Frame Register!");
12304   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12305   while (Depth--)
12306     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12307                             MachinePointerInfo(),
12308                             false, false, false, 0);
12309   return FrameAddr;
12310 }
12311
12312 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12313                                                      SelectionDAG &DAG) const {
12314   const X86RegisterInfo *RegInfo =
12315     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12316   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12317 }
12318
12319 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12320   SDValue Chain     = Op.getOperand(0);
12321   SDValue Offset    = Op.getOperand(1);
12322   SDValue Handler   = Op.getOperand(2);
12323   SDLoc dl      (Op);
12324
12325   EVT PtrVT = getPointerTy();
12326   const X86RegisterInfo *RegInfo =
12327     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12328   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12329   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12330           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12331          "Invalid Frame Register!");
12332   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12333   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12334
12335   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12336                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12337   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12338   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12339                        false, false, 0);
12340   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12341
12342   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12343                      DAG.getRegister(StoreAddrReg, PtrVT));
12344 }
12345
12346 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12347                                                SelectionDAG &DAG) const {
12348   SDLoc DL(Op);
12349   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12350                      DAG.getVTList(MVT::i32, MVT::Other),
12351                      Op.getOperand(0), Op.getOperand(1));
12352 }
12353
12354 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12355                                                 SelectionDAG &DAG) const {
12356   SDLoc DL(Op);
12357   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12358                      Op.getOperand(0), Op.getOperand(1));
12359 }
12360
12361 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12362   return Op.getOperand(0);
12363 }
12364
12365 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12366                                                 SelectionDAG &DAG) const {
12367   SDValue Root = Op.getOperand(0);
12368   SDValue Trmp = Op.getOperand(1); // trampoline
12369   SDValue FPtr = Op.getOperand(2); // nested function
12370   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12371   SDLoc dl (Op);
12372
12373   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12374   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12375
12376   if (Subtarget->is64Bit()) {
12377     SDValue OutChains[6];
12378
12379     // Large code-model.
12380     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12381     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12382
12383     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12384     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12385
12386     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12387
12388     // Load the pointer to the nested function into R11.
12389     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12390     SDValue Addr = Trmp;
12391     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12392                                 Addr, MachinePointerInfo(TrmpAddr),
12393                                 false, false, 0);
12394
12395     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12396                        DAG.getConstant(2, MVT::i64));
12397     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12398                                 MachinePointerInfo(TrmpAddr, 2),
12399                                 false, false, 2);
12400
12401     // Load the 'nest' parameter value into R10.
12402     // R10 is specified in X86CallingConv.td
12403     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12404     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12405                        DAG.getConstant(10, MVT::i64));
12406     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12407                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12408                                 false, false, 0);
12409
12410     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12411                        DAG.getConstant(12, MVT::i64));
12412     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12413                                 MachinePointerInfo(TrmpAddr, 12),
12414                                 false, false, 2);
12415
12416     // Jump to the nested function.
12417     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12418     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12419                        DAG.getConstant(20, MVT::i64));
12420     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12421                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12422                                 false, false, 0);
12423
12424     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12425     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12426                        DAG.getConstant(22, MVT::i64));
12427     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12428                                 MachinePointerInfo(TrmpAddr, 22),
12429                                 false, false, 0);
12430
12431     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12432   } else {
12433     const Function *Func =
12434       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12435     CallingConv::ID CC = Func->getCallingConv();
12436     unsigned NestReg;
12437
12438     switch (CC) {
12439     default:
12440       llvm_unreachable("Unsupported calling convention");
12441     case CallingConv::C:
12442     case CallingConv::X86_StdCall: {
12443       // Pass 'nest' parameter in ECX.
12444       // Must be kept in sync with X86CallingConv.td
12445       NestReg = X86::ECX;
12446
12447       // Check that ECX wasn't needed by an 'inreg' parameter.
12448       FunctionType *FTy = Func->getFunctionType();
12449       const AttributeSet &Attrs = Func->getAttributes();
12450
12451       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12452         unsigned InRegCount = 0;
12453         unsigned Idx = 1;
12454
12455         for (FunctionType::param_iterator I = FTy->param_begin(),
12456              E = FTy->param_end(); I != E; ++I, ++Idx)
12457           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12458             // FIXME: should only count parameters that are lowered to integers.
12459             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12460
12461         if (InRegCount > 2) {
12462           report_fatal_error("Nest register in use - reduce number of inreg"
12463                              " parameters!");
12464         }
12465       }
12466       break;
12467     }
12468     case CallingConv::X86_FastCall:
12469     case CallingConv::X86_ThisCall:
12470     case CallingConv::Fast:
12471       // Pass 'nest' parameter in EAX.
12472       // Must be kept in sync with X86CallingConv.td
12473       NestReg = X86::EAX;
12474       break;
12475     }
12476
12477     SDValue OutChains[4];
12478     SDValue Addr, Disp;
12479
12480     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12481                        DAG.getConstant(10, MVT::i32));
12482     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12483
12484     // This is storing the opcode for MOV32ri.
12485     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12486     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12487     OutChains[0] = DAG.getStore(Root, dl,
12488                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12489                                 Trmp, MachinePointerInfo(TrmpAddr),
12490                                 false, false, 0);
12491
12492     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12493                        DAG.getConstant(1, MVT::i32));
12494     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12495                                 MachinePointerInfo(TrmpAddr, 1),
12496                                 false, false, 1);
12497
12498     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12499     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12500                        DAG.getConstant(5, MVT::i32));
12501     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12502                                 MachinePointerInfo(TrmpAddr, 5),
12503                                 false, false, 1);
12504
12505     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12506                        DAG.getConstant(6, MVT::i32));
12507     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12508                                 MachinePointerInfo(TrmpAddr, 6),
12509                                 false, false, 1);
12510
12511     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12512   }
12513 }
12514
12515 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12516                                             SelectionDAG &DAG) const {
12517   /*
12518    The rounding mode is in bits 11:10 of FPSR, and has the following
12519    settings:
12520      00 Round to nearest
12521      01 Round to -inf
12522      10 Round to +inf
12523      11 Round to 0
12524
12525   FLT_ROUNDS, on the other hand, expects the following:
12526     -1 Undefined
12527      0 Round to 0
12528      1 Round to nearest
12529      2 Round to +inf
12530      3 Round to -inf
12531
12532   To perform the conversion, we do:
12533     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12534   */
12535
12536   MachineFunction &MF = DAG.getMachineFunction();
12537   const TargetMachine &TM = MF.getTarget();
12538   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12539   unsigned StackAlignment = TFI.getStackAlignment();
12540   MVT VT = Op.getSimpleValueType();
12541   SDLoc DL(Op);
12542
12543   // Save FP Control Word to stack slot
12544   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12545   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12546
12547   MachineMemOperand *MMO =
12548    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12549                            MachineMemOperand::MOStore, 2, 2);
12550
12551   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12552   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12553                                           DAG.getVTList(MVT::Other),
12554                                           Ops, array_lengthof(Ops), MVT::i16,
12555                                           MMO);
12556
12557   // Load FP Control Word from stack slot
12558   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12559                             MachinePointerInfo(), false, false, false, 0);
12560
12561   // Transform as necessary
12562   SDValue CWD1 =
12563     DAG.getNode(ISD::SRL, DL, MVT::i16,
12564                 DAG.getNode(ISD::AND, DL, MVT::i16,
12565                             CWD, DAG.getConstant(0x800, MVT::i16)),
12566                 DAG.getConstant(11, MVT::i8));
12567   SDValue CWD2 =
12568     DAG.getNode(ISD::SRL, DL, MVT::i16,
12569                 DAG.getNode(ISD::AND, DL, MVT::i16,
12570                             CWD, DAG.getConstant(0x400, MVT::i16)),
12571                 DAG.getConstant(9, MVT::i8));
12572
12573   SDValue RetVal =
12574     DAG.getNode(ISD::AND, DL, MVT::i16,
12575                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12576                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12577                             DAG.getConstant(1, MVT::i16)),
12578                 DAG.getConstant(3, MVT::i16));
12579
12580   return DAG.getNode((VT.getSizeInBits() < 16 ?
12581                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12582 }
12583
12584 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12585   MVT VT = Op.getSimpleValueType();
12586   EVT OpVT = VT;
12587   unsigned NumBits = VT.getSizeInBits();
12588   SDLoc dl(Op);
12589
12590   Op = Op.getOperand(0);
12591   if (VT == MVT::i8) {
12592     // Zero extend to i32 since there is not an i8 bsr.
12593     OpVT = MVT::i32;
12594     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12595   }
12596
12597   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12598   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12599   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12600
12601   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12602   SDValue Ops[] = {
12603     Op,
12604     DAG.getConstant(NumBits+NumBits-1, OpVT),
12605     DAG.getConstant(X86::COND_E, MVT::i8),
12606     Op.getValue(1)
12607   };
12608   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12609
12610   // Finally xor with NumBits-1.
12611   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12612
12613   if (VT == MVT::i8)
12614     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12615   return Op;
12616 }
12617
12618 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12619   MVT VT = Op.getSimpleValueType();
12620   EVT OpVT = VT;
12621   unsigned NumBits = VT.getSizeInBits();
12622   SDLoc dl(Op);
12623
12624   Op = Op.getOperand(0);
12625   if (VT == MVT::i8) {
12626     // Zero extend to i32 since there is not an i8 bsr.
12627     OpVT = MVT::i32;
12628     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12629   }
12630
12631   // Issue a bsr (scan bits in reverse).
12632   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12633   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12634
12635   // And xor with NumBits-1.
12636   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12637
12638   if (VT == MVT::i8)
12639     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12640   return Op;
12641 }
12642
12643 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12644   MVT VT = Op.getSimpleValueType();
12645   unsigned NumBits = VT.getSizeInBits();
12646   SDLoc dl(Op);
12647   Op = Op.getOperand(0);
12648
12649   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12650   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12651   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12652
12653   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12654   SDValue Ops[] = {
12655     Op,
12656     DAG.getConstant(NumBits, VT),
12657     DAG.getConstant(X86::COND_E, MVT::i8),
12658     Op.getValue(1)
12659   };
12660   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12661 }
12662
12663 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12664 // ones, and then concatenate the result back.
12665 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12666   MVT VT = Op.getSimpleValueType();
12667
12668   assert(VT.is256BitVector() && VT.isInteger() &&
12669          "Unsupported value type for operation");
12670
12671   unsigned NumElems = VT.getVectorNumElements();
12672   SDLoc dl(Op);
12673
12674   // Extract the LHS vectors
12675   SDValue LHS = Op.getOperand(0);
12676   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12677   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12678
12679   // Extract the RHS vectors
12680   SDValue RHS = Op.getOperand(1);
12681   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12682   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12683
12684   MVT EltVT = VT.getVectorElementType();
12685   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12686
12687   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12688                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12689                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12690 }
12691
12692 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12693   assert(Op.getSimpleValueType().is256BitVector() &&
12694          Op.getSimpleValueType().isInteger() &&
12695          "Only handle AVX 256-bit vector integer operation");
12696   return Lower256IntArith(Op, DAG);
12697 }
12698
12699 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12700   assert(Op.getSimpleValueType().is256BitVector() &&
12701          Op.getSimpleValueType().isInteger() &&
12702          "Only handle AVX 256-bit vector integer operation");
12703   return Lower256IntArith(Op, DAG);
12704 }
12705
12706 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12707                         SelectionDAG &DAG) {
12708   SDLoc dl(Op);
12709   MVT VT = Op.getSimpleValueType();
12710
12711   // Decompose 256-bit ops into smaller 128-bit ops.
12712   if (VT.is256BitVector() && !Subtarget->hasInt256())
12713     return Lower256IntArith(Op, DAG);
12714
12715   SDValue A = Op.getOperand(0);
12716   SDValue B = Op.getOperand(1);
12717
12718   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12719   if (VT == MVT::v4i32) {
12720     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12721            "Should not custom lower when pmuldq is available!");
12722
12723     // Extract the odd parts.
12724     static const int UnpackMask[] = { 1, -1, 3, -1 };
12725     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12726     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12727
12728     // Multiply the even parts.
12729     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12730     // Now multiply odd parts.
12731     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12732
12733     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12734     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12735
12736     // Merge the two vectors back together with a shuffle. This expands into 2
12737     // shuffles.
12738     static const int ShufMask[] = { 0, 4, 2, 6 };
12739     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12740   }
12741
12742   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12743          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12744
12745   //  Ahi = psrlqi(a, 32);
12746   //  Bhi = psrlqi(b, 32);
12747   //
12748   //  AloBlo = pmuludq(a, b);
12749   //  AloBhi = pmuludq(a, Bhi);
12750   //  AhiBlo = pmuludq(Ahi, b);
12751
12752   //  AloBhi = psllqi(AloBhi, 32);
12753   //  AhiBlo = psllqi(AhiBlo, 32);
12754   //  return AloBlo + AloBhi + AhiBlo;
12755
12756   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12757   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12758
12759   // Bit cast to 32-bit vectors for MULUDQ
12760   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12761                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12762   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12763   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12764   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12765   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12766
12767   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12768   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12769   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12770
12771   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12772   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12773
12774   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12775   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12776 }
12777
12778 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12779   MVT VT = Op.getSimpleValueType();
12780   MVT EltTy = VT.getVectorElementType();
12781   unsigned NumElts = VT.getVectorNumElements();
12782   SDValue N0 = Op.getOperand(0);
12783   SDLoc dl(Op);
12784
12785   // Lower sdiv X, pow2-const.
12786   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12787   if (!C)
12788     return SDValue();
12789
12790   APInt SplatValue, SplatUndef;
12791   unsigned SplatBitSize;
12792   bool HasAnyUndefs;
12793   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12794                           HasAnyUndefs) ||
12795       EltTy.getSizeInBits() < SplatBitSize)
12796     return SDValue();
12797
12798   if ((SplatValue != 0) &&
12799       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12800     unsigned Lg2 = SplatValue.countTrailingZeros();
12801     // Splat the sign bit.
12802     SmallVector<SDValue, 16> Sz(NumElts,
12803                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12804                                                 EltTy));
12805     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12806                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12807                                           NumElts));
12808     // Add (N0 < 0) ? abs2 - 1 : 0;
12809     SmallVector<SDValue, 16> Amt(NumElts,
12810                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12811                                                  EltTy));
12812     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12813                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12814                                           NumElts));
12815     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12816     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12817     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12818                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12819                                           NumElts));
12820
12821     // If we're dividing by a positive value, we're done.  Otherwise, we must
12822     // negate the result.
12823     if (SplatValue.isNonNegative())
12824       return SRA;
12825
12826     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12827     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12828     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12829   }
12830   return SDValue();
12831 }
12832
12833 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12834                                          const X86Subtarget *Subtarget) {
12835   MVT VT = Op.getSimpleValueType();
12836   SDLoc dl(Op);
12837   SDValue R = Op.getOperand(0);
12838   SDValue Amt = Op.getOperand(1);
12839
12840   // Optimize shl/srl/sra with constant shift amount.
12841   if (isSplatVector(Amt.getNode())) {
12842     SDValue SclrAmt = Amt->getOperand(0);
12843     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12844       uint64_t ShiftAmt = C->getZExtValue();
12845
12846       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12847           (Subtarget->hasInt256() &&
12848            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12849           (Subtarget->hasAVX512() &&
12850            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12851         if (Op.getOpcode() == ISD::SHL)
12852           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12853                                             DAG);
12854         if (Op.getOpcode() == ISD::SRL)
12855           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12856                                             DAG);
12857         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12858           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12859                                             DAG);
12860       }
12861
12862       if (VT == MVT::v16i8) {
12863         if (Op.getOpcode() == ISD::SHL) {
12864           // Make a large shift.
12865           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12866                                                    MVT::v8i16, R, ShiftAmt,
12867                                                    DAG);
12868           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12869           // Zero out the rightmost bits.
12870           SmallVector<SDValue, 16> V(16,
12871                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12872                                                      MVT::i8));
12873           return DAG.getNode(ISD::AND, dl, VT, SHL,
12874                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12875         }
12876         if (Op.getOpcode() == ISD::SRL) {
12877           // Make a large shift.
12878           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12879                                                    MVT::v8i16, R, ShiftAmt,
12880                                                    DAG);
12881           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12882           // Zero out the leftmost bits.
12883           SmallVector<SDValue, 16> V(16,
12884                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12885                                                      MVT::i8));
12886           return DAG.getNode(ISD::AND, dl, VT, SRL,
12887                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12888         }
12889         if (Op.getOpcode() == ISD::SRA) {
12890           if (ShiftAmt == 7) {
12891             // R s>> 7  ===  R s< 0
12892             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12893             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12894           }
12895
12896           // R s>> a === ((R u>> a) ^ m) - m
12897           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12898           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12899                                                          MVT::i8));
12900           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12901           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12902           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12903           return Res;
12904         }
12905         llvm_unreachable("Unknown shift opcode.");
12906       }
12907
12908       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12909         if (Op.getOpcode() == ISD::SHL) {
12910           // Make a large shift.
12911           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12912                                                    MVT::v16i16, R, ShiftAmt,
12913                                                    DAG);
12914           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12915           // Zero out the rightmost bits.
12916           SmallVector<SDValue, 32> V(32,
12917                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12918                                                      MVT::i8));
12919           return DAG.getNode(ISD::AND, dl, VT, SHL,
12920                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12921         }
12922         if (Op.getOpcode() == ISD::SRL) {
12923           // Make a large shift.
12924           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12925                                                    MVT::v16i16, R, ShiftAmt,
12926                                                    DAG);
12927           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12928           // Zero out the leftmost bits.
12929           SmallVector<SDValue, 32> V(32,
12930                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12931                                                      MVT::i8));
12932           return DAG.getNode(ISD::AND, dl, VT, SRL,
12933                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12934         }
12935         if (Op.getOpcode() == ISD::SRA) {
12936           if (ShiftAmt == 7) {
12937             // R s>> 7  ===  R s< 0
12938             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12939             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12940           }
12941
12942           // R s>> a === ((R u>> a) ^ m) - m
12943           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12944           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12945                                                          MVT::i8));
12946           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12947           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12948           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12949           return Res;
12950         }
12951         llvm_unreachable("Unknown shift opcode.");
12952       }
12953     }
12954   }
12955
12956   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12957   if (!Subtarget->is64Bit() &&
12958       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12959       Amt.getOpcode() == ISD::BITCAST &&
12960       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12961     Amt = Amt.getOperand(0);
12962     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
12963                      VT.getVectorNumElements();
12964     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12965     uint64_t ShiftAmt = 0;
12966     for (unsigned i = 0; i != Ratio; ++i) {
12967       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12968       if (C == 0)
12969         return SDValue();
12970       // 6 == Log2(64)
12971       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12972     }
12973     // Check remaining shift amounts.
12974     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12975       uint64_t ShAmt = 0;
12976       for (unsigned j = 0; j != Ratio; ++j) {
12977         ConstantSDNode *C =
12978           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12979         if (C == 0)
12980           return SDValue();
12981         // 6 == Log2(64)
12982         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12983       }
12984       if (ShAmt != ShiftAmt)
12985         return SDValue();
12986     }
12987     switch (Op.getOpcode()) {
12988     default:
12989       llvm_unreachable("Unknown shift opcode!");
12990     case ISD::SHL:
12991       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12992                                         DAG);
12993     case ISD::SRL:
12994       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12995                                         DAG);
12996     case ISD::SRA:
12997       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12998                                         DAG);
12999     }
13000   }
13001
13002   return SDValue();
13003 }
13004
13005 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13006                                         const X86Subtarget* Subtarget) {
13007   MVT VT = Op.getSimpleValueType();
13008   SDLoc dl(Op);
13009   SDValue R = Op.getOperand(0);
13010   SDValue Amt = Op.getOperand(1);
13011
13012   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13013       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13014       (Subtarget->hasInt256() &&
13015        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13016         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13017        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13018     SDValue BaseShAmt;
13019     EVT EltVT = VT.getVectorElementType();
13020
13021     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13022       unsigned NumElts = VT.getVectorNumElements();
13023       unsigned i, j;
13024       for (i = 0; i != NumElts; ++i) {
13025         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13026           continue;
13027         break;
13028       }
13029       for (j = i; j != NumElts; ++j) {
13030         SDValue Arg = Amt.getOperand(j);
13031         if (Arg.getOpcode() == ISD::UNDEF) continue;
13032         if (Arg != Amt.getOperand(i))
13033           break;
13034       }
13035       if (i != NumElts && j == NumElts)
13036         BaseShAmt = Amt.getOperand(i);
13037     } else {
13038       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13039         Amt = Amt.getOperand(0);
13040       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13041                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13042         SDValue InVec = Amt.getOperand(0);
13043         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13044           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13045           unsigned i = 0;
13046           for (; i != NumElts; ++i) {
13047             SDValue Arg = InVec.getOperand(i);
13048             if (Arg.getOpcode() == ISD::UNDEF) continue;
13049             BaseShAmt = Arg;
13050             break;
13051           }
13052         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13053            if (ConstantSDNode *C =
13054                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13055              unsigned SplatIdx =
13056                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13057              if (C->getZExtValue() == SplatIdx)
13058                BaseShAmt = InVec.getOperand(1);
13059            }
13060         }
13061         if (BaseShAmt.getNode() == 0)
13062           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13063                                   DAG.getIntPtrConstant(0));
13064       }
13065     }
13066
13067     if (BaseShAmt.getNode()) {
13068       if (EltVT.bitsGT(MVT::i32))
13069         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13070       else if (EltVT.bitsLT(MVT::i32))
13071         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13072
13073       switch (Op.getOpcode()) {
13074       default:
13075         llvm_unreachable("Unknown shift opcode!");
13076       case ISD::SHL:
13077         switch (VT.SimpleTy) {
13078         default: return SDValue();
13079         case MVT::v2i64:
13080         case MVT::v4i32:
13081         case MVT::v8i16:
13082         case MVT::v4i64:
13083         case MVT::v8i32:
13084         case MVT::v16i16:
13085         case MVT::v16i32:
13086         case MVT::v8i64:
13087           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13088         }
13089       case ISD::SRA:
13090         switch (VT.SimpleTy) {
13091         default: return SDValue();
13092         case MVT::v4i32:
13093         case MVT::v8i16:
13094         case MVT::v8i32:
13095         case MVT::v16i16:
13096         case MVT::v16i32:
13097         case MVT::v8i64:
13098           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13099         }
13100       case ISD::SRL:
13101         switch (VT.SimpleTy) {
13102         default: return SDValue();
13103         case MVT::v2i64:
13104         case MVT::v4i32:
13105         case MVT::v8i16:
13106         case MVT::v4i64:
13107         case MVT::v8i32:
13108         case MVT::v16i16:
13109         case MVT::v16i32:
13110         case MVT::v8i64:
13111           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13112         }
13113       }
13114     }
13115   }
13116
13117   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13118   if (!Subtarget->is64Bit() &&
13119       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13120       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13121       Amt.getOpcode() == ISD::BITCAST &&
13122       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13123     Amt = Amt.getOperand(0);
13124     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13125                      VT.getVectorNumElements();
13126     std::vector<SDValue> Vals(Ratio);
13127     for (unsigned i = 0; i != Ratio; ++i)
13128       Vals[i] = Amt.getOperand(i);
13129     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13130       for (unsigned j = 0; j != Ratio; ++j)
13131         if (Vals[j] != Amt.getOperand(i + j))
13132           return SDValue();
13133     }
13134     switch (Op.getOpcode()) {
13135     default:
13136       llvm_unreachable("Unknown shift opcode!");
13137     case ISD::SHL:
13138       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13139     case ISD::SRL:
13140       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13141     case ISD::SRA:
13142       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13143     }
13144   }
13145
13146   return SDValue();
13147 }
13148
13149 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13150                           SelectionDAG &DAG) {
13151
13152   MVT VT = Op.getSimpleValueType();
13153   SDLoc dl(Op);
13154   SDValue R = Op.getOperand(0);
13155   SDValue Amt = Op.getOperand(1);
13156   SDValue V;
13157
13158   if (!Subtarget->hasSSE2())
13159     return SDValue();
13160
13161   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13162   if (V.getNode())
13163     return V;
13164
13165   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13166   if (V.getNode())
13167       return V;
13168
13169   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13170     return Op;
13171   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13172   if (Subtarget->hasInt256()) {
13173     if (Op.getOpcode() == ISD::SRL &&
13174         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13175          VT == MVT::v4i64 || VT == MVT::v8i32))
13176       return Op;
13177     if (Op.getOpcode() == ISD::SHL &&
13178         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13179          VT == MVT::v4i64 || VT == MVT::v8i32))
13180       return Op;
13181     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13182       return Op;
13183   }
13184
13185   // If possible, lower this packed shift into a vector multiply instead of
13186   // expanding it into a sequence of scalar shifts.
13187   // Do this only if the vector shift count is a constant build_vector.
13188   if (Op.getOpcode() == ISD::SHL && 
13189       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13190        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13191       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13192     SmallVector<SDValue, 8> Elts;
13193     EVT SVT = VT.getScalarType();
13194     unsigned SVTBits = SVT.getSizeInBits();
13195     const APInt &One = APInt(SVTBits, 1);
13196     unsigned NumElems = VT.getVectorNumElements();
13197
13198     for (unsigned i=0; i !=NumElems; ++i) {
13199       SDValue Op = Amt->getOperand(i);
13200       if (Op->getOpcode() == ISD::UNDEF) {
13201         Elts.push_back(Op);
13202         continue;
13203       }
13204
13205       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13206       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13207       uint64_t ShAmt = C.getZExtValue();
13208       if (ShAmt >= SVTBits) {
13209         Elts.push_back(DAG.getUNDEF(SVT));
13210         continue;
13211       }
13212       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13213     }
13214     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13215     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13216   }
13217
13218   // Lower SHL with variable shift amount.
13219   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13220     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13221
13222     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13223     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13224     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13225     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13226   }
13227
13228   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13229     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13230
13231     // a = a << 5;
13232     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13233     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13234
13235     // Turn 'a' into a mask suitable for VSELECT
13236     SDValue VSelM = DAG.getConstant(0x80, VT);
13237     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13238     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13239
13240     SDValue CM1 = DAG.getConstant(0x0f, VT);
13241     SDValue CM2 = DAG.getConstant(0x3f, VT);
13242
13243     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13244     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13245     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13246     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13247     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13248
13249     // a += a
13250     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13251     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13252     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13253
13254     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13255     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13256     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13257     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13258     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13259
13260     // a += a
13261     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13262     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13263     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13264
13265     // return VSELECT(r, r+r, a);
13266     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13267                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13268     return R;
13269   }
13270
13271   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13272   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13273   // solution better.
13274   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13275     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13276     unsigned ExtOpc =
13277         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13278     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13279     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13280     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13281                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13282     }
13283
13284   // Decompose 256-bit shifts into smaller 128-bit shifts.
13285   if (VT.is256BitVector()) {
13286     unsigned NumElems = VT.getVectorNumElements();
13287     MVT EltVT = VT.getVectorElementType();
13288     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13289
13290     // Extract the two vectors
13291     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13292     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13293
13294     // Recreate the shift amount vectors
13295     SDValue Amt1, Amt2;
13296     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13297       // Constant shift amount
13298       SmallVector<SDValue, 4> Amt1Csts;
13299       SmallVector<SDValue, 4> Amt2Csts;
13300       for (unsigned i = 0; i != NumElems/2; ++i)
13301         Amt1Csts.push_back(Amt->getOperand(i));
13302       for (unsigned i = NumElems/2; i != NumElems; ++i)
13303         Amt2Csts.push_back(Amt->getOperand(i));
13304
13305       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13306                                  &Amt1Csts[0], NumElems/2);
13307       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13308                                  &Amt2Csts[0], NumElems/2);
13309     } else {
13310       // Variable shift amount
13311       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13312       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13313     }
13314
13315     // Issue new vector shifts for the smaller types
13316     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13317     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13318
13319     // Concatenate the result back
13320     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13321   }
13322
13323   return SDValue();
13324 }
13325
13326 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13327   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13328   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13329   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13330   // has only one use.
13331   SDNode *N = Op.getNode();
13332   SDValue LHS = N->getOperand(0);
13333   SDValue RHS = N->getOperand(1);
13334   unsigned BaseOp = 0;
13335   unsigned Cond = 0;
13336   SDLoc DL(Op);
13337   switch (Op.getOpcode()) {
13338   default: llvm_unreachable("Unknown ovf instruction!");
13339   case ISD::SADDO:
13340     // A subtract of one will be selected as a INC. Note that INC doesn't
13341     // set CF, so we can't do this for UADDO.
13342     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13343       if (C->isOne()) {
13344         BaseOp = X86ISD::INC;
13345         Cond = X86::COND_O;
13346         break;
13347       }
13348     BaseOp = X86ISD::ADD;
13349     Cond = X86::COND_O;
13350     break;
13351   case ISD::UADDO:
13352     BaseOp = X86ISD::ADD;
13353     Cond = X86::COND_B;
13354     break;
13355   case ISD::SSUBO:
13356     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13357     // set CF, so we can't do this for USUBO.
13358     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13359       if (C->isOne()) {
13360         BaseOp = X86ISD::DEC;
13361         Cond = X86::COND_O;
13362         break;
13363       }
13364     BaseOp = X86ISD::SUB;
13365     Cond = X86::COND_O;
13366     break;
13367   case ISD::USUBO:
13368     BaseOp = X86ISD::SUB;
13369     Cond = X86::COND_B;
13370     break;
13371   case ISD::SMULO:
13372     BaseOp = X86ISD::SMUL;
13373     Cond = X86::COND_O;
13374     break;
13375   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13376     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13377                                  MVT::i32);
13378     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13379
13380     SDValue SetCC =
13381       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13382                   DAG.getConstant(X86::COND_O, MVT::i32),
13383                   SDValue(Sum.getNode(), 2));
13384
13385     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13386   }
13387   }
13388
13389   // Also sets EFLAGS.
13390   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13391   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13392
13393   SDValue SetCC =
13394     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13395                 DAG.getConstant(Cond, MVT::i32),
13396                 SDValue(Sum.getNode(), 1));
13397
13398   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13399 }
13400
13401 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13402                                                   SelectionDAG &DAG) const {
13403   SDLoc dl(Op);
13404   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13405   MVT VT = Op.getSimpleValueType();
13406
13407   if (!Subtarget->hasSSE2() || !VT.isVector())
13408     return SDValue();
13409
13410   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13411                       ExtraVT.getScalarType().getSizeInBits();
13412
13413   switch (VT.SimpleTy) {
13414     default: return SDValue();
13415     case MVT::v8i32:
13416     case MVT::v16i16:
13417       if (!Subtarget->hasFp256())
13418         return SDValue();
13419       if (!Subtarget->hasInt256()) {
13420         // needs to be split
13421         unsigned NumElems = VT.getVectorNumElements();
13422
13423         // Extract the LHS vectors
13424         SDValue LHS = Op.getOperand(0);
13425         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13426         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13427
13428         MVT EltVT = VT.getVectorElementType();
13429         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13430
13431         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13432         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13433         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13434                                    ExtraNumElems/2);
13435         SDValue Extra = DAG.getValueType(ExtraVT);
13436
13437         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13438         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13439
13440         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13441       }
13442       // fall through
13443     case MVT::v4i32:
13444     case MVT::v8i16: {
13445       SDValue Op0 = Op.getOperand(0);
13446       SDValue Op00 = Op0.getOperand(0);
13447       SDValue Tmp1;
13448       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13449       if (Op0.getOpcode() == ISD::BITCAST &&
13450           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13451         // (sext (vzext x)) -> (vsext x)
13452         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13453         if (Tmp1.getNode()) {
13454           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13455           // This folding is only valid when the in-reg type is a vector of i8,
13456           // i16, or i32.
13457           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13458               ExtraEltVT == MVT::i32) {
13459             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13460             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13461                    "This optimization is invalid without a VZEXT.");
13462             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13463           }
13464           Op0 = Tmp1;
13465         }
13466       }
13467
13468       // If the above didn't work, then just use Shift-Left + Shift-Right.
13469       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13470                                         DAG);
13471       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13472                                         DAG);
13473     }
13474   }
13475 }
13476
13477 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13478                                  SelectionDAG &DAG) {
13479   SDLoc dl(Op);
13480   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13481     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13482   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13483     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13484
13485   // The only fence that needs an instruction is a sequentially-consistent
13486   // cross-thread fence.
13487   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13488     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13489     // no-sse2). There isn't any reason to disable it if the target processor
13490     // supports it.
13491     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13492       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13493
13494     SDValue Chain = Op.getOperand(0);
13495     SDValue Zero = DAG.getConstant(0, MVT::i32);
13496     SDValue Ops[] = {
13497       DAG.getRegister(X86::ESP, MVT::i32), // Base
13498       DAG.getTargetConstant(1, MVT::i8),   // Scale
13499       DAG.getRegister(0, MVT::i32),        // Index
13500       DAG.getTargetConstant(0, MVT::i32),  // Disp
13501       DAG.getRegister(0, MVT::i32),        // Segment.
13502       Zero,
13503       Chain
13504     };
13505     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13506     return SDValue(Res, 0);
13507   }
13508
13509   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13510   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13511 }
13512
13513 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13514                              SelectionDAG &DAG) {
13515   MVT T = Op.getSimpleValueType();
13516   SDLoc DL(Op);
13517   unsigned Reg = 0;
13518   unsigned size = 0;
13519   switch(T.SimpleTy) {
13520   default: llvm_unreachable("Invalid value type!");
13521   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13522   case MVT::i16: Reg = X86::AX;  size = 2; break;
13523   case MVT::i32: Reg = X86::EAX; size = 4; break;
13524   case MVT::i64:
13525     assert(Subtarget->is64Bit() && "Node not type legal!");
13526     Reg = X86::RAX; size = 8;
13527     break;
13528   }
13529   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13530                                     Op.getOperand(2), SDValue());
13531   SDValue Ops[] = { cpIn.getValue(0),
13532                     Op.getOperand(1),
13533                     Op.getOperand(3),
13534                     DAG.getTargetConstant(size, MVT::i8),
13535                     cpIn.getValue(1) };
13536   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13537   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13538   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13539                                            Ops, array_lengthof(Ops), T, MMO);
13540   SDValue cpOut =
13541     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13542   return cpOut;
13543 }
13544
13545 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13546                                      SelectionDAG &DAG) {
13547   assert(Subtarget->is64Bit() && "Result not type legalized?");
13548   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13549   SDValue TheChain = Op.getOperand(0);
13550   SDLoc dl(Op);
13551   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13552   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13553   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13554                                    rax.getValue(2));
13555   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13556                             DAG.getConstant(32, MVT::i8));
13557   SDValue Ops[] = {
13558     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13559     rdx.getValue(1)
13560   };
13561   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13562 }
13563
13564 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13565                             SelectionDAG &DAG) {
13566   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13567   MVT DstVT = Op.getSimpleValueType();
13568   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13569          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13570   assert((DstVT == MVT::i64 ||
13571           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13572          "Unexpected custom BITCAST");
13573   // i64 <=> MMX conversions are Legal.
13574   if (SrcVT==MVT::i64 && DstVT.isVector())
13575     return Op;
13576   if (DstVT==MVT::i64 && SrcVT.isVector())
13577     return Op;
13578   // MMX <=> MMX conversions are Legal.
13579   if (SrcVT.isVector() && DstVT.isVector())
13580     return Op;
13581   // All other conversions need to be expanded.
13582   return SDValue();
13583 }
13584
13585 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13586   SDNode *Node = Op.getNode();
13587   SDLoc dl(Node);
13588   EVT T = Node->getValueType(0);
13589   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13590                               DAG.getConstant(0, T), Node->getOperand(2));
13591   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13592                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13593                        Node->getOperand(0),
13594                        Node->getOperand(1), negOp,
13595                        cast<AtomicSDNode>(Node)->getSrcValue(),
13596                        cast<AtomicSDNode>(Node)->getAlignment(),
13597                        cast<AtomicSDNode>(Node)->getOrdering(),
13598                        cast<AtomicSDNode>(Node)->getSynchScope());
13599 }
13600
13601 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13602   SDNode *Node = Op.getNode();
13603   SDLoc dl(Node);
13604   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13605
13606   // Convert seq_cst store -> xchg
13607   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13608   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13609   //        (The only way to get a 16-byte store is cmpxchg16b)
13610   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13611   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13612       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13613     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13614                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13615                                  Node->getOperand(0),
13616                                  Node->getOperand(1), Node->getOperand(2),
13617                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13618                                  cast<AtomicSDNode>(Node)->getOrdering(),
13619                                  cast<AtomicSDNode>(Node)->getSynchScope());
13620     return Swap.getValue(1);
13621   }
13622   // Other atomic stores have a simple pattern.
13623   return Op;
13624 }
13625
13626 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13627   EVT VT = Op.getNode()->getSimpleValueType(0);
13628
13629   // Let legalize expand this if it isn't a legal type yet.
13630   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13631     return SDValue();
13632
13633   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13634
13635   unsigned Opc;
13636   bool ExtraOp = false;
13637   switch (Op.getOpcode()) {
13638   default: llvm_unreachable("Invalid code");
13639   case ISD::ADDC: Opc = X86ISD::ADD; break;
13640   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13641   case ISD::SUBC: Opc = X86ISD::SUB; break;
13642   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13643   }
13644
13645   if (!ExtraOp)
13646     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13647                        Op.getOperand(1));
13648   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13649                      Op.getOperand(1), Op.getOperand(2));
13650 }
13651
13652 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13653                             SelectionDAG &DAG) {
13654   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13655
13656   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13657   // which returns the values as { float, float } (in XMM0) or
13658   // { double, double } (which is returned in XMM0, XMM1).
13659   SDLoc dl(Op);
13660   SDValue Arg = Op.getOperand(0);
13661   EVT ArgVT = Arg.getValueType();
13662   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13663
13664   TargetLowering::ArgListTy Args;
13665   TargetLowering::ArgListEntry Entry;
13666
13667   Entry.Node = Arg;
13668   Entry.Ty = ArgTy;
13669   Entry.isSExt = false;
13670   Entry.isZExt = false;
13671   Args.push_back(Entry);
13672
13673   bool isF64 = ArgVT == MVT::f64;
13674   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13675   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13676   // the results are returned via SRet in memory.
13677   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13679   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13680
13681   Type *RetTy = isF64
13682     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13683     : (Type*)VectorType::get(ArgTy, 4);
13684   TargetLowering::
13685     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13686                          false, false, false, false, 0,
13687                          CallingConv::C, /*isTaillCall=*/false,
13688                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13689                          Callee, Args, DAG, dl);
13690   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13691
13692   if (isF64)
13693     // Returned in xmm0 and xmm1.
13694     return CallResult.first;
13695
13696   // Returned in bits 0:31 and 32:64 xmm0.
13697   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13698                                CallResult.first, DAG.getIntPtrConstant(0));
13699   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13700                                CallResult.first, DAG.getIntPtrConstant(1));
13701   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13702   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13703 }
13704
13705 /// LowerOperation - Provide custom lowering hooks for some operations.
13706 ///
13707 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13708   switch (Op.getOpcode()) {
13709   default: llvm_unreachable("Should not custom lower this!");
13710   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13711   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13712   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13713   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13714   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13715   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13716   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13717   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13718   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13719   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13720   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13721   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13722   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13723   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13724   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13725   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13726   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13727   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13728   case ISD::SHL_PARTS:
13729   case ISD::SRA_PARTS:
13730   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13731   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13732   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13733   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13734   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13735   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13736   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13737   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13738   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13739   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13740   case ISD::FABS:               return LowerFABS(Op, DAG);
13741   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13742   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13743   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13744   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13745   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13746   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13747   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13748   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13749   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13750   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13751   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13752   case ISD::INTRINSIC_VOID:
13753   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13754   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13755   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13756   case ISD::FRAME_TO_ARGS_OFFSET:
13757                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13758   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13759   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13760   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13761   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13762   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13763   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13764   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13765   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13766   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13767   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13768   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13769   case ISD::SRA:
13770   case ISD::SRL:
13771   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13772   case ISD::SADDO:
13773   case ISD::UADDO:
13774   case ISD::SSUBO:
13775   case ISD::USUBO:
13776   case ISD::SMULO:
13777   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13778   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13779   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13780   case ISD::ADDC:
13781   case ISD::ADDE:
13782   case ISD::SUBC:
13783   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13784   case ISD::ADD:                return LowerADD(Op, DAG);
13785   case ISD::SUB:                return LowerSUB(Op, DAG);
13786   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13787   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13788   }
13789 }
13790
13791 static void ReplaceATOMIC_LOAD(SDNode *Node,
13792                                   SmallVectorImpl<SDValue> &Results,
13793                                   SelectionDAG &DAG) {
13794   SDLoc dl(Node);
13795   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13796
13797   // Convert wide load -> cmpxchg8b/cmpxchg16b
13798   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13799   //        (The only way to get a 16-byte load is cmpxchg16b)
13800   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13801   SDValue Zero = DAG.getConstant(0, VT);
13802   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13803                                Node->getOperand(0),
13804                                Node->getOperand(1), Zero, Zero,
13805                                cast<AtomicSDNode>(Node)->getMemOperand(),
13806                                cast<AtomicSDNode>(Node)->getOrdering(),
13807                                cast<AtomicSDNode>(Node)->getOrdering(),
13808                                cast<AtomicSDNode>(Node)->getSynchScope());
13809   Results.push_back(Swap.getValue(0));
13810   Results.push_back(Swap.getValue(1));
13811 }
13812
13813 static void
13814 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13815                         SelectionDAG &DAG, unsigned NewOp) {
13816   SDLoc dl(Node);
13817   assert (Node->getValueType(0) == MVT::i64 &&
13818           "Only know how to expand i64 atomics");
13819
13820   SDValue Chain = Node->getOperand(0);
13821   SDValue In1 = Node->getOperand(1);
13822   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13823                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13824   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13825                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13826   SDValue Ops[] = { Chain, In1, In2L, In2H };
13827   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13828   SDValue Result =
13829     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13830                             cast<MemSDNode>(Node)->getMemOperand());
13831   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13832   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13833   Results.push_back(Result.getValue(2));
13834 }
13835
13836 /// ReplaceNodeResults - Replace a node with an illegal result type
13837 /// with a new node built out of custom code.
13838 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13839                                            SmallVectorImpl<SDValue>&Results,
13840                                            SelectionDAG &DAG) const {
13841   SDLoc dl(N);
13842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13843   switch (N->getOpcode()) {
13844   default:
13845     llvm_unreachable("Do not know how to custom type legalize this operation!");
13846   case ISD::SIGN_EXTEND_INREG:
13847   case ISD::ADDC:
13848   case ISD::ADDE:
13849   case ISD::SUBC:
13850   case ISD::SUBE:
13851     // We don't want to expand or promote these.
13852     return;
13853   case ISD::FP_TO_SINT:
13854   case ISD::FP_TO_UINT: {
13855     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13856
13857     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13858       return;
13859
13860     std::pair<SDValue,SDValue> Vals =
13861         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13862     SDValue FIST = Vals.first, StackSlot = Vals.second;
13863     if (FIST.getNode() != 0) {
13864       EVT VT = N->getValueType(0);
13865       // Return a load from the stack slot.
13866       if (StackSlot.getNode() != 0)
13867         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13868                                       MachinePointerInfo(),
13869                                       false, false, false, 0));
13870       else
13871         Results.push_back(FIST);
13872     }
13873     return;
13874   }
13875   case ISD::UINT_TO_FP: {
13876     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13877     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13878         N->getValueType(0) != MVT::v2f32)
13879       return;
13880     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13881                                  N->getOperand(0));
13882     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13883                                      MVT::f64);
13884     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13885     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13886                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13887     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13888     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13889     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13890     return;
13891   }
13892   case ISD::FP_ROUND: {
13893     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13894         return;
13895     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13896     Results.push_back(V);
13897     return;
13898   }
13899   case ISD::READCYCLECOUNTER: {
13900     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13901     SDValue TheChain = N->getOperand(0);
13902     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13903     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13904                                      rd.getValue(1));
13905     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13906                                      eax.getValue(2));
13907     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13908     SDValue Ops[] = { eax, edx };
13909     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13910                                   array_lengthof(Ops)));
13911     Results.push_back(edx.getValue(1));
13912     return;
13913   }
13914   case ISD::ATOMIC_CMP_SWAP: {
13915     EVT T = N->getValueType(0);
13916     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13917     bool Regs64bit = T == MVT::i128;
13918     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13919     SDValue cpInL, cpInH;
13920     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13921                         DAG.getConstant(0, HalfT));
13922     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13923                         DAG.getConstant(1, HalfT));
13924     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13925                              Regs64bit ? X86::RAX : X86::EAX,
13926                              cpInL, SDValue());
13927     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13928                              Regs64bit ? X86::RDX : X86::EDX,
13929                              cpInH, cpInL.getValue(1));
13930     SDValue swapInL, swapInH;
13931     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13932                           DAG.getConstant(0, HalfT));
13933     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13934                           DAG.getConstant(1, HalfT));
13935     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13936                                Regs64bit ? X86::RBX : X86::EBX,
13937                                swapInL, cpInH.getValue(1));
13938     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13939                                Regs64bit ? X86::RCX : X86::ECX,
13940                                swapInH, swapInL.getValue(1));
13941     SDValue Ops[] = { swapInH.getValue(0),
13942                       N->getOperand(1),
13943                       swapInH.getValue(1) };
13944     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13945     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13946     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13947                                   X86ISD::LCMPXCHG8_DAG;
13948     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13949                                              Ops, array_lengthof(Ops), T, MMO);
13950     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13951                                         Regs64bit ? X86::RAX : X86::EAX,
13952                                         HalfT, Result.getValue(1));
13953     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13954                                         Regs64bit ? X86::RDX : X86::EDX,
13955                                         HalfT, cpOutL.getValue(2));
13956     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13957     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13958     Results.push_back(cpOutH.getValue(1));
13959     return;
13960   }
13961   case ISD::ATOMIC_LOAD_ADD:
13962   case ISD::ATOMIC_LOAD_AND:
13963   case ISD::ATOMIC_LOAD_NAND:
13964   case ISD::ATOMIC_LOAD_OR:
13965   case ISD::ATOMIC_LOAD_SUB:
13966   case ISD::ATOMIC_LOAD_XOR:
13967   case ISD::ATOMIC_LOAD_MAX:
13968   case ISD::ATOMIC_LOAD_MIN:
13969   case ISD::ATOMIC_LOAD_UMAX:
13970   case ISD::ATOMIC_LOAD_UMIN:
13971   case ISD::ATOMIC_SWAP: {
13972     unsigned Opc;
13973     switch (N->getOpcode()) {
13974     default: llvm_unreachable("Unexpected opcode");
13975     case ISD::ATOMIC_LOAD_ADD:
13976       Opc = X86ISD::ATOMADD64_DAG;
13977       break;
13978     case ISD::ATOMIC_LOAD_AND:
13979       Opc = X86ISD::ATOMAND64_DAG;
13980       break;
13981     case ISD::ATOMIC_LOAD_NAND:
13982       Opc = X86ISD::ATOMNAND64_DAG;
13983       break;
13984     case ISD::ATOMIC_LOAD_OR:
13985       Opc = X86ISD::ATOMOR64_DAG;
13986       break;
13987     case ISD::ATOMIC_LOAD_SUB:
13988       Opc = X86ISD::ATOMSUB64_DAG;
13989       break;
13990     case ISD::ATOMIC_LOAD_XOR:
13991       Opc = X86ISD::ATOMXOR64_DAG;
13992       break;
13993     case ISD::ATOMIC_LOAD_MAX:
13994       Opc = X86ISD::ATOMMAX64_DAG;
13995       break;
13996     case ISD::ATOMIC_LOAD_MIN:
13997       Opc = X86ISD::ATOMMIN64_DAG;
13998       break;
13999     case ISD::ATOMIC_LOAD_UMAX:
14000       Opc = X86ISD::ATOMUMAX64_DAG;
14001       break;
14002     case ISD::ATOMIC_LOAD_UMIN:
14003       Opc = X86ISD::ATOMUMIN64_DAG;
14004       break;
14005     case ISD::ATOMIC_SWAP:
14006       Opc = X86ISD::ATOMSWAP64_DAG;
14007       break;
14008     }
14009     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14010     return;
14011   }
14012   case ISD::ATOMIC_LOAD:
14013     ReplaceATOMIC_LOAD(N, Results, DAG);
14014   }
14015 }
14016
14017 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14018   switch (Opcode) {
14019   default: return NULL;
14020   case X86ISD::BSF:                return "X86ISD::BSF";
14021   case X86ISD::BSR:                return "X86ISD::BSR";
14022   case X86ISD::SHLD:               return "X86ISD::SHLD";
14023   case X86ISD::SHRD:               return "X86ISD::SHRD";
14024   case X86ISD::FAND:               return "X86ISD::FAND";
14025   case X86ISD::FANDN:              return "X86ISD::FANDN";
14026   case X86ISD::FOR:                return "X86ISD::FOR";
14027   case X86ISD::FXOR:               return "X86ISD::FXOR";
14028   case X86ISD::FSRL:               return "X86ISD::FSRL";
14029   case X86ISD::FILD:               return "X86ISD::FILD";
14030   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14031   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14032   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14033   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14034   case X86ISD::FLD:                return "X86ISD::FLD";
14035   case X86ISD::FST:                return "X86ISD::FST";
14036   case X86ISD::CALL:               return "X86ISD::CALL";
14037   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14038   case X86ISD::BT:                 return "X86ISD::BT";
14039   case X86ISD::CMP:                return "X86ISD::CMP";
14040   case X86ISD::COMI:               return "X86ISD::COMI";
14041   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14042   case X86ISD::CMPM:               return "X86ISD::CMPM";
14043   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14044   case X86ISD::SETCC:              return "X86ISD::SETCC";
14045   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14046   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14047   case X86ISD::CMOV:               return "X86ISD::CMOV";
14048   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14049   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14050   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14051   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14052   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14053   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14054   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14055   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14056   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14057   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14058   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14059   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14060   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14061   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14062   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14063   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14064   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14065   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14066   case X86ISD::HADD:               return "X86ISD::HADD";
14067   case X86ISD::HSUB:               return "X86ISD::HSUB";
14068   case X86ISD::FHADD:              return "X86ISD::FHADD";
14069   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14070   case X86ISD::UMAX:               return "X86ISD::UMAX";
14071   case X86ISD::UMIN:               return "X86ISD::UMIN";
14072   case X86ISD::SMAX:               return "X86ISD::SMAX";
14073   case X86ISD::SMIN:               return "X86ISD::SMIN";
14074   case X86ISD::FMAX:               return "X86ISD::FMAX";
14075   case X86ISD::FMIN:               return "X86ISD::FMIN";
14076   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14077   case X86ISD::FMINC:              return "X86ISD::FMINC";
14078   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14079   case X86ISD::FRCP:               return "X86ISD::FRCP";
14080   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14081   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14082   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14083   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14084   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14085   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14086   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14087   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14088   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14089   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14090   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14091   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14092   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14093   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14094   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14095   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14096   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14097   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14098   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14099   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14100   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14101   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14102   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14103   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14104   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14105   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14106   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14107   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14108   case X86ISD::VSHL:               return "X86ISD::VSHL";
14109   case X86ISD::VSRL:               return "X86ISD::VSRL";
14110   case X86ISD::VSRA:               return "X86ISD::VSRA";
14111   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14112   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14113   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14114   case X86ISD::CMPP:               return "X86ISD::CMPP";
14115   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14116   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14117   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14118   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14119   case X86ISD::ADD:                return "X86ISD::ADD";
14120   case X86ISD::SUB:                return "X86ISD::SUB";
14121   case X86ISD::ADC:                return "X86ISD::ADC";
14122   case X86ISD::SBB:                return "X86ISD::SBB";
14123   case X86ISD::SMUL:               return "X86ISD::SMUL";
14124   case X86ISD::UMUL:               return "X86ISD::UMUL";
14125   case X86ISD::INC:                return "X86ISD::INC";
14126   case X86ISD::DEC:                return "X86ISD::DEC";
14127   case X86ISD::OR:                 return "X86ISD::OR";
14128   case X86ISD::XOR:                return "X86ISD::XOR";
14129   case X86ISD::AND:                return "X86ISD::AND";
14130   case X86ISD::BZHI:               return "X86ISD::BZHI";
14131   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14132   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14133   case X86ISD::PTEST:              return "X86ISD::PTEST";
14134   case X86ISD::TESTP:              return "X86ISD::TESTP";
14135   case X86ISD::TESTM:              return "X86ISD::TESTM";
14136   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14137   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14138   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14139   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14140   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14141   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14142   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14143   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14144   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14145   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14146   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14147   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14148   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14149   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14150   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14151   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14152   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14153   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14154   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14155   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14156   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14157   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14158   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14159   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14160   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14161   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14162   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14163   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14164   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14165   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14166   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14167   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14168   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14169   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14170   case X86ISD::SAHF:               return "X86ISD::SAHF";
14171   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14172   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14173   case X86ISD::FMADD:              return "X86ISD::FMADD";
14174   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14175   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14176   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14177   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14178   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14179   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14180   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14181   case X86ISD::XTEST:              return "X86ISD::XTEST";
14182   }
14183 }
14184
14185 // isLegalAddressingMode - Return true if the addressing mode represented
14186 // by AM is legal for this target, for a load/store of the specified type.
14187 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14188                                               Type *Ty) const {
14189   // X86 supports extremely general addressing modes.
14190   CodeModel::Model M = getTargetMachine().getCodeModel();
14191   Reloc::Model R = getTargetMachine().getRelocationModel();
14192
14193   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14194   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14195     return false;
14196
14197   if (AM.BaseGV) {
14198     unsigned GVFlags =
14199       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14200
14201     // If a reference to this global requires an extra load, we can't fold it.
14202     if (isGlobalStubReference(GVFlags))
14203       return false;
14204
14205     // If BaseGV requires a register for the PIC base, we cannot also have a
14206     // BaseReg specified.
14207     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14208       return false;
14209
14210     // If lower 4G is not available, then we must use rip-relative addressing.
14211     if ((M != CodeModel::Small || R != Reloc::Static) &&
14212         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14213       return false;
14214   }
14215
14216   switch (AM.Scale) {
14217   case 0:
14218   case 1:
14219   case 2:
14220   case 4:
14221   case 8:
14222     // These scales always work.
14223     break;
14224   case 3:
14225   case 5:
14226   case 9:
14227     // These scales are formed with basereg+scalereg.  Only accept if there is
14228     // no basereg yet.
14229     if (AM.HasBaseReg)
14230       return false;
14231     break;
14232   default:  // Other stuff never works.
14233     return false;
14234   }
14235
14236   return true;
14237 }
14238
14239 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14240   unsigned Bits = Ty->getScalarSizeInBits();
14241
14242   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14243   // particularly cheaper than those without.
14244   if (Bits == 8)
14245     return false;
14246
14247   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14248   // variable shifts just as cheap as scalar ones.
14249   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14250     return false;
14251
14252   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14253   // fully general vector.
14254   return true;
14255 }
14256
14257 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14258   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14259     return false;
14260   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14261   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14262   return NumBits1 > NumBits2;
14263 }
14264
14265 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14266   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14267     return false;
14268
14269   if (!isTypeLegal(EVT::getEVT(Ty1)))
14270     return false;
14271
14272   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14273
14274   // Assuming the caller doesn't have a zeroext or signext return parameter,
14275   // truncation all the way down to i1 is valid.
14276   return true;
14277 }
14278
14279 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14280   return isInt<32>(Imm);
14281 }
14282
14283 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14284   // Can also use sub to handle negated immediates.
14285   return isInt<32>(Imm);
14286 }
14287
14288 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14289   if (!VT1.isInteger() || !VT2.isInteger())
14290     return false;
14291   unsigned NumBits1 = VT1.getSizeInBits();
14292   unsigned NumBits2 = VT2.getSizeInBits();
14293   return NumBits1 > NumBits2;
14294 }
14295
14296 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14297   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14298   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14299 }
14300
14301 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14302   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14303   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14304 }
14305
14306 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14307   EVT VT1 = Val.getValueType();
14308   if (isZExtFree(VT1, VT2))
14309     return true;
14310
14311   if (Val.getOpcode() != ISD::LOAD)
14312     return false;
14313
14314   if (!VT1.isSimple() || !VT1.isInteger() ||
14315       !VT2.isSimple() || !VT2.isInteger())
14316     return false;
14317
14318   switch (VT1.getSimpleVT().SimpleTy) {
14319   default: break;
14320   case MVT::i8:
14321   case MVT::i16:
14322   case MVT::i32:
14323     // X86 has 8, 16, and 32-bit zero-extending loads.
14324     return true;
14325   }
14326
14327   return false;
14328 }
14329
14330 bool
14331 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14332   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14333     return false;
14334
14335   VT = VT.getScalarType();
14336
14337   if (!VT.isSimple())
14338     return false;
14339
14340   switch (VT.getSimpleVT().SimpleTy) {
14341   case MVT::f32:
14342   case MVT::f64:
14343     return true;
14344   default:
14345     break;
14346   }
14347
14348   return false;
14349 }
14350
14351 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14352   // i16 instructions are longer (0x66 prefix) and potentially slower.
14353   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14354 }
14355
14356 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14357 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14358 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14359 /// are assumed to be legal.
14360 bool
14361 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14362                                       EVT VT) const {
14363   if (!VT.isSimple())
14364     return false;
14365
14366   MVT SVT = VT.getSimpleVT();
14367
14368   // Very little shuffling can be done for 64-bit vectors right now.
14369   if (VT.getSizeInBits() == 64)
14370     return false;
14371
14372   // FIXME: pshufb, blends, shifts.
14373   return (SVT.getVectorNumElements() == 2 ||
14374           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14375           isMOVLMask(M, SVT) ||
14376           isSHUFPMask(M, SVT) ||
14377           isPSHUFDMask(M, SVT) ||
14378           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14379           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14380           isPALIGNRMask(M, SVT, Subtarget) ||
14381           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14382           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14383           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14384           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14385 }
14386
14387 bool
14388 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14389                                           EVT VT) const {
14390   if (!VT.isSimple())
14391     return false;
14392
14393   MVT SVT = VT.getSimpleVT();
14394   unsigned NumElts = SVT.getVectorNumElements();
14395   // FIXME: This collection of masks seems suspect.
14396   if (NumElts == 2)
14397     return true;
14398   if (NumElts == 4 && SVT.is128BitVector()) {
14399     return (isMOVLMask(Mask, SVT)  ||
14400             isCommutedMOVLMask(Mask, SVT, true) ||
14401             isSHUFPMask(Mask, SVT) ||
14402             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14403   }
14404   return false;
14405 }
14406
14407 //===----------------------------------------------------------------------===//
14408 //                           X86 Scheduler Hooks
14409 //===----------------------------------------------------------------------===//
14410
14411 /// Utility function to emit xbegin specifying the start of an RTM region.
14412 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14413                                      const TargetInstrInfo *TII) {
14414   DebugLoc DL = MI->getDebugLoc();
14415
14416   const BasicBlock *BB = MBB->getBasicBlock();
14417   MachineFunction::iterator I = MBB;
14418   ++I;
14419
14420   // For the v = xbegin(), we generate
14421   //
14422   // thisMBB:
14423   //  xbegin sinkMBB
14424   //
14425   // mainMBB:
14426   //  eax = -1
14427   //
14428   // sinkMBB:
14429   //  v = eax
14430
14431   MachineBasicBlock *thisMBB = MBB;
14432   MachineFunction *MF = MBB->getParent();
14433   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14434   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14435   MF->insert(I, mainMBB);
14436   MF->insert(I, sinkMBB);
14437
14438   // Transfer the remainder of BB and its successor edges to sinkMBB.
14439   sinkMBB->splice(sinkMBB->begin(), MBB,
14440                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14441   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14442
14443   // thisMBB:
14444   //  xbegin sinkMBB
14445   //  # fallthrough to mainMBB
14446   //  # abortion to sinkMBB
14447   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14448   thisMBB->addSuccessor(mainMBB);
14449   thisMBB->addSuccessor(sinkMBB);
14450
14451   // mainMBB:
14452   //  EAX = -1
14453   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14454   mainMBB->addSuccessor(sinkMBB);
14455
14456   // sinkMBB:
14457   // EAX is live into the sinkMBB
14458   sinkMBB->addLiveIn(X86::EAX);
14459   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14460           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14461     .addReg(X86::EAX);
14462
14463   MI->eraseFromParent();
14464   return sinkMBB;
14465 }
14466
14467 // Get CMPXCHG opcode for the specified data type.
14468 static unsigned getCmpXChgOpcode(EVT VT) {
14469   switch (VT.getSimpleVT().SimpleTy) {
14470   case MVT::i8:  return X86::LCMPXCHG8;
14471   case MVT::i16: return X86::LCMPXCHG16;
14472   case MVT::i32: return X86::LCMPXCHG32;
14473   case MVT::i64: return X86::LCMPXCHG64;
14474   default:
14475     break;
14476   }
14477   llvm_unreachable("Invalid operand size!");
14478 }
14479
14480 // Get LOAD opcode for the specified data type.
14481 static unsigned getLoadOpcode(EVT VT) {
14482   switch (VT.getSimpleVT().SimpleTy) {
14483   case MVT::i8:  return X86::MOV8rm;
14484   case MVT::i16: return X86::MOV16rm;
14485   case MVT::i32: return X86::MOV32rm;
14486   case MVT::i64: return X86::MOV64rm;
14487   default:
14488     break;
14489   }
14490   llvm_unreachable("Invalid operand size!");
14491 }
14492
14493 // Get opcode of the non-atomic one from the specified atomic instruction.
14494 static unsigned getNonAtomicOpcode(unsigned Opc) {
14495   switch (Opc) {
14496   case X86::ATOMAND8:  return X86::AND8rr;
14497   case X86::ATOMAND16: return X86::AND16rr;
14498   case X86::ATOMAND32: return X86::AND32rr;
14499   case X86::ATOMAND64: return X86::AND64rr;
14500   case X86::ATOMOR8:   return X86::OR8rr;
14501   case X86::ATOMOR16:  return X86::OR16rr;
14502   case X86::ATOMOR32:  return X86::OR32rr;
14503   case X86::ATOMOR64:  return X86::OR64rr;
14504   case X86::ATOMXOR8:  return X86::XOR8rr;
14505   case X86::ATOMXOR16: return X86::XOR16rr;
14506   case X86::ATOMXOR32: return X86::XOR32rr;
14507   case X86::ATOMXOR64: return X86::XOR64rr;
14508   }
14509   llvm_unreachable("Unhandled atomic-load-op opcode!");
14510 }
14511
14512 // Get opcode of the non-atomic one from the specified atomic instruction with
14513 // extra opcode.
14514 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14515                                                unsigned &ExtraOpc) {
14516   switch (Opc) {
14517   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14518   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14519   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14520   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14521   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14522   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14523   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14524   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14525   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14526   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14527   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14528   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14529   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14530   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14531   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14532   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14533   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14534   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14535   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14536   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14537   }
14538   llvm_unreachable("Unhandled atomic-load-op opcode!");
14539 }
14540
14541 // Get opcode of the non-atomic one from the specified atomic instruction for
14542 // 64-bit data type on 32-bit target.
14543 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14544   switch (Opc) {
14545   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14546   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14547   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14548   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14549   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14550   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14551   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14552   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14553   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14554   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14555   }
14556   llvm_unreachable("Unhandled atomic-load-op opcode!");
14557 }
14558
14559 // Get opcode of the non-atomic one from the specified atomic instruction for
14560 // 64-bit data type on 32-bit target with extra opcode.
14561 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14562                                                    unsigned &HiOpc,
14563                                                    unsigned &ExtraOpc) {
14564   switch (Opc) {
14565   case X86::ATOMNAND6432:
14566     ExtraOpc = X86::NOT32r;
14567     HiOpc = X86::AND32rr;
14568     return X86::AND32rr;
14569   }
14570   llvm_unreachable("Unhandled atomic-load-op opcode!");
14571 }
14572
14573 // Get pseudo CMOV opcode from the specified data type.
14574 static unsigned getPseudoCMOVOpc(EVT VT) {
14575   switch (VT.getSimpleVT().SimpleTy) {
14576   case MVT::i8:  return X86::CMOV_GR8;
14577   case MVT::i16: return X86::CMOV_GR16;
14578   case MVT::i32: return X86::CMOV_GR32;
14579   default:
14580     break;
14581   }
14582   llvm_unreachable("Unknown CMOV opcode!");
14583 }
14584
14585 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14586 // They will be translated into a spin-loop or compare-exchange loop from
14587 //
14588 //    ...
14589 //    dst = atomic-fetch-op MI.addr, MI.val
14590 //    ...
14591 //
14592 // to
14593 //
14594 //    ...
14595 //    t1 = LOAD MI.addr
14596 // loop:
14597 //    t4 = phi(t1, t3 / loop)
14598 //    t2 = OP MI.val, t4
14599 //    EAX = t4
14600 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14601 //    t3 = EAX
14602 //    JNE loop
14603 // sink:
14604 //    dst = t3
14605 //    ...
14606 MachineBasicBlock *
14607 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14608                                        MachineBasicBlock *MBB) const {
14609   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14610   DebugLoc DL = MI->getDebugLoc();
14611
14612   MachineFunction *MF = MBB->getParent();
14613   MachineRegisterInfo &MRI = MF->getRegInfo();
14614
14615   const BasicBlock *BB = MBB->getBasicBlock();
14616   MachineFunction::iterator I = MBB;
14617   ++I;
14618
14619   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14620          "Unexpected number of operands");
14621
14622   assert(MI->hasOneMemOperand() &&
14623          "Expected atomic-load-op to have one memoperand");
14624
14625   // Memory Reference
14626   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14627   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14628
14629   unsigned DstReg, SrcReg;
14630   unsigned MemOpndSlot;
14631
14632   unsigned CurOp = 0;
14633
14634   DstReg = MI->getOperand(CurOp++).getReg();
14635   MemOpndSlot = CurOp;
14636   CurOp += X86::AddrNumOperands;
14637   SrcReg = MI->getOperand(CurOp++).getReg();
14638
14639   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14640   MVT::SimpleValueType VT = *RC->vt_begin();
14641   unsigned t1 = MRI.createVirtualRegister(RC);
14642   unsigned t2 = MRI.createVirtualRegister(RC);
14643   unsigned t3 = MRI.createVirtualRegister(RC);
14644   unsigned t4 = MRI.createVirtualRegister(RC);
14645   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14646
14647   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14648   unsigned LOADOpc = getLoadOpcode(VT);
14649
14650   // For the atomic load-arith operator, we generate
14651   //
14652   //  thisMBB:
14653   //    t1 = LOAD [MI.addr]
14654   //  mainMBB:
14655   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14656   //    t1 = OP MI.val, EAX
14657   //    EAX = t4
14658   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14659   //    t3 = EAX
14660   //    JNE mainMBB
14661   //  sinkMBB:
14662   //    dst = t3
14663
14664   MachineBasicBlock *thisMBB = MBB;
14665   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14666   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14667   MF->insert(I, mainMBB);
14668   MF->insert(I, sinkMBB);
14669
14670   MachineInstrBuilder MIB;
14671
14672   // Transfer the remainder of BB and its successor edges to sinkMBB.
14673   sinkMBB->splice(sinkMBB->begin(), MBB,
14674                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14675   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14676
14677   // thisMBB:
14678   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14679   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14680     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14681     if (NewMO.isReg())
14682       NewMO.setIsKill(false);
14683     MIB.addOperand(NewMO);
14684   }
14685   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14686     unsigned flags = (*MMOI)->getFlags();
14687     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14688     MachineMemOperand *MMO =
14689       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14690                                (*MMOI)->getSize(),
14691                                (*MMOI)->getBaseAlignment(),
14692                                (*MMOI)->getTBAAInfo(),
14693                                (*MMOI)->getRanges());
14694     MIB.addMemOperand(MMO);
14695   }
14696
14697   thisMBB->addSuccessor(mainMBB);
14698
14699   // mainMBB:
14700   MachineBasicBlock *origMainMBB = mainMBB;
14701
14702   // Add a PHI.
14703   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14704                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14705
14706   unsigned Opc = MI->getOpcode();
14707   switch (Opc) {
14708   default:
14709     llvm_unreachable("Unhandled atomic-load-op opcode!");
14710   case X86::ATOMAND8:
14711   case X86::ATOMAND16:
14712   case X86::ATOMAND32:
14713   case X86::ATOMAND64:
14714   case X86::ATOMOR8:
14715   case X86::ATOMOR16:
14716   case X86::ATOMOR32:
14717   case X86::ATOMOR64:
14718   case X86::ATOMXOR8:
14719   case X86::ATOMXOR16:
14720   case X86::ATOMXOR32:
14721   case X86::ATOMXOR64: {
14722     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14723     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14724       .addReg(t4);
14725     break;
14726   }
14727   case X86::ATOMNAND8:
14728   case X86::ATOMNAND16:
14729   case X86::ATOMNAND32:
14730   case X86::ATOMNAND64: {
14731     unsigned Tmp = MRI.createVirtualRegister(RC);
14732     unsigned NOTOpc;
14733     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14734     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14735       .addReg(t4);
14736     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14737     break;
14738   }
14739   case X86::ATOMMAX8:
14740   case X86::ATOMMAX16:
14741   case X86::ATOMMAX32:
14742   case X86::ATOMMAX64:
14743   case X86::ATOMMIN8:
14744   case X86::ATOMMIN16:
14745   case X86::ATOMMIN32:
14746   case X86::ATOMMIN64:
14747   case X86::ATOMUMAX8:
14748   case X86::ATOMUMAX16:
14749   case X86::ATOMUMAX32:
14750   case X86::ATOMUMAX64:
14751   case X86::ATOMUMIN8:
14752   case X86::ATOMUMIN16:
14753   case X86::ATOMUMIN32:
14754   case X86::ATOMUMIN64: {
14755     unsigned CMPOpc;
14756     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14757
14758     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14759       .addReg(SrcReg)
14760       .addReg(t4);
14761
14762     if (Subtarget->hasCMov()) {
14763       if (VT != MVT::i8) {
14764         // Native support
14765         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14766           .addReg(SrcReg)
14767           .addReg(t4);
14768       } else {
14769         // Promote i8 to i32 to use CMOV32
14770         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14771         const TargetRegisterClass *RC32 =
14772           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14773         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14774         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14775         unsigned Tmp = MRI.createVirtualRegister(RC32);
14776
14777         unsigned Undef = MRI.createVirtualRegister(RC32);
14778         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14779
14780         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14781           .addReg(Undef)
14782           .addReg(SrcReg)
14783           .addImm(X86::sub_8bit);
14784         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14785           .addReg(Undef)
14786           .addReg(t4)
14787           .addImm(X86::sub_8bit);
14788
14789         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14790           .addReg(SrcReg32)
14791           .addReg(AccReg32);
14792
14793         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14794           .addReg(Tmp, 0, X86::sub_8bit);
14795       }
14796     } else {
14797       // Use pseudo select and lower them.
14798       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14799              "Invalid atomic-load-op transformation!");
14800       unsigned SelOpc = getPseudoCMOVOpc(VT);
14801       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14802       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14803       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14804               .addReg(SrcReg).addReg(t4)
14805               .addImm(CC);
14806       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14807       // Replace the original PHI node as mainMBB is changed after CMOV
14808       // lowering.
14809       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14810         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14811       Phi->eraseFromParent();
14812     }
14813     break;
14814   }
14815   }
14816
14817   // Copy PhyReg back from virtual register.
14818   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14819     .addReg(t4);
14820
14821   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14822   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14823     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14824     if (NewMO.isReg())
14825       NewMO.setIsKill(false);
14826     MIB.addOperand(NewMO);
14827   }
14828   MIB.addReg(t2);
14829   MIB.setMemRefs(MMOBegin, MMOEnd);
14830
14831   // Copy PhyReg back to virtual register.
14832   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14833     .addReg(PhyReg);
14834
14835   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14836
14837   mainMBB->addSuccessor(origMainMBB);
14838   mainMBB->addSuccessor(sinkMBB);
14839
14840   // sinkMBB:
14841   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14842           TII->get(TargetOpcode::COPY), DstReg)
14843     .addReg(t3);
14844
14845   MI->eraseFromParent();
14846   return sinkMBB;
14847 }
14848
14849 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14850 // instructions. They will be translated into a spin-loop or compare-exchange
14851 // loop from
14852 //
14853 //    ...
14854 //    dst = atomic-fetch-op MI.addr, MI.val
14855 //    ...
14856 //
14857 // to
14858 //
14859 //    ...
14860 //    t1L = LOAD [MI.addr + 0]
14861 //    t1H = LOAD [MI.addr + 4]
14862 // loop:
14863 //    t4L = phi(t1L, t3L / loop)
14864 //    t4H = phi(t1H, t3H / loop)
14865 //    t2L = OP MI.val.lo, t4L
14866 //    t2H = OP MI.val.hi, t4H
14867 //    EAX = t4L
14868 //    EDX = t4H
14869 //    EBX = t2L
14870 //    ECX = t2H
14871 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14872 //    t3L = EAX
14873 //    t3H = EDX
14874 //    JNE loop
14875 // sink:
14876 //    dstL = t3L
14877 //    dstH = t3H
14878 //    ...
14879 MachineBasicBlock *
14880 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14881                                            MachineBasicBlock *MBB) const {
14882   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14883   DebugLoc DL = MI->getDebugLoc();
14884
14885   MachineFunction *MF = MBB->getParent();
14886   MachineRegisterInfo &MRI = MF->getRegInfo();
14887
14888   const BasicBlock *BB = MBB->getBasicBlock();
14889   MachineFunction::iterator I = MBB;
14890   ++I;
14891
14892   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14893          "Unexpected number of operands");
14894
14895   assert(MI->hasOneMemOperand() &&
14896          "Expected atomic-load-op32 to have one memoperand");
14897
14898   // Memory Reference
14899   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14900   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14901
14902   unsigned DstLoReg, DstHiReg;
14903   unsigned SrcLoReg, SrcHiReg;
14904   unsigned MemOpndSlot;
14905
14906   unsigned CurOp = 0;
14907
14908   DstLoReg = MI->getOperand(CurOp++).getReg();
14909   DstHiReg = MI->getOperand(CurOp++).getReg();
14910   MemOpndSlot = CurOp;
14911   CurOp += X86::AddrNumOperands;
14912   SrcLoReg = MI->getOperand(CurOp++).getReg();
14913   SrcHiReg = MI->getOperand(CurOp++).getReg();
14914
14915   const TargetRegisterClass *RC = &X86::GR32RegClass;
14916   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14917
14918   unsigned t1L = MRI.createVirtualRegister(RC);
14919   unsigned t1H = MRI.createVirtualRegister(RC);
14920   unsigned t2L = MRI.createVirtualRegister(RC);
14921   unsigned t2H = MRI.createVirtualRegister(RC);
14922   unsigned t3L = MRI.createVirtualRegister(RC);
14923   unsigned t3H = MRI.createVirtualRegister(RC);
14924   unsigned t4L = MRI.createVirtualRegister(RC);
14925   unsigned t4H = MRI.createVirtualRegister(RC);
14926
14927   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14928   unsigned LOADOpc = X86::MOV32rm;
14929
14930   // For the atomic load-arith operator, we generate
14931   //
14932   //  thisMBB:
14933   //    t1L = LOAD [MI.addr + 0]
14934   //    t1H = LOAD [MI.addr + 4]
14935   //  mainMBB:
14936   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14937   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14938   //    t2L = OP MI.val.lo, t4L
14939   //    t2H = OP MI.val.hi, t4H
14940   //    EBX = t2L
14941   //    ECX = t2H
14942   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14943   //    t3L = EAX
14944   //    t3H = EDX
14945   //    JNE loop
14946   //  sinkMBB:
14947   //    dstL = t3L
14948   //    dstH = t3H
14949
14950   MachineBasicBlock *thisMBB = MBB;
14951   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14952   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14953   MF->insert(I, mainMBB);
14954   MF->insert(I, sinkMBB);
14955
14956   MachineInstrBuilder MIB;
14957
14958   // Transfer the remainder of BB and its successor edges to sinkMBB.
14959   sinkMBB->splice(sinkMBB->begin(), MBB,
14960                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14961   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14962
14963   // thisMBB:
14964   // Lo
14965   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14966   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14967     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14968     if (NewMO.isReg())
14969       NewMO.setIsKill(false);
14970     MIB.addOperand(NewMO);
14971   }
14972   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14973     unsigned flags = (*MMOI)->getFlags();
14974     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14975     MachineMemOperand *MMO =
14976       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14977                                (*MMOI)->getSize(),
14978                                (*MMOI)->getBaseAlignment(),
14979                                (*MMOI)->getTBAAInfo(),
14980                                (*MMOI)->getRanges());
14981     MIB.addMemOperand(MMO);
14982   };
14983   MachineInstr *LowMI = MIB;
14984
14985   // Hi
14986   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14987   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14988     if (i == X86::AddrDisp) {
14989       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14990     } else {
14991       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14992       if (NewMO.isReg())
14993         NewMO.setIsKill(false);
14994       MIB.addOperand(NewMO);
14995     }
14996   }
14997   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14998
14999   thisMBB->addSuccessor(mainMBB);
15000
15001   // mainMBB:
15002   MachineBasicBlock *origMainMBB = mainMBB;
15003
15004   // Add PHIs.
15005   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15006                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15007   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15008                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15009
15010   unsigned Opc = MI->getOpcode();
15011   switch (Opc) {
15012   default:
15013     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15014   case X86::ATOMAND6432:
15015   case X86::ATOMOR6432:
15016   case X86::ATOMXOR6432:
15017   case X86::ATOMADD6432:
15018   case X86::ATOMSUB6432: {
15019     unsigned HiOpc;
15020     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15021     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15022       .addReg(SrcLoReg);
15023     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15024       .addReg(SrcHiReg);
15025     break;
15026   }
15027   case X86::ATOMNAND6432: {
15028     unsigned HiOpc, NOTOpc;
15029     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15030     unsigned TmpL = MRI.createVirtualRegister(RC);
15031     unsigned TmpH = MRI.createVirtualRegister(RC);
15032     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15033       .addReg(t4L);
15034     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15035       .addReg(t4H);
15036     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15037     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15038     break;
15039   }
15040   case X86::ATOMMAX6432:
15041   case X86::ATOMMIN6432:
15042   case X86::ATOMUMAX6432:
15043   case X86::ATOMUMIN6432: {
15044     unsigned HiOpc;
15045     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15046     unsigned cL = MRI.createVirtualRegister(RC8);
15047     unsigned cH = MRI.createVirtualRegister(RC8);
15048     unsigned cL32 = MRI.createVirtualRegister(RC);
15049     unsigned cH32 = MRI.createVirtualRegister(RC);
15050     unsigned cc = MRI.createVirtualRegister(RC);
15051     // cl := cmp src_lo, lo
15052     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15053       .addReg(SrcLoReg).addReg(t4L);
15054     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15055     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15056     // ch := cmp src_hi, hi
15057     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15058       .addReg(SrcHiReg).addReg(t4H);
15059     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15060     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15061     // cc := if (src_hi == hi) ? cl : ch;
15062     if (Subtarget->hasCMov()) {
15063       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15064         .addReg(cH32).addReg(cL32);
15065     } else {
15066       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15067               .addReg(cH32).addReg(cL32)
15068               .addImm(X86::COND_E);
15069       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15070     }
15071     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15072     if (Subtarget->hasCMov()) {
15073       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15074         .addReg(SrcLoReg).addReg(t4L);
15075       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15076         .addReg(SrcHiReg).addReg(t4H);
15077     } else {
15078       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15079               .addReg(SrcLoReg).addReg(t4L)
15080               .addImm(X86::COND_NE);
15081       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15082       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15083       // 2nd CMOV lowering.
15084       mainMBB->addLiveIn(X86::EFLAGS);
15085       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15086               .addReg(SrcHiReg).addReg(t4H)
15087               .addImm(X86::COND_NE);
15088       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15089       // Replace the original PHI node as mainMBB is changed after CMOV
15090       // lowering.
15091       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15092         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15093       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15094         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15095       PhiL->eraseFromParent();
15096       PhiH->eraseFromParent();
15097     }
15098     break;
15099   }
15100   case X86::ATOMSWAP6432: {
15101     unsigned HiOpc;
15102     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15103     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15104     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15105     break;
15106   }
15107   }
15108
15109   // Copy EDX:EAX back from HiReg:LoReg
15110   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15111   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15112   // Copy ECX:EBX from t1H:t1L
15113   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15114   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15115
15116   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15117   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15118     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15119     if (NewMO.isReg())
15120       NewMO.setIsKill(false);
15121     MIB.addOperand(NewMO);
15122   }
15123   MIB.setMemRefs(MMOBegin, MMOEnd);
15124
15125   // Copy EDX:EAX back to t3H:t3L
15126   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15127   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15128
15129   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15130
15131   mainMBB->addSuccessor(origMainMBB);
15132   mainMBB->addSuccessor(sinkMBB);
15133
15134   // sinkMBB:
15135   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15136           TII->get(TargetOpcode::COPY), DstLoReg)
15137     .addReg(t3L);
15138   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15139           TII->get(TargetOpcode::COPY), DstHiReg)
15140     .addReg(t3H);
15141
15142   MI->eraseFromParent();
15143   return sinkMBB;
15144 }
15145
15146 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15147 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15148 // in the .td file.
15149 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15150                                        const TargetInstrInfo *TII) {
15151   unsigned Opc;
15152   switch (MI->getOpcode()) {
15153   default: llvm_unreachable("illegal opcode!");
15154   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15155   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15156   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15157   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15158   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15159   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15160   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15161   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15162   }
15163
15164   DebugLoc dl = MI->getDebugLoc();
15165   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15166
15167   unsigned NumArgs = MI->getNumOperands();
15168   for (unsigned i = 1; i < NumArgs; ++i) {
15169     MachineOperand &Op = MI->getOperand(i);
15170     if (!(Op.isReg() && Op.isImplicit()))
15171       MIB.addOperand(Op);
15172   }
15173   if (MI->hasOneMemOperand())
15174     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15175
15176   BuildMI(*BB, MI, dl,
15177     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15178     .addReg(X86::XMM0);
15179
15180   MI->eraseFromParent();
15181   return BB;
15182 }
15183
15184 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15185 // defs in an instruction pattern
15186 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15187                                        const TargetInstrInfo *TII) {
15188   unsigned Opc;
15189   switch (MI->getOpcode()) {
15190   default: llvm_unreachable("illegal opcode!");
15191   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15192   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15193   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15194   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15195   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15196   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15197   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15198   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15199   }
15200
15201   DebugLoc dl = MI->getDebugLoc();
15202   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15203
15204   unsigned NumArgs = MI->getNumOperands(); // remove the results
15205   for (unsigned i = 1; i < NumArgs; ++i) {
15206     MachineOperand &Op = MI->getOperand(i);
15207     if (!(Op.isReg() && Op.isImplicit()))
15208       MIB.addOperand(Op);
15209   }
15210   if (MI->hasOneMemOperand())
15211     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15212
15213   BuildMI(*BB, MI, dl,
15214     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15215     .addReg(X86::ECX);
15216
15217   MI->eraseFromParent();
15218   return BB;
15219 }
15220
15221 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15222                                        const TargetInstrInfo *TII,
15223                                        const X86Subtarget* Subtarget) {
15224   DebugLoc dl = MI->getDebugLoc();
15225
15226   // Address into RAX/EAX, other two args into ECX, EDX.
15227   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15228   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15229   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15230   for (int i = 0; i < X86::AddrNumOperands; ++i)
15231     MIB.addOperand(MI->getOperand(i));
15232
15233   unsigned ValOps = X86::AddrNumOperands;
15234   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15235     .addReg(MI->getOperand(ValOps).getReg());
15236   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15237     .addReg(MI->getOperand(ValOps+1).getReg());
15238
15239   // The instruction doesn't actually take any operands though.
15240   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15241
15242   MI->eraseFromParent(); // The pseudo is gone now.
15243   return BB;
15244 }
15245
15246 MachineBasicBlock *
15247 X86TargetLowering::EmitVAARG64WithCustomInserter(
15248                    MachineInstr *MI,
15249                    MachineBasicBlock *MBB) const {
15250   // Emit va_arg instruction on X86-64.
15251
15252   // Operands to this pseudo-instruction:
15253   // 0  ) Output        : destination address (reg)
15254   // 1-5) Input         : va_list address (addr, i64mem)
15255   // 6  ) ArgSize       : Size (in bytes) of vararg type
15256   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15257   // 8  ) Align         : Alignment of type
15258   // 9  ) EFLAGS (implicit-def)
15259
15260   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15261   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15262
15263   unsigned DestReg = MI->getOperand(0).getReg();
15264   MachineOperand &Base = MI->getOperand(1);
15265   MachineOperand &Scale = MI->getOperand(2);
15266   MachineOperand &Index = MI->getOperand(3);
15267   MachineOperand &Disp = MI->getOperand(4);
15268   MachineOperand &Segment = MI->getOperand(5);
15269   unsigned ArgSize = MI->getOperand(6).getImm();
15270   unsigned ArgMode = MI->getOperand(7).getImm();
15271   unsigned Align = MI->getOperand(8).getImm();
15272
15273   // Memory Reference
15274   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15275   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15276   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15277
15278   // Machine Information
15279   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15280   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15281   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15282   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15283   DebugLoc DL = MI->getDebugLoc();
15284
15285   // struct va_list {
15286   //   i32   gp_offset
15287   //   i32   fp_offset
15288   //   i64   overflow_area (address)
15289   //   i64   reg_save_area (address)
15290   // }
15291   // sizeof(va_list) = 24
15292   // alignment(va_list) = 8
15293
15294   unsigned TotalNumIntRegs = 6;
15295   unsigned TotalNumXMMRegs = 8;
15296   bool UseGPOffset = (ArgMode == 1);
15297   bool UseFPOffset = (ArgMode == 2);
15298   unsigned MaxOffset = TotalNumIntRegs * 8 +
15299                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15300
15301   /* Align ArgSize to a multiple of 8 */
15302   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15303   bool NeedsAlign = (Align > 8);
15304
15305   MachineBasicBlock *thisMBB = MBB;
15306   MachineBasicBlock *overflowMBB;
15307   MachineBasicBlock *offsetMBB;
15308   MachineBasicBlock *endMBB;
15309
15310   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15311   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15312   unsigned OffsetReg = 0;
15313
15314   if (!UseGPOffset && !UseFPOffset) {
15315     // If we only pull from the overflow region, we don't create a branch.
15316     // We don't need to alter control flow.
15317     OffsetDestReg = 0; // unused
15318     OverflowDestReg = DestReg;
15319
15320     offsetMBB = NULL;
15321     overflowMBB = thisMBB;
15322     endMBB = thisMBB;
15323   } else {
15324     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15325     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15326     // If not, pull from overflow_area. (branch to overflowMBB)
15327     //
15328     //       thisMBB
15329     //         |     .
15330     //         |        .
15331     //     offsetMBB   overflowMBB
15332     //         |        .
15333     //         |     .
15334     //        endMBB
15335
15336     // Registers for the PHI in endMBB
15337     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15338     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15339
15340     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15341     MachineFunction *MF = MBB->getParent();
15342     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15343     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15344     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15345
15346     MachineFunction::iterator MBBIter = MBB;
15347     ++MBBIter;
15348
15349     // Insert the new basic blocks
15350     MF->insert(MBBIter, offsetMBB);
15351     MF->insert(MBBIter, overflowMBB);
15352     MF->insert(MBBIter, endMBB);
15353
15354     // Transfer the remainder of MBB and its successor edges to endMBB.
15355     endMBB->splice(endMBB->begin(), thisMBB,
15356                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15357     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15358
15359     // Make offsetMBB and overflowMBB successors of thisMBB
15360     thisMBB->addSuccessor(offsetMBB);
15361     thisMBB->addSuccessor(overflowMBB);
15362
15363     // endMBB is a successor of both offsetMBB and overflowMBB
15364     offsetMBB->addSuccessor(endMBB);
15365     overflowMBB->addSuccessor(endMBB);
15366
15367     // Load the offset value into a register
15368     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15369     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15370       .addOperand(Base)
15371       .addOperand(Scale)
15372       .addOperand(Index)
15373       .addDisp(Disp, UseFPOffset ? 4 : 0)
15374       .addOperand(Segment)
15375       .setMemRefs(MMOBegin, MMOEnd);
15376
15377     // Check if there is enough room left to pull this argument.
15378     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15379       .addReg(OffsetReg)
15380       .addImm(MaxOffset + 8 - ArgSizeA8);
15381
15382     // Branch to "overflowMBB" if offset >= max
15383     // Fall through to "offsetMBB" otherwise
15384     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15385       .addMBB(overflowMBB);
15386   }
15387
15388   // In offsetMBB, emit code to use the reg_save_area.
15389   if (offsetMBB) {
15390     assert(OffsetReg != 0);
15391
15392     // Read the reg_save_area address.
15393     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15394     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15395       .addOperand(Base)
15396       .addOperand(Scale)
15397       .addOperand(Index)
15398       .addDisp(Disp, 16)
15399       .addOperand(Segment)
15400       .setMemRefs(MMOBegin, MMOEnd);
15401
15402     // Zero-extend the offset
15403     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15404       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15405         .addImm(0)
15406         .addReg(OffsetReg)
15407         .addImm(X86::sub_32bit);
15408
15409     // Add the offset to the reg_save_area to get the final address.
15410     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15411       .addReg(OffsetReg64)
15412       .addReg(RegSaveReg);
15413
15414     // Compute the offset for the next argument
15415     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15416     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15417       .addReg(OffsetReg)
15418       .addImm(UseFPOffset ? 16 : 8);
15419
15420     // Store it back into the va_list.
15421     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15422       .addOperand(Base)
15423       .addOperand(Scale)
15424       .addOperand(Index)
15425       .addDisp(Disp, UseFPOffset ? 4 : 0)
15426       .addOperand(Segment)
15427       .addReg(NextOffsetReg)
15428       .setMemRefs(MMOBegin, MMOEnd);
15429
15430     // Jump to endMBB
15431     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15432       .addMBB(endMBB);
15433   }
15434
15435   //
15436   // Emit code to use overflow area
15437   //
15438
15439   // Load the overflow_area address into a register.
15440   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15441   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15442     .addOperand(Base)
15443     .addOperand(Scale)
15444     .addOperand(Index)
15445     .addDisp(Disp, 8)
15446     .addOperand(Segment)
15447     .setMemRefs(MMOBegin, MMOEnd);
15448
15449   // If we need to align it, do so. Otherwise, just copy the address
15450   // to OverflowDestReg.
15451   if (NeedsAlign) {
15452     // Align the overflow address
15453     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15454     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15455
15456     // aligned_addr = (addr + (align-1)) & ~(align-1)
15457     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15458       .addReg(OverflowAddrReg)
15459       .addImm(Align-1);
15460
15461     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15462       .addReg(TmpReg)
15463       .addImm(~(uint64_t)(Align-1));
15464   } else {
15465     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15466       .addReg(OverflowAddrReg);
15467   }
15468
15469   // Compute the next overflow address after this argument.
15470   // (the overflow address should be kept 8-byte aligned)
15471   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15472   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15473     .addReg(OverflowDestReg)
15474     .addImm(ArgSizeA8);
15475
15476   // Store the new overflow address.
15477   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15478     .addOperand(Base)
15479     .addOperand(Scale)
15480     .addOperand(Index)
15481     .addDisp(Disp, 8)
15482     .addOperand(Segment)
15483     .addReg(NextAddrReg)
15484     .setMemRefs(MMOBegin, MMOEnd);
15485
15486   // If we branched, emit the PHI to the front of endMBB.
15487   if (offsetMBB) {
15488     BuildMI(*endMBB, endMBB->begin(), DL,
15489             TII->get(X86::PHI), DestReg)
15490       .addReg(OffsetDestReg).addMBB(offsetMBB)
15491       .addReg(OverflowDestReg).addMBB(overflowMBB);
15492   }
15493
15494   // Erase the pseudo instruction
15495   MI->eraseFromParent();
15496
15497   return endMBB;
15498 }
15499
15500 MachineBasicBlock *
15501 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15502                                                  MachineInstr *MI,
15503                                                  MachineBasicBlock *MBB) const {
15504   // Emit code to save XMM registers to the stack. The ABI says that the
15505   // number of registers to save is given in %al, so it's theoretically
15506   // possible to do an indirect jump trick to avoid saving all of them,
15507   // however this code takes a simpler approach and just executes all
15508   // of the stores if %al is non-zero. It's less code, and it's probably
15509   // easier on the hardware branch predictor, and stores aren't all that
15510   // expensive anyway.
15511
15512   // Create the new basic blocks. One block contains all the XMM stores,
15513   // and one block is the final destination regardless of whether any
15514   // stores were performed.
15515   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15516   MachineFunction *F = MBB->getParent();
15517   MachineFunction::iterator MBBIter = MBB;
15518   ++MBBIter;
15519   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15520   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15521   F->insert(MBBIter, XMMSaveMBB);
15522   F->insert(MBBIter, EndMBB);
15523
15524   // Transfer the remainder of MBB and its successor edges to EndMBB.
15525   EndMBB->splice(EndMBB->begin(), MBB,
15526                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15527   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15528
15529   // The original block will now fall through to the XMM save block.
15530   MBB->addSuccessor(XMMSaveMBB);
15531   // The XMMSaveMBB will fall through to the end block.
15532   XMMSaveMBB->addSuccessor(EndMBB);
15533
15534   // Now add the instructions.
15535   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15536   DebugLoc DL = MI->getDebugLoc();
15537
15538   unsigned CountReg = MI->getOperand(0).getReg();
15539   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15540   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15541
15542   if (!Subtarget->isTargetWin64()) {
15543     // If %al is 0, branch around the XMM save block.
15544     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15545     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15546     MBB->addSuccessor(EndMBB);
15547   }
15548
15549   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15550   // that was just emitted, but clearly shouldn't be "saved".
15551   assert((MI->getNumOperands() <= 3 ||
15552           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15553           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15554          && "Expected last argument to be EFLAGS");
15555   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15556   // In the XMM save block, save all the XMM argument registers.
15557   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15558     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15559     MachineMemOperand *MMO =
15560       F->getMachineMemOperand(
15561           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15562         MachineMemOperand::MOStore,
15563         /*Size=*/16, /*Align=*/16);
15564     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15565       .addFrameIndex(RegSaveFrameIndex)
15566       .addImm(/*Scale=*/1)
15567       .addReg(/*IndexReg=*/0)
15568       .addImm(/*Disp=*/Offset)
15569       .addReg(/*Segment=*/0)
15570       .addReg(MI->getOperand(i).getReg())
15571       .addMemOperand(MMO);
15572   }
15573
15574   MI->eraseFromParent();   // The pseudo instruction is gone now.
15575
15576   return EndMBB;
15577 }
15578
15579 // The EFLAGS operand of SelectItr might be missing a kill marker
15580 // because there were multiple uses of EFLAGS, and ISel didn't know
15581 // which to mark. Figure out whether SelectItr should have had a
15582 // kill marker, and set it if it should. Returns the correct kill
15583 // marker value.
15584 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15585                                      MachineBasicBlock* BB,
15586                                      const TargetRegisterInfo* TRI) {
15587   // Scan forward through BB for a use/def of EFLAGS.
15588   MachineBasicBlock::iterator miI(std::next(SelectItr));
15589   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15590     const MachineInstr& mi = *miI;
15591     if (mi.readsRegister(X86::EFLAGS))
15592       return false;
15593     if (mi.definesRegister(X86::EFLAGS))
15594       break; // Should have kill-flag - update below.
15595   }
15596
15597   // If we hit the end of the block, check whether EFLAGS is live into a
15598   // successor.
15599   if (miI == BB->end()) {
15600     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15601                                           sEnd = BB->succ_end();
15602          sItr != sEnd; ++sItr) {
15603       MachineBasicBlock* succ = *sItr;
15604       if (succ->isLiveIn(X86::EFLAGS))
15605         return false;
15606     }
15607   }
15608
15609   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15610   // out. SelectMI should have a kill flag on EFLAGS.
15611   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15612   return true;
15613 }
15614
15615 MachineBasicBlock *
15616 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15617                                      MachineBasicBlock *BB) const {
15618   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15619   DebugLoc DL = MI->getDebugLoc();
15620
15621   // To "insert" a SELECT_CC instruction, we actually have to insert the
15622   // diamond control-flow pattern.  The incoming instruction knows the
15623   // destination vreg to set, the condition code register to branch on, the
15624   // true/false values to select between, and a branch opcode to use.
15625   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15626   MachineFunction::iterator It = BB;
15627   ++It;
15628
15629   //  thisMBB:
15630   //  ...
15631   //   TrueVal = ...
15632   //   cmpTY ccX, r1, r2
15633   //   bCC copy1MBB
15634   //   fallthrough --> copy0MBB
15635   MachineBasicBlock *thisMBB = BB;
15636   MachineFunction *F = BB->getParent();
15637   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15638   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15639   F->insert(It, copy0MBB);
15640   F->insert(It, sinkMBB);
15641
15642   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15643   // live into the sink and copy blocks.
15644   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15645   if (!MI->killsRegister(X86::EFLAGS) &&
15646       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15647     copy0MBB->addLiveIn(X86::EFLAGS);
15648     sinkMBB->addLiveIn(X86::EFLAGS);
15649   }
15650
15651   // Transfer the remainder of BB and its successor edges to sinkMBB.
15652   sinkMBB->splice(sinkMBB->begin(), BB,
15653                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
15654   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15655
15656   // Add the true and fallthrough blocks as its successors.
15657   BB->addSuccessor(copy0MBB);
15658   BB->addSuccessor(sinkMBB);
15659
15660   // Create the conditional branch instruction.
15661   unsigned Opc =
15662     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15663   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15664
15665   //  copy0MBB:
15666   //   %FalseValue = ...
15667   //   # fallthrough to sinkMBB
15668   copy0MBB->addSuccessor(sinkMBB);
15669
15670   //  sinkMBB:
15671   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15672   //  ...
15673   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15674           TII->get(X86::PHI), MI->getOperand(0).getReg())
15675     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15676     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15677
15678   MI->eraseFromParent();   // The pseudo instruction is gone now.
15679   return sinkMBB;
15680 }
15681
15682 MachineBasicBlock *
15683 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15684                                         bool Is64Bit) const {
15685   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15686   DebugLoc DL = MI->getDebugLoc();
15687   MachineFunction *MF = BB->getParent();
15688   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15689
15690   assert(getTargetMachine().Options.EnableSegmentedStacks);
15691
15692   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15693   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15694
15695   // BB:
15696   //  ... [Till the alloca]
15697   // If stacklet is not large enough, jump to mallocMBB
15698   //
15699   // bumpMBB:
15700   //  Allocate by subtracting from RSP
15701   //  Jump to continueMBB
15702   //
15703   // mallocMBB:
15704   //  Allocate by call to runtime
15705   //
15706   // continueMBB:
15707   //  ...
15708   //  [rest of original BB]
15709   //
15710
15711   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15712   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15713   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15714
15715   MachineRegisterInfo &MRI = MF->getRegInfo();
15716   const TargetRegisterClass *AddrRegClass =
15717     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15718
15719   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15720     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15721     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15722     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15723     sizeVReg = MI->getOperand(1).getReg(),
15724     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15725
15726   MachineFunction::iterator MBBIter = BB;
15727   ++MBBIter;
15728
15729   MF->insert(MBBIter, bumpMBB);
15730   MF->insert(MBBIter, mallocMBB);
15731   MF->insert(MBBIter, continueMBB);
15732
15733   continueMBB->splice(continueMBB->begin(), BB,
15734                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
15735   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15736
15737   // Add code to the main basic block to check if the stack limit has been hit,
15738   // and if so, jump to mallocMBB otherwise to bumpMBB.
15739   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15740   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15741     .addReg(tmpSPVReg).addReg(sizeVReg);
15742   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15743     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15744     .addReg(SPLimitVReg);
15745   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15746
15747   // bumpMBB simply decreases the stack pointer, since we know the current
15748   // stacklet has enough space.
15749   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15750     .addReg(SPLimitVReg);
15751   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15752     .addReg(SPLimitVReg);
15753   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15754
15755   // Calls into a routine in libgcc to allocate more space from the heap.
15756   const uint32_t *RegMask =
15757     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15758   if (Is64Bit) {
15759     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15760       .addReg(sizeVReg);
15761     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15762       .addExternalSymbol("__morestack_allocate_stack_space")
15763       .addRegMask(RegMask)
15764       .addReg(X86::RDI, RegState::Implicit)
15765       .addReg(X86::RAX, RegState::ImplicitDefine);
15766   } else {
15767     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15768       .addImm(12);
15769     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15770     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15771       .addExternalSymbol("__morestack_allocate_stack_space")
15772       .addRegMask(RegMask)
15773       .addReg(X86::EAX, RegState::ImplicitDefine);
15774   }
15775
15776   if (!Is64Bit)
15777     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15778       .addImm(16);
15779
15780   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15781     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15782   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15783
15784   // Set up the CFG correctly.
15785   BB->addSuccessor(bumpMBB);
15786   BB->addSuccessor(mallocMBB);
15787   mallocMBB->addSuccessor(continueMBB);
15788   bumpMBB->addSuccessor(continueMBB);
15789
15790   // Take care of the PHI nodes.
15791   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15792           MI->getOperand(0).getReg())
15793     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15794     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15795
15796   // Delete the original pseudo instruction.
15797   MI->eraseFromParent();
15798
15799   // And we're done.
15800   return continueMBB;
15801 }
15802
15803 MachineBasicBlock *
15804 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15805                                           MachineBasicBlock *BB) const {
15806   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15807   DebugLoc DL = MI->getDebugLoc();
15808
15809   assert(!Subtarget->isTargetMacho());
15810
15811   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15812   // non-trivial part is impdef of ESP.
15813
15814   if (Subtarget->isTargetWin64()) {
15815     if (Subtarget->isTargetCygMing()) {
15816       // ___chkstk(Mingw64):
15817       // Clobbers R10, R11, RAX and EFLAGS.
15818       // Updates RSP.
15819       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15820         .addExternalSymbol("___chkstk")
15821         .addReg(X86::RAX, RegState::Implicit)
15822         .addReg(X86::RSP, RegState::Implicit)
15823         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15824         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15825         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15826     } else {
15827       // __chkstk(MSVCRT): does not update stack pointer.
15828       // Clobbers R10, R11 and EFLAGS.
15829       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15830         .addExternalSymbol("__chkstk")
15831         .addReg(X86::RAX, RegState::Implicit)
15832         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15833       // RAX has the offset to be subtracted from RSP.
15834       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15835         .addReg(X86::RSP)
15836         .addReg(X86::RAX);
15837     }
15838   } else {
15839     const char *StackProbeSymbol =
15840       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15841
15842     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15843       .addExternalSymbol(StackProbeSymbol)
15844       .addReg(X86::EAX, RegState::Implicit)
15845       .addReg(X86::ESP, RegState::Implicit)
15846       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15847       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15848       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15849   }
15850
15851   MI->eraseFromParent();   // The pseudo instruction is gone now.
15852   return BB;
15853 }
15854
15855 MachineBasicBlock *
15856 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15857                                       MachineBasicBlock *BB) const {
15858   // This is pretty easy.  We're taking the value that we received from
15859   // our load from the relocation, sticking it in either RDI (x86-64)
15860   // or EAX and doing an indirect call.  The return value will then
15861   // be in the normal return register.
15862   const X86InstrInfo *TII
15863     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15864   DebugLoc DL = MI->getDebugLoc();
15865   MachineFunction *F = BB->getParent();
15866
15867   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15868   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15869
15870   // Get a register mask for the lowered call.
15871   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15872   // proper register mask.
15873   const uint32_t *RegMask =
15874     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15875   if (Subtarget->is64Bit()) {
15876     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15877                                       TII->get(X86::MOV64rm), X86::RDI)
15878     .addReg(X86::RIP)
15879     .addImm(0).addReg(0)
15880     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15881                       MI->getOperand(3).getTargetFlags())
15882     .addReg(0);
15883     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15884     addDirectMem(MIB, X86::RDI);
15885     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15886   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15887     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15888                                       TII->get(X86::MOV32rm), X86::EAX)
15889     .addReg(0)
15890     .addImm(0).addReg(0)
15891     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15892                       MI->getOperand(3).getTargetFlags())
15893     .addReg(0);
15894     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15895     addDirectMem(MIB, X86::EAX);
15896     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15897   } else {
15898     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15899                                       TII->get(X86::MOV32rm), X86::EAX)
15900     .addReg(TII->getGlobalBaseReg(F))
15901     .addImm(0).addReg(0)
15902     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15903                       MI->getOperand(3).getTargetFlags())
15904     .addReg(0);
15905     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15906     addDirectMem(MIB, X86::EAX);
15907     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15908   }
15909
15910   MI->eraseFromParent(); // The pseudo instruction is gone now.
15911   return BB;
15912 }
15913
15914 MachineBasicBlock *
15915 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15916                                     MachineBasicBlock *MBB) const {
15917   DebugLoc DL = MI->getDebugLoc();
15918   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15919
15920   MachineFunction *MF = MBB->getParent();
15921   MachineRegisterInfo &MRI = MF->getRegInfo();
15922
15923   const BasicBlock *BB = MBB->getBasicBlock();
15924   MachineFunction::iterator I = MBB;
15925   ++I;
15926
15927   // Memory Reference
15928   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15929   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15930
15931   unsigned DstReg;
15932   unsigned MemOpndSlot = 0;
15933
15934   unsigned CurOp = 0;
15935
15936   DstReg = MI->getOperand(CurOp++).getReg();
15937   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15938   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15939   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15940   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15941
15942   MemOpndSlot = CurOp;
15943
15944   MVT PVT = getPointerTy();
15945   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15946          "Invalid Pointer Size!");
15947
15948   // For v = setjmp(buf), we generate
15949   //
15950   // thisMBB:
15951   //  buf[LabelOffset] = restoreMBB
15952   //  SjLjSetup restoreMBB
15953   //
15954   // mainMBB:
15955   //  v_main = 0
15956   //
15957   // sinkMBB:
15958   //  v = phi(main, restore)
15959   //
15960   // restoreMBB:
15961   //  v_restore = 1
15962
15963   MachineBasicBlock *thisMBB = MBB;
15964   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15965   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15966   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15967   MF->insert(I, mainMBB);
15968   MF->insert(I, sinkMBB);
15969   MF->push_back(restoreMBB);
15970
15971   MachineInstrBuilder MIB;
15972
15973   // Transfer the remainder of BB and its successor edges to sinkMBB.
15974   sinkMBB->splice(sinkMBB->begin(), MBB,
15975                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15976   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15977
15978   // thisMBB:
15979   unsigned PtrStoreOpc = 0;
15980   unsigned LabelReg = 0;
15981   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15982   Reloc::Model RM = getTargetMachine().getRelocationModel();
15983   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15984                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15985
15986   // Prepare IP either in reg or imm.
15987   if (!UseImmLabel) {
15988     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15989     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15990     LabelReg = MRI.createVirtualRegister(PtrRC);
15991     if (Subtarget->is64Bit()) {
15992       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15993               .addReg(X86::RIP)
15994               .addImm(0)
15995               .addReg(0)
15996               .addMBB(restoreMBB)
15997               .addReg(0);
15998     } else {
15999       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16000       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16001               .addReg(XII->getGlobalBaseReg(MF))
16002               .addImm(0)
16003               .addReg(0)
16004               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16005               .addReg(0);
16006     }
16007   } else
16008     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16009   // Store IP
16010   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16011   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16012     if (i == X86::AddrDisp)
16013       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16014     else
16015       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16016   }
16017   if (!UseImmLabel)
16018     MIB.addReg(LabelReg);
16019   else
16020     MIB.addMBB(restoreMBB);
16021   MIB.setMemRefs(MMOBegin, MMOEnd);
16022   // Setup
16023   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16024           .addMBB(restoreMBB);
16025
16026   const X86RegisterInfo *RegInfo =
16027     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16028   MIB.addRegMask(RegInfo->getNoPreservedMask());
16029   thisMBB->addSuccessor(mainMBB);
16030   thisMBB->addSuccessor(restoreMBB);
16031
16032   // mainMBB:
16033   //  EAX = 0
16034   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16035   mainMBB->addSuccessor(sinkMBB);
16036
16037   // sinkMBB:
16038   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16039           TII->get(X86::PHI), DstReg)
16040     .addReg(mainDstReg).addMBB(mainMBB)
16041     .addReg(restoreDstReg).addMBB(restoreMBB);
16042
16043   // restoreMBB:
16044   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16045   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16046   restoreMBB->addSuccessor(sinkMBB);
16047
16048   MI->eraseFromParent();
16049   return sinkMBB;
16050 }
16051
16052 MachineBasicBlock *
16053 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16054                                      MachineBasicBlock *MBB) const {
16055   DebugLoc DL = MI->getDebugLoc();
16056   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16057
16058   MachineFunction *MF = MBB->getParent();
16059   MachineRegisterInfo &MRI = MF->getRegInfo();
16060
16061   // Memory Reference
16062   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16063   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16064
16065   MVT PVT = getPointerTy();
16066   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16067          "Invalid Pointer Size!");
16068
16069   const TargetRegisterClass *RC =
16070     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16071   unsigned Tmp = MRI.createVirtualRegister(RC);
16072   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16073   const X86RegisterInfo *RegInfo =
16074     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16075   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16076   unsigned SP = RegInfo->getStackRegister();
16077
16078   MachineInstrBuilder MIB;
16079
16080   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16081   const int64_t SPOffset = 2 * PVT.getStoreSize();
16082
16083   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16084   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16085
16086   // Reload FP
16087   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16088   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16089     MIB.addOperand(MI->getOperand(i));
16090   MIB.setMemRefs(MMOBegin, MMOEnd);
16091   // Reload IP
16092   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16093   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16094     if (i == X86::AddrDisp)
16095       MIB.addDisp(MI->getOperand(i), LabelOffset);
16096     else
16097       MIB.addOperand(MI->getOperand(i));
16098   }
16099   MIB.setMemRefs(MMOBegin, MMOEnd);
16100   // Reload SP
16101   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16102   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16103     if (i == X86::AddrDisp)
16104       MIB.addDisp(MI->getOperand(i), SPOffset);
16105     else
16106       MIB.addOperand(MI->getOperand(i));
16107   }
16108   MIB.setMemRefs(MMOBegin, MMOEnd);
16109   // Jump
16110   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16111
16112   MI->eraseFromParent();
16113   return MBB;
16114 }
16115
16116 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16117 // accumulator loops. Writing back to the accumulator allows the coalescer
16118 // to remove extra copies in the loop.   
16119 MachineBasicBlock *
16120 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16121                                  MachineBasicBlock *MBB) const {
16122   MachineOperand &AddendOp = MI->getOperand(3);
16123
16124   // Bail out early if the addend isn't a register - we can't switch these.
16125   if (!AddendOp.isReg())
16126     return MBB;
16127
16128   MachineFunction &MF = *MBB->getParent();
16129   MachineRegisterInfo &MRI = MF.getRegInfo();
16130
16131   // Check whether the addend is defined by a PHI:
16132   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16133   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16134   if (!AddendDef.isPHI())
16135     return MBB;
16136
16137   // Look for the following pattern:
16138   // loop:
16139   //   %addend = phi [%entry, 0], [%loop, %result]
16140   //   ...
16141   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16142
16143   // Replace with:
16144   //   loop:
16145   //   %addend = phi [%entry, 0], [%loop, %result]
16146   //   ...
16147   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16148
16149   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16150     assert(AddendDef.getOperand(i).isReg());
16151     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16152     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16153     if (&PHISrcInst == MI) {
16154       // Found a matching instruction.
16155       unsigned NewFMAOpc = 0;
16156       switch (MI->getOpcode()) {
16157         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16158         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16159         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16160         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16161         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16162         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16163         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16164         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16165         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16166         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16167         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16168         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16169         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16170         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16171         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16172         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16173         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16174         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16175         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16176         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16177         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16178         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16179         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16180         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16181         default: llvm_unreachable("Unrecognized FMA variant.");
16182       }
16183
16184       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16185       MachineInstrBuilder MIB =
16186         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16187         .addOperand(MI->getOperand(0))
16188         .addOperand(MI->getOperand(3))
16189         .addOperand(MI->getOperand(2))
16190         .addOperand(MI->getOperand(1));
16191       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16192       MI->eraseFromParent();
16193     }
16194   }
16195
16196   return MBB;
16197 }
16198
16199 MachineBasicBlock *
16200 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16201                                                MachineBasicBlock *BB) const {
16202   switch (MI->getOpcode()) {
16203   default: llvm_unreachable("Unexpected instr type to insert");
16204   case X86::TAILJMPd64:
16205   case X86::TAILJMPr64:
16206   case X86::TAILJMPm64:
16207     llvm_unreachable("TAILJMP64 would not be touched here.");
16208   case X86::TCRETURNdi64:
16209   case X86::TCRETURNri64:
16210   case X86::TCRETURNmi64:
16211     return BB;
16212   case X86::WIN_ALLOCA:
16213     return EmitLoweredWinAlloca(MI, BB);
16214   case X86::SEG_ALLOCA_32:
16215     return EmitLoweredSegAlloca(MI, BB, false);
16216   case X86::SEG_ALLOCA_64:
16217     return EmitLoweredSegAlloca(MI, BB, true);
16218   case X86::TLSCall_32:
16219   case X86::TLSCall_64:
16220     return EmitLoweredTLSCall(MI, BB);
16221   case X86::CMOV_GR8:
16222   case X86::CMOV_FR32:
16223   case X86::CMOV_FR64:
16224   case X86::CMOV_V4F32:
16225   case X86::CMOV_V2F64:
16226   case X86::CMOV_V2I64:
16227   case X86::CMOV_V8F32:
16228   case X86::CMOV_V4F64:
16229   case X86::CMOV_V4I64:
16230   case X86::CMOV_V16F32:
16231   case X86::CMOV_V8F64:
16232   case X86::CMOV_V8I64:
16233   case X86::CMOV_GR16:
16234   case X86::CMOV_GR32:
16235   case X86::CMOV_RFP32:
16236   case X86::CMOV_RFP64:
16237   case X86::CMOV_RFP80:
16238     return EmitLoweredSelect(MI, BB);
16239
16240   case X86::FP32_TO_INT16_IN_MEM:
16241   case X86::FP32_TO_INT32_IN_MEM:
16242   case X86::FP32_TO_INT64_IN_MEM:
16243   case X86::FP64_TO_INT16_IN_MEM:
16244   case X86::FP64_TO_INT32_IN_MEM:
16245   case X86::FP64_TO_INT64_IN_MEM:
16246   case X86::FP80_TO_INT16_IN_MEM:
16247   case X86::FP80_TO_INT32_IN_MEM:
16248   case X86::FP80_TO_INT64_IN_MEM: {
16249     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16250     DebugLoc DL = MI->getDebugLoc();
16251
16252     // Change the floating point control register to use "round towards zero"
16253     // mode when truncating to an integer value.
16254     MachineFunction *F = BB->getParent();
16255     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16256     addFrameReference(BuildMI(*BB, MI, DL,
16257                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16258
16259     // Load the old value of the high byte of the control word...
16260     unsigned OldCW =
16261       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16262     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16263                       CWFrameIdx);
16264
16265     // Set the high part to be round to zero...
16266     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16267       .addImm(0xC7F);
16268
16269     // Reload the modified control word now...
16270     addFrameReference(BuildMI(*BB, MI, DL,
16271                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16272
16273     // Restore the memory image of control word to original value
16274     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16275       .addReg(OldCW);
16276
16277     // Get the X86 opcode to use.
16278     unsigned Opc;
16279     switch (MI->getOpcode()) {
16280     default: llvm_unreachable("illegal opcode!");
16281     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16282     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16283     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16284     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16285     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16286     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16287     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16288     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16289     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16290     }
16291
16292     X86AddressMode AM;
16293     MachineOperand &Op = MI->getOperand(0);
16294     if (Op.isReg()) {
16295       AM.BaseType = X86AddressMode::RegBase;
16296       AM.Base.Reg = Op.getReg();
16297     } else {
16298       AM.BaseType = X86AddressMode::FrameIndexBase;
16299       AM.Base.FrameIndex = Op.getIndex();
16300     }
16301     Op = MI->getOperand(1);
16302     if (Op.isImm())
16303       AM.Scale = Op.getImm();
16304     Op = MI->getOperand(2);
16305     if (Op.isImm())
16306       AM.IndexReg = Op.getImm();
16307     Op = MI->getOperand(3);
16308     if (Op.isGlobal()) {
16309       AM.GV = Op.getGlobal();
16310     } else {
16311       AM.Disp = Op.getImm();
16312     }
16313     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16314                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16315
16316     // Reload the original control word now.
16317     addFrameReference(BuildMI(*BB, MI, DL,
16318                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16319
16320     MI->eraseFromParent();   // The pseudo instruction is gone now.
16321     return BB;
16322   }
16323     // String/text processing lowering.
16324   case X86::PCMPISTRM128REG:
16325   case X86::VPCMPISTRM128REG:
16326   case X86::PCMPISTRM128MEM:
16327   case X86::VPCMPISTRM128MEM:
16328   case X86::PCMPESTRM128REG:
16329   case X86::VPCMPESTRM128REG:
16330   case X86::PCMPESTRM128MEM:
16331   case X86::VPCMPESTRM128MEM:
16332     assert(Subtarget->hasSSE42() &&
16333            "Target must have SSE4.2 or AVX features enabled");
16334     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16335
16336   // String/text processing lowering.
16337   case X86::PCMPISTRIREG:
16338   case X86::VPCMPISTRIREG:
16339   case X86::PCMPISTRIMEM:
16340   case X86::VPCMPISTRIMEM:
16341   case X86::PCMPESTRIREG:
16342   case X86::VPCMPESTRIREG:
16343   case X86::PCMPESTRIMEM:
16344   case X86::VPCMPESTRIMEM:
16345     assert(Subtarget->hasSSE42() &&
16346            "Target must have SSE4.2 or AVX features enabled");
16347     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16348
16349   // Thread synchronization.
16350   case X86::MONITOR:
16351     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16352
16353   // xbegin
16354   case X86::XBEGIN:
16355     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16356
16357   // Atomic Lowering.
16358   case X86::ATOMAND8:
16359   case X86::ATOMAND16:
16360   case X86::ATOMAND32:
16361   case X86::ATOMAND64:
16362     // Fall through
16363   case X86::ATOMOR8:
16364   case X86::ATOMOR16:
16365   case X86::ATOMOR32:
16366   case X86::ATOMOR64:
16367     // Fall through
16368   case X86::ATOMXOR16:
16369   case X86::ATOMXOR8:
16370   case X86::ATOMXOR32:
16371   case X86::ATOMXOR64:
16372     // Fall through
16373   case X86::ATOMNAND8:
16374   case X86::ATOMNAND16:
16375   case X86::ATOMNAND32:
16376   case X86::ATOMNAND64:
16377     // Fall through
16378   case X86::ATOMMAX8:
16379   case X86::ATOMMAX16:
16380   case X86::ATOMMAX32:
16381   case X86::ATOMMAX64:
16382     // Fall through
16383   case X86::ATOMMIN8:
16384   case X86::ATOMMIN16:
16385   case X86::ATOMMIN32:
16386   case X86::ATOMMIN64:
16387     // Fall through
16388   case X86::ATOMUMAX8:
16389   case X86::ATOMUMAX16:
16390   case X86::ATOMUMAX32:
16391   case X86::ATOMUMAX64:
16392     // Fall through
16393   case X86::ATOMUMIN8:
16394   case X86::ATOMUMIN16:
16395   case X86::ATOMUMIN32:
16396   case X86::ATOMUMIN64:
16397     return EmitAtomicLoadArith(MI, BB);
16398
16399   // This group does 64-bit operations on a 32-bit host.
16400   case X86::ATOMAND6432:
16401   case X86::ATOMOR6432:
16402   case X86::ATOMXOR6432:
16403   case X86::ATOMNAND6432:
16404   case X86::ATOMADD6432:
16405   case X86::ATOMSUB6432:
16406   case X86::ATOMMAX6432:
16407   case X86::ATOMMIN6432:
16408   case X86::ATOMUMAX6432:
16409   case X86::ATOMUMIN6432:
16410   case X86::ATOMSWAP6432:
16411     return EmitAtomicLoadArith6432(MI, BB);
16412
16413   case X86::VASTART_SAVE_XMM_REGS:
16414     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16415
16416   case X86::VAARG_64:
16417     return EmitVAARG64WithCustomInserter(MI, BB);
16418
16419   case X86::EH_SjLj_SetJmp32:
16420   case X86::EH_SjLj_SetJmp64:
16421     return emitEHSjLjSetJmp(MI, BB);
16422
16423   case X86::EH_SjLj_LongJmp32:
16424   case X86::EH_SjLj_LongJmp64:
16425     return emitEHSjLjLongJmp(MI, BB);
16426
16427   case TargetOpcode::STACKMAP:
16428   case TargetOpcode::PATCHPOINT:
16429     return emitPatchPoint(MI, BB);
16430
16431   case X86::VFMADDPDr213r:
16432   case X86::VFMADDPSr213r:
16433   case X86::VFMADDSDr213r:
16434   case X86::VFMADDSSr213r:
16435   case X86::VFMSUBPDr213r:
16436   case X86::VFMSUBPSr213r:
16437   case X86::VFMSUBSDr213r:
16438   case X86::VFMSUBSSr213r:
16439   case X86::VFNMADDPDr213r:
16440   case X86::VFNMADDPSr213r:
16441   case X86::VFNMADDSDr213r:
16442   case X86::VFNMADDSSr213r:
16443   case X86::VFNMSUBPDr213r:
16444   case X86::VFNMSUBPSr213r:
16445   case X86::VFNMSUBSDr213r:
16446   case X86::VFNMSUBSSr213r:
16447   case X86::VFMADDPDr213rY:
16448   case X86::VFMADDPSr213rY:
16449   case X86::VFMSUBPDr213rY:
16450   case X86::VFMSUBPSr213rY:
16451   case X86::VFNMADDPDr213rY:
16452   case X86::VFNMADDPSr213rY:
16453   case X86::VFNMSUBPDr213rY:
16454   case X86::VFNMSUBPSr213rY:
16455     return emitFMA3Instr(MI, BB);
16456   }
16457 }
16458
16459 //===----------------------------------------------------------------------===//
16460 //                           X86 Optimization Hooks
16461 //===----------------------------------------------------------------------===//
16462
16463 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16464                                                        APInt &KnownZero,
16465                                                        APInt &KnownOne,
16466                                                        const SelectionDAG &DAG,
16467                                                        unsigned Depth) const {
16468   unsigned BitWidth = KnownZero.getBitWidth();
16469   unsigned Opc = Op.getOpcode();
16470   assert((Opc >= ISD::BUILTIN_OP_END ||
16471           Opc == ISD::INTRINSIC_WO_CHAIN ||
16472           Opc == ISD::INTRINSIC_W_CHAIN ||
16473           Opc == ISD::INTRINSIC_VOID) &&
16474          "Should use MaskedValueIsZero if you don't know whether Op"
16475          " is a target node!");
16476
16477   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16478   switch (Opc) {
16479   default: break;
16480   case X86ISD::ADD:
16481   case X86ISD::SUB:
16482   case X86ISD::ADC:
16483   case X86ISD::SBB:
16484   case X86ISD::SMUL:
16485   case X86ISD::UMUL:
16486   case X86ISD::INC:
16487   case X86ISD::DEC:
16488   case X86ISD::OR:
16489   case X86ISD::XOR:
16490   case X86ISD::AND:
16491     // These nodes' second result is a boolean.
16492     if (Op.getResNo() == 0)
16493       break;
16494     // Fallthrough
16495   case X86ISD::SETCC:
16496     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16497     break;
16498   case ISD::INTRINSIC_WO_CHAIN: {
16499     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16500     unsigned NumLoBits = 0;
16501     switch (IntId) {
16502     default: break;
16503     case Intrinsic::x86_sse_movmsk_ps:
16504     case Intrinsic::x86_avx_movmsk_ps_256:
16505     case Intrinsic::x86_sse2_movmsk_pd:
16506     case Intrinsic::x86_avx_movmsk_pd_256:
16507     case Intrinsic::x86_mmx_pmovmskb:
16508     case Intrinsic::x86_sse2_pmovmskb_128:
16509     case Intrinsic::x86_avx2_pmovmskb: {
16510       // High bits of movmskp{s|d}, pmovmskb are known zero.
16511       switch (IntId) {
16512         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16513         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16514         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16515         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16516         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16517         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16518         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16519         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16520       }
16521       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16522       break;
16523     }
16524     }
16525     break;
16526   }
16527   }
16528 }
16529
16530 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16531                                                          unsigned Depth) const {
16532   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16533   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16534     return Op.getValueType().getScalarType().getSizeInBits();
16535
16536   // Fallback case.
16537   return 1;
16538 }
16539
16540 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16541 /// node is a GlobalAddress + offset.
16542 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16543                                        const GlobalValue* &GA,
16544                                        int64_t &Offset) const {
16545   if (N->getOpcode() == X86ISD::Wrapper) {
16546     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16547       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16548       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16549       return true;
16550     }
16551   }
16552   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16553 }
16554
16555 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16556 /// same as extracting the high 128-bit part of 256-bit vector and then
16557 /// inserting the result into the low part of a new 256-bit vector
16558 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16559   EVT VT = SVOp->getValueType(0);
16560   unsigned NumElems = VT.getVectorNumElements();
16561
16562   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16563   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16564     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16565         SVOp->getMaskElt(j) >= 0)
16566       return false;
16567
16568   return true;
16569 }
16570
16571 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16572 /// same as extracting the low 128-bit part of 256-bit vector and then
16573 /// inserting the result into the high part of a new 256-bit vector
16574 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16575   EVT VT = SVOp->getValueType(0);
16576   unsigned NumElems = VT.getVectorNumElements();
16577
16578   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16579   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16580     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16581         SVOp->getMaskElt(j) >= 0)
16582       return false;
16583
16584   return true;
16585 }
16586
16587 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16588 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16589                                         TargetLowering::DAGCombinerInfo &DCI,
16590                                         const X86Subtarget* Subtarget) {
16591   SDLoc dl(N);
16592   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16593   SDValue V1 = SVOp->getOperand(0);
16594   SDValue V2 = SVOp->getOperand(1);
16595   EVT VT = SVOp->getValueType(0);
16596   unsigned NumElems = VT.getVectorNumElements();
16597
16598   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16599       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16600     //
16601     //                   0,0,0,...
16602     //                      |
16603     //    V      UNDEF    BUILD_VECTOR    UNDEF
16604     //     \      /           \           /
16605     //  CONCAT_VECTOR         CONCAT_VECTOR
16606     //         \                  /
16607     //          \                /
16608     //          RESULT: V + zero extended
16609     //
16610     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16611         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16612         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16613       return SDValue();
16614
16615     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16616       return SDValue();
16617
16618     // To match the shuffle mask, the first half of the mask should
16619     // be exactly the first vector, and all the rest a splat with the
16620     // first element of the second one.
16621     for (unsigned i = 0; i != NumElems/2; ++i)
16622       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16623           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16624         return SDValue();
16625
16626     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16627     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16628       if (Ld->hasNUsesOfValue(1, 0)) {
16629         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16630         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16631         SDValue ResNode =
16632           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16633                                   array_lengthof(Ops),
16634                                   Ld->getMemoryVT(),
16635                                   Ld->getPointerInfo(),
16636                                   Ld->getAlignment(),
16637                                   false/*isVolatile*/, true/*ReadMem*/,
16638                                   false/*WriteMem*/);
16639
16640         // Make sure the newly-created LOAD is in the same position as Ld in
16641         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16642         // and update uses of Ld's output chain to use the TokenFactor.
16643         if (Ld->hasAnyUseOfValue(1)) {
16644           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16645                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16646           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16647           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16648                                  SDValue(ResNode.getNode(), 1));
16649         }
16650
16651         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16652       }
16653     }
16654
16655     // Emit a zeroed vector and insert the desired subvector on its
16656     // first half.
16657     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16658     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16659     return DCI.CombineTo(N, InsV);
16660   }
16661
16662   //===--------------------------------------------------------------------===//
16663   // Combine some shuffles into subvector extracts and inserts:
16664   //
16665
16666   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16667   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16668     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16669     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16670     return DCI.CombineTo(N, InsV);
16671   }
16672
16673   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16674   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16675     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16676     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16677     return DCI.CombineTo(N, InsV);
16678   }
16679
16680   return SDValue();
16681 }
16682
16683 /// PerformShuffleCombine - Performs several different shuffle combines.
16684 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16685                                      TargetLowering::DAGCombinerInfo &DCI,
16686                                      const X86Subtarget *Subtarget) {
16687   SDLoc dl(N);
16688   EVT VT = N->getValueType(0);
16689
16690   // Don't create instructions with illegal types after legalize types has run.
16691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16692   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16693     return SDValue();
16694
16695   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16696   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16697       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16698     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16699
16700   // Only handle 128 wide vector from here on.
16701   if (!VT.is128BitVector())
16702     return SDValue();
16703
16704   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16705   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16706   // consecutive, non-overlapping, and in the right order.
16707   SmallVector<SDValue, 16> Elts;
16708   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16709     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16710
16711   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16712 }
16713
16714 /// PerformTruncateCombine - Converts truncate operation to
16715 /// a sequence of vector shuffle operations.
16716 /// It is possible when we truncate 256-bit vector to 128-bit vector
16717 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16718                                       TargetLowering::DAGCombinerInfo &DCI,
16719                                       const X86Subtarget *Subtarget)  {
16720   return SDValue();
16721 }
16722
16723 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16724 /// specific shuffle of a load can be folded into a single element load.
16725 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16726 /// shuffles have been customed lowered so we need to handle those here.
16727 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16728                                          TargetLowering::DAGCombinerInfo &DCI) {
16729   if (DCI.isBeforeLegalizeOps())
16730     return SDValue();
16731
16732   SDValue InVec = N->getOperand(0);
16733   SDValue EltNo = N->getOperand(1);
16734
16735   if (!isa<ConstantSDNode>(EltNo))
16736     return SDValue();
16737
16738   EVT VT = InVec.getValueType();
16739
16740   bool HasShuffleIntoBitcast = false;
16741   if (InVec.getOpcode() == ISD::BITCAST) {
16742     // Don't duplicate a load with other uses.
16743     if (!InVec.hasOneUse())
16744       return SDValue();
16745     EVT BCVT = InVec.getOperand(0).getValueType();
16746     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16747       return SDValue();
16748     InVec = InVec.getOperand(0);
16749     HasShuffleIntoBitcast = true;
16750   }
16751
16752   if (!isTargetShuffle(InVec.getOpcode()))
16753     return SDValue();
16754
16755   // Don't duplicate a load with other uses.
16756   if (!InVec.hasOneUse())
16757     return SDValue();
16758
16759   SmallVector<int, 16> ShuffleMask;
16760   bool UnaryShuffle;
16761   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16762                             UnaryShuffle))
16763     return SDValue();
16764
16765   // Select the input vector, guarding against out of range extract vector.
16766   unsigned NumElems = VT.getVectorNumElements();
16767   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16768   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16769   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16770                                          : InVec.getOperand(1);
16771
16772   // If inputs to shuffle are the same for both ops, then allow 2 uses
16773   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16774
16775   if (LdNode.getOpcode() == ISD::BITCAST) {
16776     // Don't duplicate a load with other uses.
16777     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16778       return SDValue();
16779
16780     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16781     LdNode = LdNode.getOperand(0);
16782   }
16783
16784   if (!ISD::isNormalLoad(LdNode.getNode()))
16785     return SDValue();
16786
16787   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16788
16789   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16790     return SDValue();
16791
16792   if (HasShuffleIntoBitcast) {
16793     // If there's a bitcast before the shuffle, check if the load type and
16794     // alignment is valid.
16795     unsigned Align = LN0->getAlignment();
16796     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16797     unsigned NewAlign = TLI.getDataLayout()->
16798       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16799
16800     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16801       return SDValue();
16802   }
16803
16804   // All checks match so transform back to vector_shuffle so that DAG combiner
16805   // can finish the job
16806   SDLoc dl(N);
16807
16808   // Create shuffle node taking into account the case that its a unary shuffle
16809   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16810   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16811                                  InVec.getOperand(0), Shuffle,
16812                                  &ShuffleMask[0]);
16813   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16814   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16815                      EltNo);
16816 }
16817
16818 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16819 /// generation and convert it from being a bunch of shuffles and extracts
16820 /// to a simple store and scalar loads to extract the elements.
16821 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16822                                          TargetLowering::DAGCombinerInfo &DCI) {
16823   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16824   if (NewOp.getNode())
16825     return NewOp;
16826
16827   SDValue InputVector = N->getOperand(0);
16828
16829   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16830   // from mmx to v2i32 has a single usage.
16831   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16832       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16833       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16834     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16835                        N->getValueType(0),
16836                        InputVector.getNode()->getOperand(0));
16837
16838   // Only operate on vectors of 4 elements, where the alternative shuffling
16839   // gets to be more expensive.
16840   if (InputVector.getValueType() != MVT::v4i32)
16841     return SDValue();
16842
16843   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16844   // single use which is a sign-extend or zero-extend, and all elements are
16845   // used.
16846   SmallVector<SDNode *, 4> Uses;
16847   unsigned ExtractedElements = 0;
16848   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16849        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16850     if (UI.getUse().getResNo() != InputVector.getResNo())
16851       return SDValue();
16852
16853     SDNode *Extract = *UI;
16854     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16855       return SDValue();
16856
16857     if (Extract->getValueType(0) != MVT::i32)
16858       return SDValue();
16859     if (!Extract->hasOneUse())
16860       return SDValue();
16861     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16862         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16863       return SDValue();
16864     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16865       return SDValue();
16866
16867     // Record which element was extracted.
16868     ExtractedElements |=
16869       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16870
16871     Uses.push_back(Extract);
16872   }
16873
16874   // If not all the elements were used, this may not be worthwhile.
16875   if (ExtractedElements != 15)
16876     return SDValue();
16877
16878   // Ok, we've now decided to do the transformation.
16879   SDLoc dl(InputVector);
16880
16881   // Store the value to a temporary stack slot.
16882   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16883   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16884                             MachinePointerInfo(), false, false, 0);
16885
16886   // Replace each use (extract) with a load of the appropriate element.
16887   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16888        UE = Uses.end(); UI != UE; ++UI) {
16889     SDNode *Extract = *UI;
16890
16891     // cOMpute the element's address.
16892     SDValue Idx = Extract->getOperand(1);
16893     unsigned EltSize =
16894         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16895     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16896     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16897     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16898
16899     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16900                                      StackPtr, OffsetVal);
16901
16902     // Load the scalar.
16903     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16904                                      ScalarAddr, MachinePointerInfo(),
16905                                      false, false, false, 0);
16906
16907     // Replace the exact with the load.
16908     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16909   }
16910
16911   // The replacement was made in place; don't return anything.
16912   return SDValue();
16913 }
16914
16915 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16916 static std::pair<unsigned, bool>
16917 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16918                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16919   if (!VT.isVector())
16920     return std::make_pair(0, false);
16921
16922   bool NeedSplit = false;
16923   switch (VT.getSimpleVT().SimpleTy) {
16924   default: return std::make_pair(0, false);
16925   case MVT::v32i8:
16926   case MVT::v16i16:
16927   case MVT::v8i32:
16928     if (!Subtarget->hasAVX2())
16929       NeedSplit = true;
16930     if (!Subtarget->hasAVX())
16931       return std::make_pair(0, false);
16932     break;
16933   case MVT::v16i8:
16934   case MVT::v8i16:
16935   case MVT::v4i32:
16936     if (!Subtarget->hasSSE2())
16937       return std::make_pair(0, false);
16938   }
16939
16940   // SSE2 has only a small subset of the operations.
16941   bool hasUnsigned = Subtarget->hasSSE41() ||
16942                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16943   bool hasSigned = Subtarget->hasSSE41() ||
16944                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16945
16946   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16947
16948   unsigned Opc = 0;
16949   // Check for x CC y ? x : y.
16950   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16951       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16952     switch (CC) {
16953     default: break;
16954     case ISD::SETULT:
16955     case ISD::SETULE:
16956       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16957     case ISD::SETUGT:
16958     case ISD::SETUGE:
16959       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16960     case ISD::SETLT:
16961     case ISD::SETLE:
16962       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16963     case ISD::SETGT:
16964     case ISD::SETGE:
16965       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16966     }
16967   // Check for x CC y ? y : x -- a min/max with reversed arms.
16968   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16969              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16970     switch (CC) {
16971     default: break;
16972     case ISD::SETULT:
16973     case ISD::SETULE:
16974       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16975     case ISD::SETUGT:
16976     case ISD::SETUGE:
16977       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16978     case ISD::SETLT:
16979     case ISD::SETLE:
16980       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16981     case ISD::SETGT:
16982     case ISD::SETGE:
16983       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16984     }
16985   }
16986
16987   return std::make_pair(Opc, NeedSplit);
16988 }
16989
16990 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16991 /// nodes.
16992 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16993                                     TargetLowering::DAGCombinerInfo &DCI,
16994                                     const X86Subtarget *Subtarget) {
16995   SDLoc DL(N);
16996   SDValue Cond = N->getOperand(0);
16997   // Get the LHS/RHS of the select.
16998   SDValue LHS = N->getOperand(1);
16999   SDValue RHS = N->getOperand(2);
17000   EVT VT = LHS.getValueType();
17001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17002
17003   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17004   // instructions match the semantics of the common C idiom x<y?x:y but not
17005   // x<=y?x:y, because of how they handle negative zero (which can be
17006   // ignored in unsafe-math mode).
17007   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17008       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17009       (Subtarget->hasSSE2() ||
17010        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17011     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17012
17013     unsigned Opcode = 0;
17014     // Check for x CC y ? x : y.
17015     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17016         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17017       switch (CC) {
17018       default: break;
17019       case ISD::SETULT:
17020         // Converting this to a min would handle NaNs incorrectly, and swapping
17021         // the operands would cause it to handle comparisons between positive
17022         // and negative zero incorrectly.
17023         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17024           if (!DAG.getTarget().Options.UnsafeFPMath &&
17025               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17026             break;
17027           std::swap(LHS, RHS);
17028         }
17029         Opcode = X86ISD::FMIN;
17030         break;
17031       case ISD::SETOLE:
17032         // Converting this to a min would handle comparisons between positive
17033         // and negative zero incorrectly.
17034         if (!DAG.getTarget().Options.UnsafeFPMath &&
17035             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17036           break;
17037         Opcode = X86ISD::FMIN;
17038         break;
17039       case ISD::SETULE:
17040         // Converting this to a min would handle both negative zeros and NaNs
17041         // incorrectly, but we can swap the operands to fix both.
17042         std::swap(LHS, RHS);
17043       case ISD::SETOLT:
17044       case ISD::SETLT:
17045       case ISD::SETLE:
17046         Opcode = X86ISD::FMIN;
17047         break;
17048
17049       case ISD::SETOGE:
17050         // Converting this to a max would handle comparisons between positive
17051         // and negative zero incorrectly.
17052         if (!DAG.getTarget().Options.UnsafeFPMath &&
17053             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17054           break;
17055         Opcode = X86ISD::FMAX;
17056         break;
17057       case ISD::SETUGT:
17058         // Converting this to a max would handle NaNs incorrectly, and swapping
17059         // the operands would cause it to handle comparisons between positive
17060         // and negative zero incorrectly.
17061         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17062           if (!DAG.getTarget().Options.UnsafeFPMath &&
17063               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17064             break;
17065           std::swap(LHS, RHS);
17066         }
17067         Opcode = X86ISD::FMAX;
17068         break;
17069       case ISD::SETUGE:
17070         // Converting this to a max would handle both negative zeros and NaNs
17071         // incorrectly, but we can swap the operands to fix both.
17072         std::swap(LHS, RHS);
17073       case ISD::SETOGT:
17074       case ISD::SETGT:
17075       case ISD::SETGE:
17076         Opcode = X86ISD::FMAX;
17077         break;
17078       }
17079     // Check for x CC y ? y : x -- a min/max with reversed arms.
17080     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17081                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17082       switch (CC) {
17083       default: break;
17084       case ISD::SETOGE:
17085         // Converting this to a min would handle comparisons between positive
17086         // and negative zero incorrectly, and swapping the operands would
17087         // cause it to handle NaNs incorrectly.
17088         if (!DAG.getTarget().Options.UnsafeFPMath &&
17089             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17090           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17091             break;
17092           std::swap(LHS, RHS);
17093         }
17094         Opcode = X86ISD::FMIN;
17095         break;
17096       case ISD::SETUGT:
17097         // Converting this to a min would handle NaNs incorrectly.
17098         if (!DAG.getTarget().Options.UnsafeFPMath &&
17099             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17100           break;
17101         Opcode = X86ISD::FMIN;
17102         break;
17103       case ISD::SETUGE:
17104         // Converting this to a min would handle both negative zeros and NaNs
17105         // incorrectly, but we can swap the operands to fix both.
17106         std::swap(LHS, RHS);
17107       case ISD::SETOGT:
17108       case ISD::SETGT:
17109       case ISD::SETGE:
17110         Opcode = X86ISD::FMIN;
17111         break;
17112
17113       case ISD::SETULT:
17114         // Converting this to a max would handle NaNs incorrectly.
17115         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17116           break;
17117         Opcode = X86ISD::FMAX;
17118         break;
17119       case ISD::SETOLE:
17120         // Converting this to a max would handle comparisons between positive
17121         // and negative zero incorrectly, and swapping the operands would
17122         // cause it to handle NaNs incorrectly.
17123         if (!DAG.getTarget().Options.UnsafeFPMath &&
17124             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17125           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17126             break;
17127           std::swap(LHS, RHS);
17128         }
17129         Opcode = X86ISD::FMAX;
17130         break;
17131       case ISD::SETULE:
17132         // Converting this to a max would handle both negative zeros and NaNs
17133         // incorrectly, but we can swap the operands to fix both.
17134         std::swap(LHS, RHS);
17135       case ISD::SETOLT:
17136       case ISD::SETLT:
17137       case ISD::SETLE:
17138         Opcode = X86ISD::FMAX;
17139         break;
17140       }
17141     }
17142
17143     if (Opcode)
17144       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17145   }
17146
17147   EVT CondVT = Cond.getValueType();
17148   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17149       CondVT.getVectorElementType() == MVT::i1) {
17150     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17151     // lowering on AVX-512. In this case we convert it to
17152     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17153     // The same situation for all 128 and 256-bit vectors of i8 and i16
17154     EVT OpVT = LHS.getValueType();
17155     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17156         (OpVT.getVectorElementType() == MVT::i8 ||
17157          OpVT.getVectorElementType() == MVT::i16)) {
17158       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17159       DCI.AddToWorklist(Cond.getNode());
17160       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17161     }
17162   }
17163   // If this is a select between two integer constants, try to do some
17164   // optimizations.
17165   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17166     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17167       // Don't do this for crazy integer types.
17168       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17169         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17170         // so that TrueC (the true value) is larger than FalseC.
17171         bool NeedsCondInvert = false;
17172
17173         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17174             // Efficiently invertible.
17175             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17176              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17177               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17178           NeedsCondInvert = true;
17179           std::swap(TrueC, FalseC);
17180         }
17181
17182         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17183         if (FalseC->getAPIntValue() == 0 &&
17184             TrueC->getAPIntValue().isPowerOf2()) {
17185           if (NeedsCondInvert) // Invert the condition if needed.
17186             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17187                                DAG.getConstant(1, Cond.getValueType()));
17188
17189           // Zero extend the condition if needed.
17190           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17191
17192           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17193           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17194                              DAG.getConstant(ShAmt, MVT::i8));
17195         }
17196
17197         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17198         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17199           if (NeedsCondInvert) // Invert the condition if needed.
17200             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17201                                DAG.getConstant(1, Cond.getValueType()));
17202
17203           // Zero extend the condition if needed.
17204           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17205                              FalseC->getValueType(0), Cond);
17206           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17207                              SDValue(FalseC, 0));
17208         }
17209
17210         // Optimize cases that will turn into an LEA instruction.  This requires
17211         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17212         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17213           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17214           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17215
17216           bool isFastMultiplier = false;
17217           if (Diff < 10) {
17218             switch ((unsigned char)Diff) {
17219               default: break;
17220               case 1:  // result = add base, cond
17221               case 2:  // result = lea base(    , cond*2)
17222               case 3:  // result = lea base(cond, cond*2)
17223               case 4:  // result = lea base(    , cond*4)
17224               case 5:  // result = lea base(cond, cond*4)
17225               case 8:  // result = lea base(    , cond*8)
17226               case 9:  // result = lea base(cond, cond*8)
17227                 isFastMultiplier = true;
17228                 break;
17229             }
17230           }
17231
17232           if (isFastMultiplier) {
17233             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17234             if (NeedsCondInvert) // Invert the condition if needed.
17235               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17236                                  DAG.getConstant(1, Cond.getValueType()));
17237
17238             // Zero extend the condition if needed.
17239             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17240                                Cond);
17241             // Scale the condition by the difference.
17242             if (Diff != 1)
17243               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17244                                  DAG.getConstant(Diff, Cond.getValueType()));
17245
17246             // Add the base if non-zero.
17247             if (FalseC->getAPIntValue() != 0)
17248               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17249                                  SDValue(FalseC, 0));
17250             return Cond;
17251           }
17252         }
17253       }
17254   }
17255
17256   // Canonicalize max and min:
17257   // (x > y) ? x : y -> (x >= y) ? x : y
17258   // (x < y) ? x : y -> (x <= y) ? x : y
17259   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17260   // the need for an extra compare
17261   // against zero. e.g.
17262   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17263   // subl   %esi, %edi
17264   // testl  %edi, %edi
17265   // movl   $0, %eax
17266   // cmovgl %edi, %eax
17267   // =>
17268   // xorl   %eax, %eax
17269   // subl   %esi, $edi
17270   // cmovsl %eax, %edi
17271   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17272       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17273       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17274     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17275     switch (CC) {
17276     default: break;
17277     case ISD::SETLT:
17278     case ISD::SETGT: {
17279       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17280       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17281                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17282       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17283     }
17284     }
17285   }
17286
17287   // Early exit check
17288   if (!TLI.isTypeLegal(VT))
17289     return SDValue();
17290
17291   // Match VSELECTs into subs with unsigned saturation.
17292   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17293       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17294       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17295        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17296     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17297
17298     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17299     // left side invert the predicate to simplify logic below.
17300     SDValue Other;
17301     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17302       Other = RHS;
17303       CC = ISD::getSetCCInverse(CC, true);
17304     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17305       Other = LHS;
17306     }
17307
17308     if (Other.getNode() && Other->getNumOperands() == 2 &&
17309         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17310       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17311       SDValue CondRHS = Cond->getOperand(1);
17312
17313       // Look for a general sub with unsigned saturation first.
17314       // x >= y ? x-y : 0 --> subus x, y
17315       // x >  y ? x-y : 0 --> subus x, y
17316       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17317           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17318         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17319
17320       // If the RHS is a constant we have to reverse the const canonicalization.
17321       // x > C-1 ? x+-C : 0 --> subus x, C
17322       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17323           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17324         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17325         if (CondRHS.getConstantOperandVal(0) == -A-1)
17326           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17327                              DAG.getConstant(-A, VT));
17328       }
17329
17330       // Another special case: If C was a sign bit, the sub has been
17331       // canonicalized into a xor.
17332       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17333       //        it's safe to decanonicalize the xor?
17334       // x s< 0 ? x^C : 0 --> subus x, C
17335       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17336           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17337           isSplatVector(OpRHS.getNode())) {
17338         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17339         if (A.isSignBit())
17340           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17341       }
17342     }
17343   }
17344
17345   // Try to match a min/max vector operation.
17346   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17347     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17348     unsigned Opc = ret.first;
17349     bool NeedSplit = ret.second;
17350
17351     if (Opc && NeedSplit) {
17352       unsigned NumElems = VT.getVectorNumElements();
17353       // Extract the LHS vectors
17354       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17355       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17356
17357       // Extract the RHS vectors
17358       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17359       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17360
17361       // Create min/max for each subvector
17362       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17363       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17364
17365       // Merge the result
17366       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17367     } else if (Opc)
17368       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17369   }
17370
17371   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17372   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17373       // Check if SETCC has already been promoted
17374       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17375       // Check that condition value type matches vselect operand type
17376       CondVT == VT) { 
17377
17378     assert(Cond.getValueType().isVector() &&
17379            "vector select expects a vector selector!");
17380
17381     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17382     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17383
17384     if (!TValIsAllOnes && !FValIsAllZeros) {
17385       // Try invert the condition if true value is not all 1s and false value
17386       // is not all 0s.
17387       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17388       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17389
17390       if (TValIsAllZeros || FValIsAllOnes) {
17391         SDValue CC = Cond.getOperand(2);
17392         ISD::CondCode NewCC =
17393           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17394                                Cond.getOperand(0).getValueType().isInteger());
17395         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17396         std::swap(LHS, RHS);
17397         TValIsAllOnes = FValIsAllOnes;
17398         FValIsAllZeros = TValIsAllZeros;
17399       }
17400     }
17401
17402     if (TValIsAllOnes || FValIsAllZeros) {
17403       SDValue Ret;
17404
17405       if (TValIsAllOnes && FValIsAllZeros)
17406         Ret = Cond;
17407       else if (TValIsAllOnes)
17408         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17409                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17410       else if (FValIsAllZeros)
17411         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17412                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17413
17414       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17415     }
17416   }
17417
17418   // Try to fold this VSELECT into a MOVSS/MOVSD
17419   if (N->getOpcode() == ISD::VSELECT &&
17420       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17421     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17422         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17423       bool CanFold = false;
17424       unsigned NumElems = Cond.getNumOperands();
17425       SDValue A = LHS;
17426       SDValue B = RHS;
17427       
17428       if (isZero(Cond.getOperand(0))) {
17429         CanFold = true;
17430
17431         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17432         // fold (vselect <0,-1> -> (movsd A, B)
17433         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17434           CanFold = isAllOnes(Cond.getOperand(i));
17435       } else if (isAllOnes(Cond.getOperand(0))) {
17436         CanFold = true;
17437         std::swap(A, B);
17438
17439         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17440         // fold (vselect <-1,0> -> (movsd B, A)
17441         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17442           CanFold = isZero(Cond.getOperand(i));
17443       }
17444
17445       if (CanFold) {
17446         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17447           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17448         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17449       }
17450
17451       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17452         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17453         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17454         //                             (v2i64 (bitcast B)))))
17455         //
17456         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17457         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17458         //                             (v2f64 (bitcast B)))))
17459         //
17460         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17461         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17462         //                             (v2i64 (bitcast A)))))
17463         //
17464         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17465         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17466         //                             (v2f64 (bitcast A)))))
17467
17468         CanFold = (isZero(Cond.getOperand(0)) &&
17469                    isZero(Cond.getOperand(1)) &&
17470                    isAllOnes(Cond.getOperand(2)) &&
17471                    isAllOnes(Cond.getOperand(3)));
17472
17473         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17474             isAllOnes(Cond.getOperand(1)) &&
17475             isZero(Cond.getOperand(2)) &&
17476             isZero(Cond.getOperand(3))) {
17477           CanFold = true;
17478           std::swap(LHS, RHS);
17479         }
17480
17481         if (CanFold) {
17482           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17483           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17484           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17485           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17486                                                 NewB, DAG);
17487           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17488         }
17489       }
17490     }
17491   }
17492
17493   // If we know that this node is legal then we know that it is going to be
17494   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17495   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17496   // to simplify previous instructions.
17497   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17498       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17499     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17500
17501     // Don't optimize vector selects that map to mask-registers.
17502     if (BitWidth == 1)
17503       return SDValue();
17504
17505     // Check all uses of that condition operand to check whether it will be
17506     // consumed by non-BLEND instructions, which may depend on all bits are set
17507     // properly.
17508     for (SDNode::use_iterator I = Cond->use_begin(),
17509                               E = Cond->use_end(); I != E; ++I)
17510       if (I->getOpcode() != ISD::VSELECT)
17511         // TODO: Add other opcodes eventually lowered into BLEND.
17512         return SDValue();
17513
17514     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17515     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17516
17517     APInt KnownZero, KnownOne;
17518     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17519                                           DCI.isBeforeLegalizeOps());
17520     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17521         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17522       DCI.CommitTargetLoweringOpt(TLO);
17523   }
17524
17525   return SDValue();
17526 }
17527
17528 // Check whether a boolean test is testing a boolean value generated by
17529 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17530 // code.
17531 //
17532 // Simplify the following patterns:
17533 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17534 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17535 // to (Op EFLAGS Cond)
17536 //
17537 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17538 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17539 // to (Op EFLAGS !Cond)
17540 //
17541 // where Op could be BRCOND or CMOV.
17542 //
17543 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17544   // Quit if not CMP and SUB with its value result used.
17545   if (Cmp.getOpcode() != X86ISD::CMP &&
17546       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17547       return SDValue();
17548
17549   // Quit if not used as a boolean value.
17550   if (CC != X86::COND_E && CC != X86::COND_NE)
17551     return SDValue();
17552
17553   // Check CMP operands. One of them should be 0 or 1 and the other should be
17554   // an SetCC or extended from it.
17555   SDValue Op1 = Cmp.getOperand(0);
17556   SDValue Op2 = Cmp.getOperand(1);
17557
17558   SDValue SetCC;
17559   const ConstantSDNode* C = 0;
17560   bool needOppositeCond = (CC == X86::COND_E);
17561   bool checkAgainstTrue = false; // Is it a comparison against 1?
17562
17563   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17564     SetCC = Op2;
17565   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17566     SetCC = Op1;
17567   else // Quit if all operands are not constants.
17568     return SDValue();
17569
17570   if (C->getZExtValue() == 1) {
17571     needOppositeCond = !needOppositeCond;
17572     checkAgainstTrue = true;
17573   } else if (C->getZExtValue() != 0)
17574     // Quit if the constant is neither 0 or 1.
17575     return SDValue();
17576
17577   bool truncatedToBoolWithAnd = false;
17578   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17579   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17580          SetCC.getOpcode() == ISD::TRUNCATE ||
17581          SetCC.getOpcode() == ISD::AND) {
17582     if (SetCC.getOpcode() == ISD::AND) {
17583       int OpIdx = -1;
17584       ConstantSDNode *CS;
17585       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17586           CS->getZExtValue() == 1)
17587         OpIdx = 1;
17588       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17589           CS->getZExtValue() == 1)
17590         OpIdx = 0;
17591       if (OpIdx == -1)
17592         break;
17593       SetCC = SetCC.getOperand(OpIdx);
17594       truncatedToBoolWithAnd = true;
17595     } else
17596       SetCC = SetCC.getOperand(0);
17597   }
17598
17599   switch (SetCC.getOpcode()) {
17600   case X86ISD::SETCC_CARRY:
17601     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17602     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17603     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17604     // truncated to i1 using 'and'.
17605     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17606       break;
17607     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17608            "Invalid use of SETCC_CARRY!");
17609     // FALL THROUGH
17610   case X86ISD::SETCC:
17611     // Set the condition code or opposite one if necessary.
17612     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17613     if (needOppositeCond)
17614       CC = X86::GetOppositeBranchCondition(CC);
17615     return SetCC.getOperand(1);
17616   case X86ISD::CMOV: {
17617     // Check whether false/true value has canonical one, i.e. 0 or 1.
17618     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17619     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17620     // Quit if true value is not a constant.
17621     if (!TVal)
17622       return SDValue();
17623     // Quit if false value is not a constant.
17624     if (!FVal) {
17625       SDValue Op = SetCC.getOperand(0);
17626       // Skip 'zext' or 'trunc' node.
17627       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17628           Op.getOpcode() == ISD::TRUNCATE)
17629         Op = Op.getOperand(0);
17630       // A special case for rdrand/rdseed, where 0 is set if false cond is
17631       // found.
17632       if ((Op.getOpcode() != X86ISD::RDRAND &&
17633            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17634         return SDValue();
17635     }
17636     // Quit if false value is not the constant 0 or 1.
17637     bool FValIsFalse = true;
17638     if (FVal && FVal->getZExtValue() != 0) {
17639       if (FVal->getZExtValue() != 1)
17640         return SDValue();
17641       // If FVal is 1, opposite cond is needed.
17642       needOppositeCond = !needOppositeCond;
17643       FValIsFalse = false;
17644     }
17645     // Quit if TVal is not the constant opposite of FVal.
17646     if (FValIsFalse && TVal->getZExtValue() != 1)
17647       return SDValue();
17648     if (!FValIsFalse && TVal->getZExtValue() != 0)
17649       return SDValue();
17650     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17651     if (needOppositeCond)
17652       CC = X86::GetOppositeBranchCondition(CC);
17653     return SetCC.getOperand(3);
17654   }
17655   }
17656
17657   return SDValue();
17658 }
17659
17660 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17661 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17662                                   TargetLowering::DAGCombinerInfo &DCI,
17663                                   const X86Subtarget *Subtarget) {
17664   SDLoc DL(N);
17665
17666   // If the flag operand isn't dead, don't touch this CMOV.
17667   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17668     return SDValue();
17669
17670   SDValue FalseOp = N->getOperand(0);
17671   SDValue TrueOp = N->getOperand(1);
17672   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17673   SDValue Cond = N->getOperand(3);
17674
17675   if (CC == X86::COND_E || CC == X86::COND_NE) {
17676     switch (Cond.getOpcode()) {
17677     default: break;
17678     case X86ISD::BSR:
17679     case X86ISD::BSF:
17680       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17681       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17682         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17683     }
17684   }
17685
17686   SDValue Flags;
17687
17688   Flags = checkBoolTestSetCCCombine(Cond, CC);
17689   if (Flags.getNode() &&
17690       // Extra check as FCMOV only supports a subset of X86 cond.
17691       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17692     SDValue Ops[] = { FalseOp, TrueOp,
17693                       DAG.getConstant(CC, MVT::i8), Flags };
17694     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17695                        Ops, array_lengthof(Ops));
17696   }
17697
17698   // If this is a select between two integer constants, try to do some
17699   // optimizations.  Note that the operands are ordered the opposite of SELECT
17700   // operands.
17701   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17702     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17703       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17704       // larger than FalseC (the false value).
17705       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17706         CC = X86::GetOppositeBranchCondition(CC);
17707         std::swap(TrueC, FalseC);
17708         std::swap(TrueOp, FalseOp);
17709       }
17710
17711       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17712       // This is efficient for any integer data type (including i8/i16) and
17713       // shift amount.
17714       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17715         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17716                            DAG.getConstant(CC, MVT::i8), Cond);
17717
17718         // Zero extend the condition if needed.
17719         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17720
17721         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17722         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17723                            DAG.getConstant(ShAmt, MVT::i8));
17724         if (N->getNumValues() == 2)  // Dead flag value?
17725           return DCI.CombineTo(N, Cond, SDValue());
17726         return Cond;
17727       }
17728
17729       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17730       // for any integer data type, including i8/i16.
17731       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17732         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17733                            DAG.getConstant(CC, MVT::i8), Cond);
17734
17735         // Zero extend the condition if needed.
17736         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17737                            FalseC->getValueType(0), Cond);
17738         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17739                            SDValue(FalseC, 0));
17740
17741         if (N->getNumValues() == 2)  // Dead flag value?
17742           return DCI.CombineTo(N, Cond, SDValue());
17743         return Cond;
17744       }
17745
17746       // Optimize cases that will turn into an LEA instruction.  This requires
17747       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17748       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17749         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17750         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17751
17752         bool isFastMultiplier = false;
17753         if (Diff < 10) {
17754           switch ((unsigned char)Diff) {
17755           default: break;
17756           case 1:  // result = add base, cond
17757           case 2:  // result = lea base(    , cond*2)
17758           case 3:  // result = lea base(cond, cond*2)
17759           case 4:  // result = lea base(    , cond*4)
17760           case 5:  // result = lea base(cond, cond*4)
17761           case 8:  // result = lea base(    , cond*8)
17762           case 9:  // result = lea base(cond, cond*8)
17763             isFastMultiplier = true;
17764             break;
17765           }
17766         }
17767
17768         if (isFastMultiplier) {
17769           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17770           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17771                              DAG.getConstant(CC, MVT::i8), Cond);
17772           // Zero extend the condition if needed.
17773           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17774                              Cond);
17775           // Scale the condition by the difference.
17776           if (Diff != 1)
17777             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17778                                DAG.getConstant(Diff, Cond.getValueType()));
17779
17780           // Add the base if non-zero.
17781           if (FalseC->getAPIntValue() != 0)
17782             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17783                                SDValue(FalseC, 0));
17784           if (N->getNumValues() == 2)  // Dead flag value?
17785             return DCI.CombineTo(N, Cond, SDValue());
17786           return Cond;
17787         }
17788       }
17789     }
17790   }
17791
17792   // Handle these cases:
17793   //   (select (x != c), e, c) -> select (x != c), e, x),
17794   //   (select (x == c), c, e) -> select (x == c), x, e)
17795   // where the c is an integer constant, and the "select" is the combination
17796   // of CMOV and CMP.
17797   //
17798   // The rationale for this change is that the conditional-move from a constant
17799   // needs two instructions, however, conditional-move from a register needs
17800   // only one instruction.
17801   //
17802   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17803   //  some instruction-combining opportunities. This opt needs to be
17804   //  postponed as late as possible.
17805   //
17806   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17807     // the DCI.xxxx conditions are provided to postpone the optimization as
17808     // late as possible.
17809
17810     ConstantSDNode *CmpAgainst = 0;
17811     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17812         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17813         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17814
17815       if (CC == X86::COND_NE &&
17816           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17817         CC = X86::GetOppositeBranchCondition(CC);
17818         std::swap(TrueOp, FalseOp);
17819       }
17820
17821       if (CC == X86::COND_E &&
17822           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17823         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17824                           DAG.getConstant(CC, MVT::i8), Cond };
17825         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17826                            array_lengthof(Ops));
17827       }
17828     }
17829   }
17830
17831   return SDValue();
17832 }
17833
17834 /// PerformMulCombine - Optimize a single multiply with constant into two
17835 /// in order to implement it with two cheaper instructions, e.g.
17836 /// LEA + SHL, LEA + LEA.
17837 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17838                                  TargetLowering::DAGCombinerInfo &DCI) {
17839   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17840     return SDValue();
17841
17842   EVT VT = N->getValueType(0);
17843   if (VT != MVT::i64)
17844     return SDValue();
17845
17846   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17847   if (!C)
17848     return SDValue();
17849   uint64_t MulAmt = C->getZExtValue();
17850   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17851     return SDValue();
17852
17853   uint64_t MulAmt1 = 0;
17854   uint64_t MulAmt2 = 0;
17855   if ((MulAmt % 9) == 0) {
17856     MulAmt1 = 9;
17857     MulAmt2 = MulAmt / 9;
17858   } else if ((MulAmt % 5) == 0) {
17859     MulAmt1 = 5;
17860     MulAmt2 = MulAmt / 5;
17861   } else if ((MulAmt % 3) == 0) {
17862     MulAmt1 = 3;
17863     MulAmt2 = MulAmt / 3;
17864   }
17865   if (MulAmt2 &&
17866       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17867     SDLoc DL(N);
17868
17869     if (isPowerOf2_64(MulAmt2) &&
17870         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17871       // If second multiplifer is pow2, issue it first. We want the multiply by
17872       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17873       // is an add.
17874       std::swap(MulAmt1, MulAmt2);
17875
17876     SDValue NewMul;
17877     if (isPowerOf2_64(MulAmt1))
17878       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17879                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17880     else
17881       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17882                            DAG.getConstant(MulAmt1, VT));
17883
17884     if (isPowerOf2_64(MulAmt2))
17885       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17886                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17887     else
17888       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17889                            DAG.getConstant(MulAmt2, VT));
17890
17891     // Do not add new nodes to DAG combiner worklist.
17892     DCI.CombineTo(N, NewMul, false);
17893   }
17894   return SDValue();
17895 }
17896
17897 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17898   SDValue N0 = N->getOperand(0);
17899   SDValue N1 = N->getOperand(1);
17900   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17901   EVT VT = N0.getValueType();
17902
17903   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17904   // since the result of setcc_c is all zero's or all ones.
17905   if (VT.isInteger() && !VT.isVector() &&
17906       N1C && N0.getOpcode() == ISD::AND &&
17907       N0.getOperand(1).getOpcode() == ISD::Constant) {
17908     SDValue N00 = N0.getOperand(0);
17909     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17910         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17911           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17912          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17913       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17914       APInt ShAmt = N1C->getAPIntValue();
17915       Mask = Mask.shl(ShAmt);
17916       if (Mask != 0)
17917         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17918                            N00, DAG.getConstant(Mask, VT));
17919     }
17920   }
17921
17922   // Hardware support for vector shifts is sparse which makes us scalarize the
17923   // vector operations in many cases. Also, on sandybridge ADD is faster than
17924   // shl.
17925   // (shl V, 1) -> add V,V
17926   if (isSplatVector(N1.getNode())) {
17927     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17928     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17929     // We shift all of the values by one. In many cases we do not have
17930     // hardware support for this operation. This is better expressed as an ADD
17931     // of two values.
17932     if (N1C && (1 == N1C->getZExtValue())) {
17933       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17934     }
17935   }
17936
17937   return SDValue();
17938 }
17939
17940 /// \brief Returns a vector of 0s if the node in input is a vector logical
17941 /// shift by a constant amount which is known to be bigger than or equal
17942 /// to the vector element size in bits.
17943 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17944                                       const X86Subtarget *Subtarget) {
17945   EVT VT = N->getValueType(0);
17946
17947   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17948       (!Subtarget->hasInt256() ||
17949        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17950     return SDValue();
17951
17952   SDValue Amt = N->getOperand(1);
17953   SDLoc DL(N);
17954   if (isSplatVector(Amt.getNode())) {
17955     SDValue SclrAmt = Amt->getOperand(0);
17956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17957       APInt ShiftAmt = C->getAPIntValue();
17958       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17959
17960       // SSE2/AVX2 logical shifts always return a vector of 0s
17961       // if the shift amount is bigger than or equal to
17962       // the element size. The constant shift amount will be
17963       // encoded as a 8-bit immediate.
17964       if (ShiftAmt.trunc(8).uge(MaxAmount))
17965         return getZeroVector(VT, Subtarget, DAG, DL);
17966     }
17967   }
17968
17969   return SDValue();
17970 }
17971
17972 /// PerformShiftCombine - Combine shifts.
17973 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17974                                    TargetLowering::DAGCombinerInfo &DCI,
17975                                    const X86Subtarget *Subtarget) {
17976   if (N->getOpcode() == ISD::SHL) {
17977     SDValue V = PerformSHLCombine(N, DAG);
17978     if (V.getNode()) return V;
17979   }
17980
17981   if (N->getOpcode() != ISD::SRA) {
17982     // Try to fold this logical shift into a zero vector.
17983     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17984     if (V.getNode()) return V;
17985   }
17986
17987   return SDValue();
17988 }
17989
17990 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17991 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17992 // and friends.  Likewise for OR -> CMPNEQSS.
17993 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17994                             TargetLowering::DAGCombinerInfo &DCI,
17995                             const X86Subtarget *Subtarget) {
17996   unsigned opcode;
17997
17998   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17999   // we're requiring SSE2 for both.
18000   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18001     SDValue N0 = N->getOperand(0);
18002     SDValue N1 = N->getOperand(1);
18003     SDValue CMP0 = N0->getOperand(1);
18004     SDValue CMP1 = N1->getOperand(1);
18005     SDLoc DL(N);
18006
18007     // The SETCCs should both refer to the same CMP.
18008     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18009       return SDValue();
18010
18011     SDValue CMP00 = CMP0->getOperand(0);
18012     SDValue CMP01 = CMP0->getOperand(1);
18013     EVT     VT    = CMP00.getValueType();
18014
18015     if (VT == MVT::f32 || VT == MVT::f64) {
18016       bool ExpectingFlags = false;
18017       // Check for any users that want flags:
18018       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18019            !ExpectingFlags && UI != UE; ++UI)
18020         switch (UI->getOpcode()) {
18021         default:
18022         case ISD::BR_CC:
18023         case ISD::BRCOND:
18024         case ISD::SELECT:
18025           ExpectingFlags = true;
18026           break;
18027         case ISD::CopyToReg:
18028         case ISD::SIGN_EXTEND:
18029         case ISD::ZERO_EXTEND:
18030         case ISD::ANY_EXTEND:
18031           break;
18032         }
18033
18034       if (!ExpectingFlags) {
18035         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18036         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18037
18038         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18039           X86::CondCode tmp = cc0;
18040           cc0 = cc1;
18041           cc1 = tmp;
18042         }
18043
18044         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18045             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18046           // FIXME: need symbolic constants for these magic numbers.
18047           // See X86ATTInstPrinter.cpp:printSSECC().
18048           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18049           if (Subtarget->hasAVX512()) {
18050             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18051                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18052             if (N->getValueType(0) != MVT::i1)
18053               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18054                                  FSetCC);
18055             return FSetCC;
18056           }
18057           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18058                                               CMP00.getValueType(), CMP00, CMP01,
18059                                               DAG.getConstant(x86cc, MVT::i8));
18060
18061           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18062           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18063
18064           if (is64BitFP && !Subtarget->is64Bit()) {
18065             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18066             // 64-bit integer, since that's not a legal type. Since
18067             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18068             // bits, but can do this little dance to extract the lowest 32 bits
18069             // and work with those going forward.
18070             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18071                                            OnesOrZeroesF);
18072             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18073                                            Vector64);
18074             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18075                                         Vector32, DAG.getIntPtrConstant(0));
18076             IntVT = MVT::i32;
18077           }
18078
18079           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18080           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18081                                       DAG.getConstant(1, IntVT));
18082           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18083           return OneBitOfTruth;
18084         }
18085       }
18086     }
18087   }
18088   return SDValue();
18089 }
18090
18091 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18092 /// so it can be folded inside ANDNP.
18093 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18094   EVT VT = N->getValueType(0);
18095
18096   // Match direct AllOnes for 128 and 256-bit vectors
18097   if (ISD::isBuildVectorAllOnes(N))
18098     return true;
18099
18100   // Look through a bit convert.
18101   if (N->getOpcode() == ISD::BITCAST)
18102     N = N->getOperand(0).getNode();
18103
18104   // Sometimes the operand may come from a insert_subvector building a 256-bit
18105   // allones vector
18106   if (VT.is256BitVector() &&
18107       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18108     SDValue V1 = N->getOperand(0);
18109     SDValue V2 = N->getOperand(1);
18110
18111     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18112         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18113         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18114         ISD::isBuildVectorAllOnes(V2.getNode()))
18115       return true;
18116   }
18117
18118   return false;
18119 }
18120
18121 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18122 // register. In most cases we actually compare or select YMM-sized registers
18123 // and mixing the two types creates horrible code. This method optimizes
18124 // some of the transition sequences.
18125 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18126                                  TargetLowering::DAGCombinerInfo &DCI,
18127                                  const X86Subtarget *Subtarget) {
18128   EVT VT = N->getValueType(0);
18129   if (!VT.is256BitVector())
18130     return SDValue();
18131
18132   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18133           N->getOpcode() == ISD::ZERO_EXTEND ||
18134           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18135
18136   SDValue Narrow = N->getOperand(0);
18137   EVT NarrowVT = Narrow->getValueType(0);
18138   if (!NarrowVT.is128BitVector())
18139     return SDValue();
18140
18141   if (Narrow->getOpcode() != ISD::XOR &&
18142       Narrow->getOpcode() != ISD::AND &&
18143       Narrow->getOpcode() != ISD::OR)
18144     return SDValue();
18145
18146   SDValue N0  = Narrow->getOperand(0);
18147   SDValue N1  = Narrow->getOperand(1);
18148   SDLoc DL(Narrow);
18149
18150   // The Left side has to be a trunc.
18151   if (N0.getOpcode() != ISD::TRUNCATE)
18152     return SDValue();
18153
18154   // The type of the truncated inputs.
18155   EVT WideVT = N0->getOperand(0)->getValueType(0);
18156   if (WideVT != VT)
18157     return SDValue();
18158
18159   // The right side has to be a 'trunc' or a constant vector.
18160   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18161   bool RHSConst = (isSplatVector(N1.getNode()) &&
18162                    isa<ConstantSDNode>(N1->getOperand(0)));
18163   if (!RHSTrunc && !RHSConst)
18164     return SDValue();
18165
18166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18167
18168   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18169     return SDValue();
18170
18171   // Set N0 and N1 to hold the inputs to the new wide operation.
18172   N0 = N0->getOperand(0);
18173   if (RHSConst) {
18174     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18175                      N1->getOperand(0));
18176     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18177     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18178   } else if (RHSTrunc) {
18179     N1 = N1->getOperand(0);
18180   }
18181
18182   // Generate the wide operation.
18183   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18184   unsigned Opcode = N->getOpcode();
18185   switch (Opcode) {
18186   case ISD::ANY_EXTEND:
18187     return Op;
18188   case ISD::ZERO_EXTEND: {
18189     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18190     APInt Mask = APInt::getAllOnesValue(InBits);
18191     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18192     return DAG.getNode(ISD::AND, DL, VT,
18193                        Op, DAG.getConstant(Mask, VT));
18194   }
18195   case ISD::SIGN_EXTEND:
18196     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18197                        Op, DAG.getValueType(NarrowVT));
18198   default:
18199     llvm_unreachable("Unexpected opcode");
18200   }
18201 }
18202
18203 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18204                                  TargetLowering::DAGCombinerInfo &DCI,
18205                                  const X86Subtarget *Subtarget) {
18206   EVT VT = N->getValueType(0);
18207   if (DCI.isBeforeLegalizeOps())
18208     return SDValue();
18209
18210   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18211   if (R.getNode())
18212     return R;
18213
18214   // Create BEXTR and BZHI instructions
18215   // BZHI is X & ((1 << Y) - 1)
18216   // BEXTR is ((X >> imm) & (2**size-1))
18217   if (VT == MVT::i32 || VT == MVT::i64) {
18218     SDValue N0 = N->getOperand(0);
18219     SDValue N1 = N->getOperand(1);
18220     SDLoc DL(N);
18221
18222     if (Subtarget->hasBMI2()) {
18223       // Check for (and (add (shl 1, Y), -1), X)
18224       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18225         SDValue N00 = N0.getOperand(0);
18226         if (N00.getOpcode() == ISD::SHL) {
18227           SDValue N001 = N00.getOperand(1);
18228           assert(N001.getValueType() == MVT::i8 && "unexpected type");
18229           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18230           if (C && C->getZExtValue() == 1)
18231             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18232         }
18233       }
18234
18235       // Check for (and X, (add (shl 1, Y), -1))
18236       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18237         SDValue N10 = N1.getOperand(0);
18238         if (N10.getOpcode() == ISD::SHL) {
18239           SDValue N101 = N10.getOperand(1);
18240           assert(N101.getValueType() == MVT::i8 && "unexpected type");
18241           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18242           if (C && C->getZExtValue() == 1)
18243             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18244         }
18245       }
18246     }
18247
18248     // Check for BEXTR.
18249     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18250         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18251       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18252       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18253       if (MaskNode && ShiftNode) {
18254         uint64_t Mask = MaskNode->getZExtValue();
18255         uint64_t Shift = ShiftNode->getZExtValue();
18256         if (isMask_64(Mask)) {
18257           uint64_t MaskSize = CountPopulation_64(Mask);
18258           if (Shift + MaskSize <= VT.getSizeInBits())
18259             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18260                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18261         }
18262       }
18263     } // BEXTR
18264
18265     return SDValue();
18266   }
18267
18268   // Want to form ANDNP nodes:
18269   // 1) In the hopes of then easily combining them with OR and AND nodes
18270   //    to form PBLEND/PSIGN.
18271   // 2) To match ANDN packed intrinsics
18272   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18273     return SDValue();
18274
18275   SDValue N0 = N->getOperand(0);
18276   SDValue N1 = N->getOperand(1);
18277   SDLoc DL(N);
18278
18279   // Check LHS for vnot
18280   if (N0.getOpcode() == ISD::XOR &&
18281       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18282       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18283     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18284
18285   // Check RHS for vnot
18286   if (N1.getOpcode() == ISD::XOR &&
18287       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18288       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18289     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18290
18291   return SDValue();
18292 }
18293
18294 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18295                                 TargetLowering::DAGCombinerInfo &DCI,
18296                                 const X86Subtarget *Subtarget) {
18297   if (DCI.isBeforeLegalizeOps())
18298     return SDValue();
18299
18300   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18301   if (R.getNode())
18302     return R;
18303
18304   SDValue N0 = N->getOperand(0);
18305   SDValue N1 = N->getOperand(1);
18306   EVT VT = N->getValueType(0);
18307
18308   // look for psign/blend
18309   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18310     if (!Subtarget->hasSSSE3() ||
18311         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18312       return SDValue();
18313
18314     // Canonicalize pandn to RHS
18315     if (N0.getOpcode() == X86ISD::ANDNP)
18316       std::swap(N0, N1);
18317     // or (and (m, y), (pandn m, x))
18318     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18319       SDValue Mask = N1.getOperand(0);
18320       SDValue X    = N1.getOperand(1);
18321       SDValue Y;
18322       if (N0.getOperand(0) == Mask)
18323         Y = N0.getOperand(1);
18324       if (N0.getOperand(1) == Mask)
18325         Y = N0.getOperand(0);
18326
18327       // Check to see if the mask appeared in both the AND and ANDNP and
18328       if (!Y.getNode())
18329         return SDValue();
18330
18331       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18332       // Look through mask bitcast.
18333       if (Mask.getOpcode() == ISD::BITCAST)
18334         Mask = Mask.getOperand(0);
18335       if (X.getOpcode() == ISD::BITCAST)
18336         X = X.getOperand(0);
18337       if (Y.getOpcode() == ISD::BITCAST)
18338         Y = Y.getOperand(0);
18339
18340       EVT MaskVT = Mask.getValueType();
18341
18342       // Validate that the Mask operand is a vector sra node.
18343       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18344       // there is no psrai.b
18345       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18346       unsigned SraAmt = ~0;
18347       if (Mask.getOpcode() == ISD::SRA) {
18348         SDValue Amt = Mask.getOperand(1);
18349         if (isSplatVector(Amt.getNode())) {
18350           SDValue SclrAmt = Amt->getOperand(0);
18351           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18352             SraAmt = C->getZExtValue();
18353         }
18354       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18355         SDValue SraC = Mask.getOperand(1);
18356         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18357       }
18358       if ((SraAmt + 1) != EltBits)
18359         return SDValue();
18360
18361       SDLoc DL(N);
18362
18363       // Now we know we at least have a plendvb with the mask val.  See if
18364       // we can form a psignb/w/d.
18365       // psign = x.type == y.type == mask.type && y = sub(0, x);
18366       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18367           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18368           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18369         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18370                "Unsupported VT for PSIGN");
18371         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18372         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18373       }
18374       // PBLENDVB only available on SSE 4.1
18375       if (!Subtarget->hasSSE41())
18376         return SDValue();
18377
18378       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18379
18380       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18381       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18382       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18383       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18384       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18385     }
18386   }
18387
18388   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18389     return SDValue();
18390
18391   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18392   MachineFunction &MF = DAG.getMachineFunction();
18393   bool OptForSize = MF.getFunction()->getAttributes().
18394     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18395
18396   // SHLD/SHRD instructions have lower register pressure, but on some
18397   // platforms they have higher latency than the equivalent
18398   // series of shifts/or that would otherwise be generated.
18399   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18400   // have higher latencies and we are not optimizing for size.
18401   if (!OptForSize && Subtarget->isSHLDSlow())
18402     return SDValue();
18403
18404   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18405     std::swap(N0, N1);
18406   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18407     return SDValue();
18408   if (!N0.hasOneUse() || !N1.hasOneUse())
18409     return SDValue();
18410
18411   SDValue ShAmt0 = N0.getOperand(1);
18412   if (ShAmt0.getValueType() != MVT::i8)
18413     return SDValue();
18414   SDValue ShAmt1 = N1.getOperand(1);
18415   if (ShAmt1.getValueType() != MVT::i8)
18416     return SDValue();
18417   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18418     ShAmt0 = ShAmt0.getOperand(0);
18419   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18420     ShAmt1 = ShAmt1.getOperand(0);
18421
18422   SDLoc DL(N);
18423   unsigned Opc = X86ISD::SHLD;
18424   SDValue Op0 = N0.getOperand(0);
18425   SDValue Op1 = N1.getOperand(0);
18426   if (ShAmt0.getOpcode() == ISD::SUB) {
18427     Opc = X86ISD::SHRD;
18428     std::swap(Op0, Op1);
18429     std::swap(ShAmt0, ShAmt1);
18430   }
18431
18432   unsigned Bits = VT.getSizeInBits();
18433   if (ShAmt1.getOpcode() == ISD::SUB) {
18434     SDValue Sum = ShAmt1.getOperand(0);
18435     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18436       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18437       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18438         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18439       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18440         return DAG.getNode(Opc, DL, VT,
18441                            Op0, Op1,
18442                            DAG.getNode(ISD::TRUNCATE, DL,
18443                                        MVT::i8, ShAmt0));
18444     }
18445   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18446     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18447     if (ShAmt0C &&
18448         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18449       return DAG.getNode(Opc, DL, VT,
18450                          N0.getOperand(0), N1.getOperand(0),
18451                          DAG.getNode(ISD::TRUNCATE, DL,
18452                                        MVT::i8, ShAmt0));
18453   }
18454
18455   return SDValue();
18456 }
18457
18458 // Generate NEG and CMOV for integer abs.
18459 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18460   EVT VT = N->getValueType(0);
18461
18462   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18463   // 8-bit integer abs to NEG and CMOV.
18464   if (VT.isInteger() && VT.getSizeInBits() == 8)
18465     return SDValue();
18466
18467   SDValue N0 = N->getOperand(0);
18468   SDValue N1 = N->getOperand(1);
18469   SDLoc DL(N);
18470
18471   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18472   // and change it to SUB and CMOV.
18473   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18474       N0.getOpcode() == ISD::ADD &&
18475       N0.getOperand(1) == N1 &&
18476       N1.getOpcode() == ISD::SRA &&
18477       N1.getOperand(0) == N0.getOperand(0))
18478     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18479       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18480         // Generate SUB & CMOV.
18481         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18482                                   DAG.getConstant(0, VT), N0.getOperand(0));
18483
18484         SDValue Ops[] = { N0.getOperand(0), Neg,
18485                           DAG.getConstant(X86::COND_GE, MVT::i8),
18486                           SDValue(Neg.getNode(), 1) };
18487         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18488                            Ops, array_lengthof(Ops));
18489       }
18490   return SDValue();
18491 }
18492
18493 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18494 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18495                                  TargetLowering::DAGCombinerInfo &DCI,
18496                                  const X86Subtarget *Subtarget) {
18497   if (DCI.isBeforeLegalizeOps())
18498     return SDValue();
18499
18500   if (Subtarget->hasCMov()) {
18501     SDValue RV = performIntegerAbsCombine(N, DAG);
18502     if (RV.getNode())
18503       return RV;
18504   }
18505
18506   return SDValue();
18507 }
18508
18509 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18510 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18511                                   TargetLowering::DAGCombinerInfo &DCI,
18512                                   const X86Subtarget *Subtarget) {
18513   LoadSDNode *Ld = cast<LoadSDNode>(N);
18514   EVT RegVT = Ld->getValueType(0);
18515   EVT MemVT = Ld->getMemoryVT();
18516   SDLoc dl(Ld);
18517   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18518   unsigned RegSz = RegVT.getSizeInBits();
18519
18520   // On Sandybridge unaligned 256bit loads are inefficient.
18521   ISD::LoadExtType Ext = Ld->getExtensionType();
18522   unsigned Alignment = Ld->getAlignment();
18523   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18524   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18525       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18526     unsigned NumElems = RegVT.getVectorNumElements();
18527     if (NumElems < 2)
18528       return SDValue();
18529
18530     SDValue Ptr = Ld->getBasePtr();
18531     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18532
18533     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18534                                   NumElems/2);
18535     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18536                                 Ld->getPointerInfo(), Ld->isVolatile(),
18537                                 Ld->isNonTemporal(), Ld->isInvariant(),
18538                                 Alignment);
18539     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18540     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18541                                 Ld->getPointerInfo(), Ld->isVolatile(),
18542                                 Ld->isNonTemporal(), Ld->isInvariant(),
18543                                 std::min(16U, Alignment));
18544     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18545                              Load1.getValue(1),
18546                              Load2.getValue(1));
18547
18548     SDValue NewVec = DAG.getUNDEF(RegVT);
18549     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18550     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18551     return DCI.CombineTo(N, NewVec, TF, true);
18552   }
18553
18554   // If this is a vector EXT Load then attempt to optimize it using a
18555   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18556   // expansion is still better than scalar code.
18557   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18558   // emit a shuffle and a arithmetic shift.
18559   // TODO: It is possible to support ZExt by zeroing the undef values
18560   // during the shuffle phase or after the shuffle.
18561   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18562       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18563     assert(MemVT != RegVT && "Cannot extend to the same type");
18564     assert(MemVT.isVector() && "Must load a vector from memory");
18565
18566     unsigned NumElems = RegVT.getVectorNumElements();
18567     unsigned MemSz = MemVT.getSizeInBits();
18568     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18569
18570     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18571       return SDValue();
18572
18573     // All sizes must be a power of two.
18574     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18575       return SDValue();
18576
18577     // Attempt to load the original value using scalar loads.
18578     // Find the largest scalar type that divides the total loaded size.
18579     MVT SclrLoadTy = MVT::i8;
18580     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18581          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18582       MVT Tp = (MVT::SimpleValueType)tp;
18583       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18584         SclrLoadTy = Tp;
18585       }
18586     }
18587
18588     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18589     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18590         (64 <= MemSz))
18591       SclrLoadTy = MVT::f64;
18592
18593     // Calculate the number of scalar loads that we need to perform
18594     // in order to load our vector from memory.
18595     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18596     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18597       return SDValue();
18598
18599     unsigned loadRegZize = RegSz;
18600     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18601       loadRegZize /= 2;
18602
18603     // Represent our vector as a sequence of elements which are the
18604     // largest scalar that we can load.
18605     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18606       loadRegZize/SclrLoadTy.getSizeInBits());
18607
18608     // Represent the data using the same element type that is stored in
18609     // memory. In practice, we ''widen'' MemVT.
18610     EVT WideVecVT =
18611           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18612                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18613
18614     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18615       "Invalid vector type");
18616
18617     // We can't shuffle using an illegal type.
18618     if (!TLI.isTypeLegal(WideVecVT))
18619       return SDValue();
18620
18621     SmallVector<SDValue, 8> Chains;
18622     SDValue Ptr = Ld->getBasePtr();
18623     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18624                                         TLI.getPointerTy());
18625     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18626
18627     for (unsigned i = 0; i < NumLoads; ++i) {
18628       // Perform a single load.
18629       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18630                                        Ptr, Ld->getPointerInfo(),
18631                                        Ld->isVolatile(), Ld->isNonTemporal(),
18632                                        Ld->isInvariant(), Ld->getAlignment());
18633       Chains.push_back(ScalarLoad.getValue(1));
18634       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18635       // another round of DAGCombining.
18636       if (i == 0)
18637         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18638       else
18639         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18640                           ScalarLoad, DAG.getIntPtrConstant(i));
18641
18642       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18643     }
18644
18645     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18646                                Chains.size());
18647
18648     // Bitcast the loaded value to a vector of the original element type, in
18649     // the size of the target vector type.
18650     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18651     unsigned SizeRatio = RegSz/MemSz;
18652
18653     if (Ext == ISD::SEXTLOAD) {
18654       // If we have SSE4.1 we can directly emit a VSEXT node.
18655       if (Subtarget->hasSSE41()) {
18656         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18657         return DCI.CombineTo(N, Sext, TF, true);
18658       }
18659
18660       // Otherwise we'll shuffle the small elements in the high bits of the
18661       // larger type and perform an arithmetic shift. If the shift is not legal
18662       // it's better to scalarize.
18663       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18664         return SDValue();
18665
18666       // Redistribute the loaded elements into the different locations.
18667       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18668       for (unsigned i = 0; i != NumElems; ++i)
18669         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18670
18671       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18672                                            DAG.getUNDEF(WideVecVT),
18673                                            &ShuffleVec[0]);
18674
18675       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18676
18677       // Build the arithmetic shift.
18678       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18679                      MemVT.getVectorElementType().getSizeInBits();
18680       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18681                           DAG.getConstant(Amt, RegVT));
18682
18683       return DCI.CombineTo(N, Shuff, TF, true);
18684     }
18685
18686     // Redistribute the loaded elements into the different locations.
18687     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18688     for (unsigned i = 0; i != NumElems; ++i)
18689       ShuffleVec[i*SizeRatio] = i;
18690
18691     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18692                                          DAG.getUNDEF(WideVecVT),
18693                                          &ShuffleVec[0]);
18694
18695     // Bitcast to the requested type.
18696     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18697     // Replace the original load with the new sequence
18698     // and return the new chain.
18699     return DCI.CombineTo(N, Shuff, TF, true);
18700   }
18701
18702   return SDValue();
18703 }
18704
18705 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18706 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18707                                    const X86Subtarget *Subtarget) {
18708   StoreSDNode *St = cast<StoreSDNode>(N);
18709   EVT VT = St->getValue().getValueType();
18710   EVT StVT = St->getMemoryVT();
18711   SDLoc dl(St);
18712   SDValue StoredVal = St->getOperand(1);
18713   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18714
18715   // If we are saving a concatenation of two XMM registers, perform two stores.
18716   // On Sandy Bridge, 256-bit memory operations are executed by two
18717   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18718   // memory  operation.
18719   unsigned Alignment = St->getAlignment();
18720   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18721   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18722       StVT == VT && !IsAligned) {
18723     unsigned NumElems = VT.getVectorNumElements();
18724     if (NumElems < 2)
18725       return SDValue();
18726
18727     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18728     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18729
18730     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18731     SDValue Ptr0 = St->getBasePtr();
18732     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18733
18734     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18735                                 St->getPointerInfo(), St->isVolatile(),
18736                                 St->isNonTemporal(), Alignment);
18737     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18738                                 St->getPointerInfo(), St->isVolatile(),
18739                                 St->isNonTemporal(),
18740                                 std::min(16U, Alignment));
18741     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18742   }
18743
18744   // Optimize trunc store (of multiple scalars) to shuffle and store.
18745   // First, pack all of the elements in one place. Next, store to memory
18746   // in fewer chunks.
18747   if (St->isTruncatingStore() && VT.isVector()) {
18748     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18749     unsigned NumElems = VT.getVectorNumElements();
18750     assert(StVT != VT && "Cannot truncate to the same type");
18751     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18752     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18753
18754     // From, To sizes and ElemCount must be pow of two
18755     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18756     // We are going to use the original vector elt for storing.
18757     // Accumulated smaller vector elements must be a multiple of the store size.
18758     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18759
18760     unsigned SizeRatio  = FromSz / ToSz;
18761
18762     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18763
18764     // Create a type on which we perform the shuffle
18765     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18766             StVT.getScalarType(), NumElems*SizeRatio);
18767
18768     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18769
18770     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18771     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18772     for (unsigned i = 0; i != NumElems; ++i)
18773       ShuffleVec[i] = i * SizeRatio;
18774
18775     // Can't shuffle using an illegal type.
18776     if (!TLI.isTypeLegal(WideVecVT))
18777       return SDValue();
18778
18779     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18780                                          DAG.getUNDEF(WideVecVT),
18781                                          &ShuffleVec[0]);
18782     // At this point all of the data is stored at the bottom of the
18783     // register. We now need to save it to mem.
18784
18785     // Find the largest store unit
18786     MVT StoreType = MVT::i8;
18787     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18788          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18789       MVT Tp = (MVT::SimpleValueType)tp;
18790       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18791         StoreType = Tp;
18792     }
18793
18794     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18795     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18796         (64 <= NumElems * ToSz))
18797       StoreType = MVT::f64;
18798
18799     // Bitcast the original vector into a vector of store-size units
18800     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18801             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18802     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18803     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18804     SmallVector<SDValue, 8> Chains;
18805     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18806                                         TLI.getPointerTy());
18807     SDValue Ptr = St->getBasePtr();
18808
18809     // Perform one or more big stores into memory.
18810     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18811       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18812                                    StoreType, ShuffWide,
18813                                    DAG.getIntPtrConstant(i));
18814       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18815                                 St->getPointerInfo(), St->isVolatile(),
18816                                 St->isNonTemporal(), St->getAlignment());
18817       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18818       Chains.push_back(Ch);
18819     }
18820
18821     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18822                                Chains.size());
18823   }
18824
18825   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18826   // the FP state in cases where an emms may be missing.
18827   // A preferable solution to the general problem is to figure out the right
18828   // places to insert EMMS.  This qualifies as a quick hack.
18829
18830   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18831   if (VT.getSizeInBits() != 64)
18832     return SDValue();
18833
18834   const Function *F = DAG.getMachineFunction().getFunction();
18835   bool NoImplicitFloatOps = F->getAttributes().
18836     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18837   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18838                      && Subtarget->hasSSE2();
18839   if ((VT.isVector() ||
18840        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18841       isa<LoadSDNode>(St->getValue()) &&
18842       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18843       St->getChain().hasOneUse() && !St->isVolatile()) {
18844     SDNode* LdVal = St->getValue().getNode();
18845     LoadSDNode *Ld = 0;
18846     int TokenFactorIndex = -1;
18847     SmallVector<SDValue, 8> Ops;
18848     SDNode* ChainVal = St->getChain().getNode();
18849     // Must be a store of a load.  We currently handle two cases:  the load
18850     // is a direct child, and it's under an intervening TokenFactor.  It is
18851     // possible to dig deeper under nested TokenFactors.
18852     if (ChainVal == LdVal)
18853       Ld = cast<LoadSDNode>(St->getChain());
18854     else if (St->getValue().hasOneUse() &&
18855              ChainVal->getOpcode() == ISD::TokenFactor) {
18856       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18857         if (ChainVal->getOperand(i).getNode() == LdVal) {
18858           TokenFactorIndex = i;
18859           Ld = cast<LoadSDNode>(St->getValue());
18860         } else
18861           Ops.push_back(ChainVal->getOperand(i));
18862       }
18863     }
18864
18865     if (!Ld || !ISD::isNormalLoad(Ld))
18866       return SDValue();
18867
18868     // If this is not the MMX case, i.e. we are just turning i64 load/store
18869     // into f64 load/store, avoid the transformation if there are multiple
18870     // uses of the loaded value.
18871     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18872       return SDValue();
18873
18874     SDLoc LdDL(Ld);
18875     SDLoc StDL(N);
18876     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18877     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18878     // pair instead.
18879     if (Subtarget->is64Bit() || F64IsLegal) {
18880       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18881       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18882                                   Ld->getPointerInfo(), Ld->isVolatile(),
18883                                   Ld->isNonTemporal(), Ld->isInvariant(),
18884                                   Ld->getAlignment());
18885       SDValue NewChain = NewLd.getValue(1);
18886       if (TokenFactorIndex != -1) {
18887         Ops.push_back(NewChain);
18888         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18889                                Ops.size());
18890       }
18891       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18892                           St->getPointerInfo(),
18893                           St->isVolatile(), St->isNonTemporal(),
18894                           St->getAlignment());
18895     }
18896
18897     // Otherwise, lower to two pairs of 32-bit loads / stores.
18898     SDValue LoAddr = Ld->getBasePtr();
18899     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18900                                  DAG.getConstant(4, MVT::i32));
18901
18902     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18903                                Ld->getPointerInfo(),
18904                                Ld->isVolatile(), Ld->isNonTemporal(),
18905                                Ld->isInvariant(), Ld->getAlignment());
18906     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18907                                Ld->getPointerInfo().getWithOffset(4),
18908                                Ld->isVolatile(), Ld->isNonTemporal(),
18909                                Ld->isInvariant(),
18910                                MinAlign(Ld->getAlignment(), 4));
18911
18912     SDValue NewChain = LoLd.getValue(1);
18913     if (TokenFactorIndex != -1) {
18914       Ops.push_back(LoLd);
18915       Ops.push_back(HiLd);
18916       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18917                              Ops.size());
18918     }
18919
18920     LoAddr = St->getBasePtr();
18921     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18922                          DAG.getConstant(4, MVT::i32));
18923
18924     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18925                                 St->getPointerInfo(),
18926                                 St->isVolatile(), St->isNonTemporal(),
18927                                 St->getAlignment());
18928     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18929                                 St->getPointerInfo().getWithOffset(4),
18930                                 St->isVolatile(),
18931                                 St->isNonTemporal(),
18932                                 MinAlign(St->getAlignment(), 4));
18933     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18934   }
18935   return SDValue();
18936 }
18937
18938 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18939 /// and return the operands for the horizontal operation in LHS and RHS.  A
18940 /// horizontal operation performs the binary operation on successive elements
18941 /// of its first operand, then on successive elements of its second operand,
18942 /// returning the resulting values in a vector.  For example, if
18943 ///   A = < float a0, float a1, float a2, float a3 >
18944 /// and
18945 ///   B = < float b0, float b1, float b2, float b3 >
18946 /// then the result of doing a horizontal operation on A and B is
18947 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18948 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18949 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18950 /// set to A, RHS to B, and the routine returns 'true'.
18951 /// Note that the binary operation should have the property that if one of the
18952 /// operands is UNDEF then the result is UNDEF.
18953 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18954   // Look for the following pattern: if
18955   //   A = < float a0, float a1, float a2, float a3 >
18956   //   B = < float b0, float b1, float b2, float b3 >
18957   // and
18958   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18959   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18960   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18961   // which is A horizontal-op B.
18962
18963   // At least one of the operands should be a vector shuffle.
18964   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18965       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18966     return false;
18967
18968   MVT VT = LHS.getSimpleValueType();
18969
18970   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18971          "Unsupported vector type for horizontal add/sub");
18972
18973   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18974   // operate independently on 128-bit lanes.
18975   unsigned NumElts = VT.getVectorNumElements();
18976   unsigned NumLanes = VT.getSizeInBits()/128;
18977   unsigned NumLaneElts = NumElts / NumLanes;
18978   assert((NumLaneElts % 2 == 0) &&
18979          "Vector type should have an even number of elements in each lane");
18980   unsigned HalfLaneElts = NumLaneElts/2;
18981
18982   // View LHS in the form
18983   //   LHS = VECTOR_SHUFFLE A, B, LMask
18984   // If LHS is not a shuffle then pretend it is the shuffle
18985   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18986   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18987   // type VT.
18988   SDValue A, B;
18989   SmallVector<int, 16> LMask(NumElts);
18990   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18991     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18992       A = LHS.getOperand(0);
18993     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18994       B = LHS.getOperand(1);
18995     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18996     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18997   } else {
18998     if (LHS.getOpcode() != ISD::UNDEF)
18999       A = LHS;
19000     for (unsigned i = 0; i != NumElts; ++i)
19001       LMask[i] = i;
19002   }
19003
19004   // Likewise, view RHS in the form
19005   //   RHS = VECTOR_SHUFFLE C, D, RMask
19006   SDValue C, D;
19007   SmallVector<int, 16> RMask(NumElts);
19008   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19009     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19010       C = RHS.getOperand(0);
19011     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19012       D = RHS.getOperand(1);
19013     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19014     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19015   } else {
19016     if (RHS.getOpcode() != ISD::UNDEF)
19017       C = RHS;
19018     for (unsigned i = 0; i != NumElts; ++i)
19019       RMask[i] = i;
19020   }
19021
19022   // Check that the shuffles are both shuffling the same vectors.
19023   if (!(A == C && B == D) && !(A == D && B == C))
19024     return false;
19025
19026   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19027   if (!A.getNode() && !B.getNode())
19028     return false;
19029
19030   // If A and B occur in reverse order in RHS, then "swap" them (which means
19031   // rewriting the mask).
19032   if (A != C)
19033     CommuteVectorShuffleMask(RMask, NumElts);
19034
19035   // At this point LHS and RHS are equivalent to
19036   //   LHS = VECTOR_SHUFFLE A, B, LMask
19037   //   RHS = VECTOR_SHUFFLE A, B, RMask
19038   // Check that the masks correspond to performing a horizontal operation.
19039   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19040     for (unsigned i = 0; i != NumLaneElts; ++i) {
19041       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19042
19043       // Ignore any UNDEF components.
19044       if (LIdx < 0 || RIdx < 0 ||
19045           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19046           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19047         continue;
19048
19049       // Check that successive elements are being operated on.  If not, this is
19050       // not a horizontal operation.
19051       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19052       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19053       if (!(LIdx == Index && RIdx == Index + 1) &&
19054           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19055         return false;
19056     }
19057   }
19058
19059   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19060   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19061   return true;
19062 }
19063
19064 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19065 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19066                                   const X86Subtarget *Subtarget) {
19067   EVT VT = N->getValueType(0);
19068   SDValue LHS = N->getOperand(0);
19069   SDValue RHS = N->getOperand(1);
19070
19071   // Try to synthesize horizontal adds from adds of shuffles.
19072   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19073        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19074       isHorizontalBinOp(LHS, RHS, true))
19075     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19076   return SDValue();
19077 }
19078
19079 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19080 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19081                                   const X86Subtarget *Subtarget) {
19082   EVT VT = N->getValueType(0);
19083   SDValue LHS = N->getOperand(0);
19084   SDValue RHS = N->getOperand(1);
19085
19086   // Try to synthesize horizontal subs from subs of shuffles.
19087   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19088        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19089       isHorizontalBinOp(LHS, RHS, false))
19090     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19091   return SDValue();
19092 }
19093
19094 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19095 /// X86ISD::FXOR nodes.
19096 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19097   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19098   // F[X]OR(0.0, x) -> x
19099   // F[X]OR(x, 0.0) -> x
19100   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19101     if (C->getValueAPF().isPosZero())
19102       return N->getOperand(1);
19103   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19104     if (C->getValueAPF().isPosZero())
19105       return N->getOperand(0);
19106   return SDValue();
19107 }
19108
19109 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19110 /// X86ISD::FMAX nodes.
19111 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19112   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19113
19114   // Only perform optimizations if UnsafeMath is used.
19115   if (!DAG.getTarget().Options.UnsafeFPMath)
19116     return SDValue();
19117
19118   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19119   // into FMINC and FMAXC, which are Commutative operations.
19120   unsigned NewOp = 0;
19121   switch (N->getOpcode()) {
19122     default: llvm_unreachable("unknown opcode");
19123     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19124     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19125   }
19126
19127   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19128                      N->getOperand(0), N->getOperand(1));
19129 }
19130
19131 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19132 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19133   // FAND(0.0, x) -> 0.0
19134   // FAND(x, 0.0) -> 0.0
19135   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19136     if (C->getValueAPF().isPosZero())
19137       return N->getOperand(0);
19138   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19139     if (C->getValueAPF().isPosZero())
19140       return N->getOperand(1);
19141   return SDValue();
19142 }
19143
19144 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19145 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19146   // FANDN(x, 0.0) -> 0.0
19147   // FANDN(0.0, x) -> x
19148   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19149     if (C->getValueAPF().isPosZero())
19150       return N->getOperand(1);
19151   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19152     if (C->getValueAPF().isPosZero())
19153       return N->getOperand(1);
19154   return SDValue();
19155 }
19156
19157 static SDValue PerformBTCombine(SDNode *N,
19158                                 SelectionDAG &DAG,
19159                                 TargetLowering::DAGCombinerInfo &DCI) {
19160   // BT ignores high bits in the bit index operand.
19161   SDValue Op1 = N->getOperand(1);
19162   if (Op1.hasOneUse()) {
19163     unsigned BitWidth = Op1.getValueSizeInBits();
19164     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19165     APInt KnownZero, KnownOne;
19166     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19167                                           !DCI.isBeforeLegalizeOps());
19168     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19169     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19170         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19171       DCI.CommitTargetLoweringOpt(TLO);
19172   }
19173   return SDValue();
19174 }
19175
19176 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19177   SDValue Op = N->getOperand(0);
19178   if (Op.getOpcode() == ISD::BITCAST)
19179     Op = Op.getOperand(0);
19180   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19181   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19182       VT.getVectorElementType().getSizeInBits() ==
19183       OpVT.getVectorElementType().getSizeInBits()) {
19184     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19185   }
19186   return SDValue();
19187 }
19188
19189 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19190                                                const X86Subtarget *Subtarget) {
19191   EVT VT = N->getValueType(0);
19192   if (!VT.isVector())
19193     return SDValue();
19194
19195   SDValue N0 = N->getOperand(0);
19196   SDValue N1 = N->getOperand(1);
19197   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19198   SDLoc dl(N);
19199
19200   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19201   // both SSE and AVX2 since there is no sign-extended shift right
19202   // operation on a vector with 64-bit elements.
19203   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19204   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19205   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19206       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19207     SDValue N00 = N0.getOperand(0);
19208
19209     // EXTLOAD has a better solution on AVX2,
19210     // it may be replaced with X86ISD::VSEXT node.
19211     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19212       if (!ISD::isNormalLoad(N00.getNode()))
19213         return SDValue();
19214
19215     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19216         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19217                                   N00, N1);
19218       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19219     }
19220   }
19221   return SDValue();
19222 }
19223
19224 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19225                                   TargetLowering::DAGCombinerInfo &DCI,
19226                                   const X86Subtarget *Subtarget) {
19227   if (!DCI.isBeforeLegalizeOps())
19228     return SDValue();
19229
19230   if (!Subtarget->hasFp256())
19231     return SDValue();
19232
19233   EVT VT = N->getValueType(0);
19234   if (VT.isVector() && VT.getSizeInBits() == 256) {
19235     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19236     if (R.getNode())
19237       return R;
19238   }
19239
19240   return SDValue();
19241 }
19242
19243 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19244                                  const X86Subtarget* Subtarget) {
19245   SDLoc dl(N);
19246   EVT VT = N->getValueType(0);
19247
19248   // Let legalize expand this if it isn't a legal type yet.
19249   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19250     return SDValue();
19251
19252   EVT ScalarVT = VT.getScalarType();
19253   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19254       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19255     return SDValue();
19256
19257   SDValue A = N->getOperand(0);
19258   SDValue B = N->getOperand(1);
19259   SDValue C = N->getOperand(2);
19260
19261   bool NegA = (A.getOpcode() == ISD::FNEG);
19262   bool NegB = (B.getOpcode() == ISD::FNEG);
19263   bool NegC = (C.getOpcode() == ISD::FNEG);
19264
19265   // Negative multiplication when NegA xor NegB
19266   bool NegMul = (NegA != NegB);
19267   if (NegA)
19268     A = A.getOperand(0);
19269   if (NegB)
19270     B = B.getOperand(0);
19271   if (NegC)
19272     C = C.getOperand(0);
19273
19274   unsigned Opcode;
19275   if (!NegMul)
19276     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19277   else
19278     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19279
19280   return DAG.getNode(Opcode, dl, VT, A, B, C);
19281 }
19282
19283 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19284                                   TargetLowering::DAGCombinerInfo &DCI,
19285                                   const X86Subtarget *Subtarget) {
19286   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19287   //           (and (i32 x86isd::setcc_carry), 1)
19288   // This eliminates the zext. This transformation is necessary because
19289   // ISD::SETCC is always legalized to i8.
19290   SDLoc dl(N);
19291   SDValue N0 = N->getOperand(0);
19292   EVT VT = N->getValueType(0);
19293
19294   if (N0.getOpcode() == ISD::AND &&
19295       N0.hasOneUse() &&
19296       N0.getOperand(0).hasOneUse()) {
19297     SDValue N00 = N0.getOperand(0);
19298     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19299       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19300       if (!C || C->getZExtValue() != 1)
19301         return SDValue();
19302       return DAG.getNode(ISD::AND, dl, VT,
19303                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19304                                      N00.getOperand(0), N00.getOperand(1)),
19305                          DAG.getConstant(1, VT));
19306     }
19307   }
19308
19309   if (N0.getOpcode() == ISD::TRUNCATE &&
19310       N0.hasOneUse() &&
19311       N0.getOperand(0).hasOneUse()) {
19312     SDValue N00 = N0.getOperand(0);
19313     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19314       return DAG.getNode(ISD::AND, dl, VT,
19315                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19316                                      N00.getOperand(0), N00.getOperand(1)),
19317                          DAG.getConstant(1, VT));
19318     }
19319   }
19320   if (VT.is256BitVector()) {
19321     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19322     if (R.getNode())
19323       return R;
19324   }
19325
19326   return SDValue();
19327 }
19328
19329 // Optimize x == -y --> x+y == 0
19330 //          x != -y --> x+y != 0
19331 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19332                                       const X86Subtarget* Subtarget) {
19333   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19334   SDValue LHS = N->getOperand(0);
19335   SDValue RHS = N->getOperand(1);
19336   EVT VT = N->getValueType(0);
19337   SDLoc DL(N);
19338
19339   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19340     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19341       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19342         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19343                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19344         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19345                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19346       }
19347   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19348     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19349       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19350         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19351                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19352         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19353                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19354       }
19355
19356   if (VT.getScalarType() == MVT::i1) {
19357     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19358       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19359     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19360     if (!IsSEXT0 && !IsVZero0)
19361       return SDValue();
19362     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19363       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19364     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19365
19366     if (!IsSEXT1 && !IsVZero1)
19367       return SDValue();
19368
19369     if (IsSEXT0 && IsVZero1) {
19370       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19371       if (CC == ISD::SETEQ)
19372         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19373       return LHS.getOperand(0);
19374     }
19375     if (IsSEXT1 && IsVZero0) {
19376       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19377       if (CC == ISD::SETEQ)
19378         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19379       return RHS.getOperand(0);
19380     }
19381   }
19382
19383   return SDValue();
19384 }
19385
19386 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19387 // as "sbb reg,reg", since it can be extended without zext and produces
19388 // an all-ones bit which is more useful than 0/1 in some cases.
19389 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19390                                MVT VT) {
19391   if (VT == MVT::i8)
19392     return DAG.getNode(ISD::AND, DL, VT,
19393                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19394                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19395                        DAG.getConstant(1, VT));
19396   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19397   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19398                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19399                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19400 }
19401
19402 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19403 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19404                                    TargetLowering::DAGCombinerInfo &DCI,
19405                                    const X86Subtarget *Subtarget) {
19406   SDLoc DL(N);
19407   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19408   SDValue EFLAGS = N->getOperand(1);
19409
19410   if (CC == X86::COND_A) {
19411     // Try to convert COND_A into COND_B in an attempt to facilitate
19412     // materializing "setb reg".
19413     //
19414     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19415     // cannot take an immediate as its first operand.
19416     //
19417     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19418         EFLAGS.getValueType().isInteger() &&
19419         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19420       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19421                                    EFLAGS.getNode()->getVTList(),
19422                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19423       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19424       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19425     }
19426   }
19427
19428   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19429   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19430   // cases.
19431   if (CC == X86::COND_B)
19432     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19433
19434   SDValue Flags;
19435
19436   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19437   if (Flags.getNode()) {
19438     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19439     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19440   }
19441
19442   return SDValue();
19443 }
19444
19445 // Optimize branch condition evaluation.
19446 //
19447 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19448                                     TargetLowering::DAGCombinerInfo &DCI,
19449                                     const X86Subtarget *Subtarget) {
19450   SDLoc DL(N);
19451   SDValue Chain = N->getOperand(0);
19452   SDValue Dest = N->getOperand(1);
19453   SDValue EFLAGS = N->getOperand(3);
19454   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19455
19456   SDValue Flags;
19457
19458   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19459   if (Flags.getNode()) {
19460     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19461     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19462                        Flags);
19463   }
19464
19465   return SDValue();
19466 }
19467
19468 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19469                                         const X86TargetLowering *XTLI) {
19470   SDValue Op0 = N->getOperand(0);
19471   EVT InVT = Op0->getValueType(0);
19472
19473   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19474   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19475     SDLoc dl(N);
19476     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19477     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19478     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19479   }
19480
19481   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19482   // a 32-bit target where SSE doesn't support i64->FP operations.
19483   if (Op0.getOpcode() == ISD::LOAD) {
19484     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19485     EVT VT = Ld->getValueType(0);
19486     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19487         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19488         !XTLI->getSubtarget()->is64Bit() &&
19489         VT == MVT::i64) {
19490       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19491                                           Ld->getChain(), Op0, DAG);
19492       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19493       return FILDChain;
19494     }
19495   }
19496   return SDValue();
19497 }
19498
19499 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19500 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19501                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19502   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19503   // the result is either zero or one (depending on the input carry bit).
19504   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19505   if (X86::isZeroNode(N->getOperand(0)) &&
19506       X86::isZeroNode(N->getOperand(1)) &&
19507       // We don't have a good way to replace an EFLAGS use, so only do this when
19508       // dead right now.
19509       SDValue(N, 1).use_empty()) {
19510     SDLoc DL(N);
19511     EVT VT = N->getValueType(0);
19512     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19513     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19514                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19515                                            DAG.getConstant(X86::COND_B,MVT::i8),
19516                                            N->getOperand(2)),
19517                                DAG.getConstant(1, VT));
19518     return DCI.CombineTo(N, Res1, CarryOut);
19519   }
19520
19521   return SDValue();
19522 }
19523
19524 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19525 //      (add Y, (setne X, 0)) -> sbb -1, Y
19526 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19527 //      (sub (setne X, 0), Y) -> adc -1, Y
19528 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19529   SDLoc DL(N);
19530
19531   // Look through ZExts.
19532   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19533   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19534     return SDValue();
19535
19536   SDValue SetCC = Ext.getOperand(0);
19537   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19538     return SDValue();
19539
19540   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19541   if (CC != X86::COND_E && CC != X86::COND_NE)
19542     return SDValue();
19543
19544   SDValue Cmp = SetCC.getOperand(1);
19545   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19546       !X86::isZeroNode(Cmp.getOperand(1)) ||
19547       !Cmp.getOperand(0).getValueType().isInteger())
19548     return SDValue();
19549
19550   SDValue CmpOp0 = Cmp.getOperand(0);
19551   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19552                                DAG.getConstant(1, CmpOp0.getValueType()));
19553
19554   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19555   if (CC == X86::COND_NE)
19556     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19557                        DL, OtherVal.getValueType(), OtherVal,
19558                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19559   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19560                      DL, OtherVal.getValueType(), OtherVal,
19561                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19562 }
19563
19564 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19565 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19566                                  const X86Subtarget *Subtarget) {
19567   EVT VT = N->getValueType(0);
19568   SDValue Op0 = N->getOperand(0);
19569   SDValue Op1 = N->getOperand(1);
19570
19571   // Try to synthesize horizontal adds from adds of shuffles.
19572   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19573        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19574       isHorizontalBinOp(Op0, Op1, true))
19575     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19576
19577   return OptimizeConditionalInDecrement(N, DAG);
19578 }
19579
19580 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19581                                  const X86Subtarget *Subtarget) {
19582   SDValue Op0 = N->getOperand(0);
19583   SDValue Op1 = N->getOperand(1);
19584
19585   // X86 can't encode an immediate LHS of a sub. See if we can push the
19586   // negation into a preceding instruction.
19587   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19588     // If the RHS of the sub is a XOR with one use and a constant, invert the
19589     // immediate. Then add one to the LHS of the sub so we can turn
19590     // X-Y -> X+~Y+1, saving one register.
19591     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19592         isa<ConstantSDNode>(Op1.getOperand(1))) {
19593       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19594       EVT VT = Op0.getValueType();
19595       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19596                                    Op1.getOperand(0),
19597                                    DAG.getConstant(~XorC, VT));
19598       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19599                          DAG.getConstant(C->getAPIntValue()+1, VT));
19600     }
19601   }
19602
19603   // Try to synthesize horizontal adds from adds of shuffles.
19604   EVT VT = N->getValueType(0);
19605   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19606        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19607       isHorizontalBinOp(Op0, Op1, true))
19608     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19609
19610   return OptimizeConditionalInDecrement(N, DAG);
19611 }
19612
19613 /// performVZEXTCombine - Performs build vector combines
19614 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19615                                         TargetLowering::DAGCombinerInfo &DCI,
19616                                         const X86Subtarget *Subtarget) {
19617   // (vzext (bitcast (vzext (x)) -> (vzext x)
19618   SDValue In = N->getOperand(0);
19619   while (In.getOpcode() == ISD::BITCAST)
19620     In = In.getOperand(0);
19621
19622   if (In.getOpcode() != X86ISD::VZEXT)
19623     return SDValue();
19624
19625   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19626                      In.getOperand(0));
19627 }
19628
19629 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19630                                              DAGCombinerInfo &DCI) const {
19631   SelectionDAG &DAG = DCI.DAG;
19632   switch (N->getOpcode()) {
19633   default: break;
19634   case ISD::EXTRACT_VECTOR_ELT:
19635     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19636   case ISD::VSELECT:
19637   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19638   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19639   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19640   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19641   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19642   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19643   case ISD::SHL:
19644   case ISD::SRA:
19645   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19646   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19647   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19648   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19649   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19650   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19651   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19652   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19653   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19654   case X86ISD::FXOR:
19655   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19656   case X86ISD::FMIN:
19657   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19658   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19659   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19660   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19661   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19662   case ISD::ANY_EXTEND:
19663   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19664   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19665   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19666   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19667   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
19668   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19669   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19670   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19671   case X86ISD::SHUFP:       // Handle all target specific shuffles
19672   case X86ISD::PALIGNR:
19673   case X86ISD::UNPCKH:
19674   case X86ISD::UNPCKL:
19675   case X86ISD::MOVHLPS:
19676   case X86ISD::MOVLHPS:
19677   case X86ISD::PSHUFD:
19678   case X86ISD::PSHUFHW:
19679   case X86ISD::PSHUFLW:
19680   case X86ISD::MOVSS:
19681   case X86ISD::MOVSD:
19682   case X86ISD::VPERMILP:
19683   case X86ISD::VPERM2X128:
19684   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19685   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19686   }
19687
19688   return SDValue();
19689 }
19690
19691 /// isTypeDesirableForOp - Return true if the target has native support for
19692 /// the specified value type and it is 'desirable' to use the type for the
19693 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19694 /// instruction encodings are longer and some i16 instructions are slow.
19695 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19696   if (!isTypeLegal(VT))
19697     return false;
19698   if (VT != MVT::i16)
19699     return true;
19700
19701   switch (Opc) {
19702   default:
19703     return true;
19704   case ISD::LOAD:
19705   case ISD::SIGN_EXTEND:
19706   case ISD::ZERO_EXTEND:
19707   case ISD::ANY_EXTEND:
19708   case ISD::SHL:
19709   case ISD::SRL:
19710   case ISD::SUB:
19711   case ISD::ADD:
19712   case ISD::MUL:
19713   case ISD::AND:
19714   case ISD::OR:
19715   case ISD::XOR:
19716     return false;
19717   }
19718 }
19719
19720 /// IsDesirableToPromoteOp - This method query the target whether it is
19721 /// beneficial for dag combiner to promote the specified node. If true, it
19722 /// should return the desired promotion type by reference.
19723 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19724   EVT VT = Op.getValueType();
19725   if (VT != MVT::i16)
19726     return false;
19727
19728   bool Promote = false;
19729   bool Commute = false;
19730   switch (Op.getOpcode()) {
19731   default: break;
19732   case ISD::LOAD: {
19733     LoadSDNode *LD = cast<LoadSDNode>(Op);
19734     // If the non-extending load has a single use and it's not live out, then it
19735     // might be folded.
19736     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19737                                                      Op.hasOneUse()*/) {
19738       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19739              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19740         // The only case where we'd want to promote LOAD (rather then it being
19741         // promoted as an operand is when it's only use is liveout.
19742         if (UI->getOpcode() != ISD::CopyToReg)
19743           return false;
19744       }
19745     }
19746     Promote = true;
19747     break;
19748   }
19749   case ISD::SIGN_EXTEND:
19750   case ISD::ZERO_EXTEND:
19751   case ISD::ANY_EXTEND:
19752     Promote = true;
19753     break;
19754   case ISD::SHL:
19755   case ISD::SRL: {
19756     SDValue N0 = Op.getOperand(0);
19757     // Look out for (store (shl (load), x)).
19758     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19759       return false;
19760     Promote = true;
19761     break;
19762   }
19763   case ISD::ADD:
19764   case ISD::MUL:
19765   case ISD::AND:
19766   case ISD::OR:
19767   case ISD::XOR:
19768     Commute = true;
19769     // fallthrough
19770   case ISD::SUB: {
19771     SDValue N0 = Op.getOperand(0);
19772     SDValue N1 = Op.getOperand(1);
19773     if (!Commute && MayFoldLoad(N1))
19774       return false;
19775     // Avoid disabling potential load folding opportunities.
19776     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19777       return false;
19778     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19779       return false;
19780     Promote = true;
19781   }
19782   }
19783
19784   PVT = MVT::i32;
19785   return Promote;
19786 }
19787
19788 //===----------------------------------------------------------------------===//
19789 //                           X86 Inline Assembly Support
19790 //===----------------------------------------------------------------------===//
19791
19792 namespace {
19793   // Helper to match a string separated by whitespace.
19794   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19795     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19796
19797     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19798       StringRef piece(*args[i]);
19799       if (!s.startswith(piece)) // Check if the piece matches.
19800         return false;
19801
19802       s = s.substr(piece.size());
19803       StringRef::size_type pos = s.find_first_not_of(" \t");
19804       if (pos == 0) // We matched a prefix.
19805         return false;
19806
19807       s = s.substr(pos);
19808     }
19809
19810     return s.empty();
19811   }
19812   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19813 }
19814
19815 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19816
19817   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19818     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19819         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19820         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19821
19822       if (AsmPieces.size() == 3)
19823         return true;
19824       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19825         return true;
19826     }
19827   }
19828   return false;
19829 }
19830
19831 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19832   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19833
19834   std::string AsmStr = IA->getAsmString();
19835
19836   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19837   if (!Ty || Ty->getBitWidth() % 16 != 0)
19838     return false;
19839
19840   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19841   SmallVector<StringRef, 4> AsmPieces;
19842   SplitString(AsmStr, AsmPieces, ";\n");
19843
19844   switch (AsmPieces.size()) {
19845   default: return false;
19846   case 1:
19847     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19848     // we will turn this bswap into something that will be lowered to logical
19849     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19850     // lower so don't worry about this.
19851     // bswap $0
19852     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19853         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19854         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19855         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19856         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19857         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19858       // No need to check constraints, nothing other than the equivalent of
19859       // "=r,0" would be valid here.
19860       return IntrinsicLowering::LowerToByteSwap(CI);
19861     }
19862
19863     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19864     if (CI->getType()->isIntegerTy(16) &&
19865         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19866         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19867          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19868       AsmPieces.clear();
19869       const std::string &ConstraintsStr = IA->getConstraintString();
19870       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19871       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19872       if (clobbersFlagRegisters(AsmPieces))
19873         return IntrinsicLowering::LowerToByteSwap(CI);
19874     }
19875     break;
19876   case 3:
19877     if (CI->getType()->isIntegerTy(32) &&
19878         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19879         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19880         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19881         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19882       AsmPieces.clear();
19883       const std::string &ConstraintsStr = IA->getConstraintString();
19884       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19885       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19886       if (clobbersFlagRegisters(AsmPieces))
19887         return IntrinsicLowering::LowerToByteSwap(CI);
19888     }
19889
19890     if (CI->getType()->isIntegerTy(64)) {
19891       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19892       if (Constraints.size() >= 2 &&
19893           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19894           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19895         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19896         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19897             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19898             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19899           return IntrinsicLowering::LowerToByteSwap(CI);
19900       }
19901     }
19902     break;
19903   }
19904   return false;
19905 }
19906
19907 /// getConstraintType - Given a constraint letter, return the type of
19908 /// constraint it is for this target.
19909 X86TargetLowering::ConstraintType
19910 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19911   if (Constraint.size() == 1) {
19912     switch (Constraint[0]) {
19913     case 'R':
19914     case 'q':
19915     case 'Q':
19916     case 'f':
19917     case 't':
19918     case 'u':
19919     case 'y':
19920     case 'x':
19921     case 'Y':
19922     case 'l':
19923       return C_RegisterClass;
19924     case 'a':
19925     case 'b':
19926     case 'c':
19927     case 'd':
19928     case 'S':
19929     case 'D':
19930     case 'A':
19931       return C_Register;
19932     case 'I':
19933     case 'J':
19934     case 'K':
19935     case 'L':
19936     case 'M':
19937     case 'N':
19938     case 'G':
19939     case 'C':
19940     case 'e':
19941     case 'Z':
19942       return C_Other;
19943     default:
19944       break;
19945     }
19946   }
19947   return TargetLowering::getConstraintType(Constraint);
19948 }
19949
19950 /// Examine constraint type and operand type and determine a weight value.
19951 /// This object must already have been set up with the operand type
19952 /// and the current alternative constraint selected.
19953 TargetLowering::ConstraintWeight
19954   X86TargetLowering::getSingleConstraintMatchWeight(
19955     AsmOperandInfo &info, const char *constraint) const {
19956   ConstraintWeight weight = CW_Invalid;
19957   Value *CallOperandVal = info.CallOperandVal;
19958     // If we don't have a value, we can't do a match,
19959     // but allow it at the lowest weight.
19960   if (CallOperandVal == NULL)
19961     return CW_Default;
19962   Type *type = CallOperandVal->getType();
19963   // Look at the constraint type.
19964   switch (*constraint) {
19965   default:
19966     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19967   case 'R':
19968   case 'q':
19969   case 'Q':
19970   case 'a':
19971   case 'b':
19972   case 'c':
19973   case 'd':
19974   case 'S':
19975   case 'D':
19976   case 'A':
19977     if (CallOperandVal->getType()->isIntegerTy())
19978       weight = CW_SpecificReg;
19979     break;
19980   case 'f':
19981   case 't':
19982   case 'u':
19983     if (type->isFloatingPointTy())
19984       weight = CW_SpecificReg;
19985     break;
19986   case 'y':
19987     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19988       weight = CW_SpecificReg;
19989     break;
19990   case 'x':
19991   case 'Y':
19992     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19993         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19994       weight = CW_Register;
19995     break;
19996   case 'I':
19997     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19998       if (C->getZExtValue() <= 31)
19999         weight = CW_Constant;
20000     }
20001     break;
20002   case 'J':
20003     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20004       if (C->getZExtValue() <= 63)
20005         weight = CW_Constant;
20006     }
20007     break;
20008   case 'K':
20009     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20010       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20011         weight = CW_Constant;
20012     }
20013     break;
20014   case 'L':
20015     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20016       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20017         weight = CW_Constant;
20018     }
20019     break;
20020   case 'M':
20021     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20022       if (C->getZExtValue() <= 3)
20023         weight = CW_Constant;
20024     }
20025     break;
20026   case 'N':
20027     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20028       if (C->getZExtValue() <= 0xff)
20029         weight = CW_Constant;
20030     }
20031     break;
20032   case 'G':
20033   case 'C':
20034     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20035       weight = CW_Constant;
20036     }
20037     break;
20038   case 'e':
20039     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20040       if ((C->getSExtValue() >= -0x80000000LL) &&
20041           (C->getSExtValue() <= 0x7fffffffLL))
20042         weight = CW_Constant;
20043     }
20044     break;
20045   case 'Z':
20046     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20047       if (C->getZExtValue() <= 0xffffffff)
20048         weight = CW_Constant;
20049     }
20050     break;
20051   }
20052   return weight;
20053 }
20054
20055 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20056 /// with another that has more specific requirements based on the type of the
20057 /// corresponding operand.
20058 const char *X86TargetLowering::
20059 LowerXConstraint(EVT ConstraintVT) const {
20060   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20061   // 'f' like normal targets.
20062   if (ConstraintVT.isFloatingPoint()) {
20063     if (Subtarget->hasSSE2())
20064       return "Y";
20065     if (Subtarget->hasSSE1())
20066       return "x";
20067   }
20068
20069   return TargetLowering::LowerXConstraint(ConstraintVT);
20070 }
20071
20072 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20073 /// vector.  If it is invalid, don't add anything to Ops.
20074 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20075                                                      std::string &Constraint,
20076                                                      std::vector<SDValue>&Ops,
20077                                                      SelectionDAG &DAG) const {
20078   SDValue Result(0, 0);
20079
20080   // Only support length 1 constraints for now.
20081   if (Constraint.length() > 1) return;
20082
20083   char ConstraintLetter = Constraint[0];
20084   switch (ConstraintLetter) {
20085   default: break;
20086   case 'I':
20087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20088       if (C->getZExtValue() <= 31) {
20089         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20090         break;
20091       }
20092     }
20093     return;
20094   case 'J':
20095     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20096       if (C->getZExtValue() <= 63) {
20097         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20098         break;
20099       }
20100     }
20101     return;
20102   case 'K':
20103     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20104       if (isInt<8>(C->getSExtValue())) {
20105         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20106         break;
20107       }
20108     }
20109     return;
20110   case 'N':
20111     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20112       if (C->getZExtValue() <= 255) {
20113         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20114         break;
20115       }
20116     }
20117     return;
20118   case 'e': {
20119     // 32-bit signed value
20120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20121       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20122                                            C->getSExtValue())) {
20123         // Widen to 64 bits here to get it sign extended.
20124         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20125         break;
20126       }
20127     // FIXME gcc accepts some relocatable values here too, but only in certain
20128     // memory models; it's complicated.
20129     }
20130     return;
20131   }
20132   case 'Z': {
20133     // 32-bit unsigned value
20134     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20135       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20136                                            C->getZExtValue())) {
20137         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20138         break;
20139       }
20140     }
20141     // FIXME gcc accepts some relocatable values here too, but only in certain
20142     // memory models; it's complicated.
20143     return;
20144   }
20145   case 'i': {
20146     // Literal immediates are always ok.
20147     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20148       // Widen to 64 bits here to get it sign extended.
20149       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20150       break;
20151     }
20152
20153     // In any sort of PIC mode addresses need to be computed at runtime by
20154     // adding in a register or some sort of table lookup.  These can't
20155     // be used as immediates.
20156     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20157       return;
20158
20159     // If we are in non-pic codegen mode, we allow the address of a global (with
20160     // an optional displacement) to be used with 'i'.
20161     GlobalAddressSDNode *GA = 0;
20162     int64_t Offset = 0;
20163
20164     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20165     while (1) {
20166       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20167         Offset += GA->getOffset();
20168         break;
20169       } else if (Op.getOpcode() == ISD::ADD) {
20170         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20171           Offset += C->getZExtValue();
20172           Op = Op.getOperand(0);
20173           continue;
20174         }
20175       } else if (Op.getOpcode() == ISD::SUB) {
20176         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20177           Offset += -C->getZExtValue();
20178           Op = Op.getOperand(0);
20179           continue;
20180         }
20181       }
20182
20183       // Otherwise, this isn't something we can handle, reject it.
20184       return;
20185     }
20186
20187     const GlobalValue *GV = GA->getGlobal();
20188     // If we require an extra load to get this address, as in PIC mode, we
20189     // can't accept it.
20190     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20191                                                         getTargetMachine())))
20192       return;
20193
20194     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20195                                         GA->getValueType(0), Offset);
20196     break;
20197   }
20198   }
20199
20200   if (Result.getNode()) {
20201     Ops.push_back(Result);
20202     return;
20203   }
20204   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20205 }
20206
20207 std::pair<unsigned, const TargetRegisterClass*>
20208 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20209                                                 MVT VT) const {
20210   // First, see if this is a constraint that directly corresponds to an LLVM
20211   // register class.
20212   if (Constraint.size() == 1) {
20213     // GCC Constraint Letters
20214     switch (Constraint[0]) {
20215     default: break;
20216       // TODO: Slight differences here in allocation order and leaving
20217       // RIP in the class. Do they matter any more here than they do
20218       // in the normal allocation?
20219     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20220       if (Subtarget->is64Bit()) {
20221         if (VT == MVT::i32 || VT == MVT::f32)
20222           return std::make_pair(0U, &X86::GR32RegClass);
20223         if (VT == MVT::i16)
20224           return std::make_pair(0U, &X86::GR16RegClass);
20225         if (VT == MVT::i8 || VT == MVT::i1)
20226           return std::make_pair(0U, &X86::GR8RegClass);
20227         if (VT == MVT::i64 || VT == MVT::f64)
20228           return std::make_pair(0U, &X86::GR64RegClass);
20229         break;
20230       }
20231       // 32-bit fallthrough
20232     case 'Q':   // Q_REGS
20233       if (VT == MVT::i32 || VT == MVT::f32)
20234         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20235       if (VT == MVT::i16)
20236         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20237       if (VT == MVT::i8 || VT == MVT::i1)
20238         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20239       if (VT == MVT::i64)
20240         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20241       break;
20242     case 'r':   // GENERAL_REGS
20243     case 'l':   // INDEX_REGS
20244       if (VT == MVT::i8 || VT == MVT::i1)
20245         return std::make_pair(0U, &X86::GR8RegClass);
20246       if (VT == MVT::i16)
20247         return std::make_pair(0U, &X86::GR16RegClass);
20248       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20249         return std::make_pair(0U, &X86::GR32RegClass);
20250       return std::make_pair(0U, &X86::GR64RegClass);
20251     case 'R':   // LEGACY_REGS
20252       if (VT == MVT::i8 || VT == MVT::i1)
20253         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20254       if (VT == MVT::i16)
20255         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20256       if (VT == MVT::i32 || !Subtarget->is64Bit())
20257         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20258       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20259     case 'f':  // FP Stack registers.
20260       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20261       // value to the correct fpstack register class.
20262       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20263         return std::make_pair(0U, &X86::RFP32RegClass);
20264       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20265         return std::make_pair(0U, &X86::RFP64RegClass);
20266       return std::make_pair(0U, &X86::RFP80RegClass);
20267     case 'y':   // MMX_REGS if MMX allowed.
20268       if (!Subtarget->hasMMX()) break;
20269       return std::make_pair(0U, &X86::VR64RegClass);
20270     case 'Y':   // SSE_REGS if SSE2 allowed
20271       if (!Subtarget->hasSSE2()) break;
20272       // FALL THROUGH.
20273     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20274       if (!Subtarget->hasSSE1()) break;
20275
20276       switch (VT.SimpleTy) {
20277       default: break;
20278       // Scalar SSE types.
20279       case MVT::f32:
20280       case MVT::i32:
20281         return std::make_pair(0U, &X86::FR32RegClass);
20282       case MVT::f64:
20283       case MVT::i64:
20284         return std::make_pair(0U, &X86::FR64RegClass);
20285       // Vector types.
20286       case MVT::v16i8:
20287       case MVT::v8i16:
20288       case MVT::v4i32:
20289       case MVT::v2i64:
20290       case MVT::v4f32:
20291       case MVT::v2f64:
20292         return std::make_pair(0U, &X86::VR128RegClass);
20293       // AVX types.
20294       case MVT::v32i8:
20295       case MVT::v16i16:
20296       case MVT::v8i32:
20297       case MVT::v4i64:
20298       case MVT::v8f32:
20299       case MVT::v4f64:
20300         return std::make_pair(0U, &X86::VR256RegClass);
20301       case MVT::v8f64:
20302       case MVT::v16f32:
20303       case MVT::v16i32:
20304       case MVT::v8i64:
20305         return std::make_pair(0U, &X86::VR512RegClass);
20306       }
20307       break;
20308     }
20309   }
20310
20311   // Use the default implementation in TargetLowering to convert the register
20312   // constraint into a member of a register class.
20313   std::pair<unsigned, const TargetRegisterClass*> Res;
20314   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20315
20316   // Not found as a standard register?
20317   if (Res.second == 0) {
20318     // Map st(0) -> st(7) -> ST0
20319     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20320         tolower(Constraint[1]) == 's' &&
20321         tolower(Constraint[2]) == 't' &&
20322         Constraint[3] == '(' &&
20323         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20324         Constraint[5] == ')' &&
20325         Constraint[6] == '}') {
20326
20327       Res.first = X86::ST0+Constraint[4]-'0';
20328       Res.second = &X86::RFP80RegClass;
20329       return Res;
20330     }
20331
20332     // GCC allows "st(0)" to be called just plain "st".
20333     if (StringRef("{st}").equals_lower(Constraint)) {
20334       Res.first = X86::ST0;
20335       Res.second = &X86::RFP80RegClass;
20336       return Res;
20337     }
20338
20339     // flags -> EFLAGS
20340     if (StringRef("{flags}").equals_lower(Constraint)) {
20341       Res.first = X86::EFLAGS;
20342       Res.second = &X86::CCRRegClass;
20343       return Res;
20344     }
20345
20346     // 'A' means EAX + EDX.
20347     if (Constraint == "A") {
20348       Res.first = X86::EAX;
20349       Res.second = &X86::GR32_ADRegClass;
20350       return Res;
20351     }
20352     return Res;
20353   }
20354
20355   // Otherwise, check to see if this is a register class of the wrong value
20356   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20357   // turn into {ax},{dx}.
20358   if (Res.second->hasType(VT))
20359     return Res;   // Correct type already, nothing to do.
20360
20361   // All of the single-register GCC register classes map their values onto
20362   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20363   // really want an 8-bit or 32-bit register, map to the appropriate register
20364   // class and return the appropriate register.
20365   if (Res.second == &X86::GR16RegClass) {
20366     if (VT == MVT::i8 || VT == MVT::i1) {
20367       unsigned DestReg = 0;
20368       switch (Res.first) {
20369       default: break;
20370       case X86::AX: DestReg = X86::AL; break;
20371       case X86::DX: DestReg = X86::DL; break;
20372       case X86::CX: DestReg = X86::CL; break;
20373       case X86::BX: DestReg = X86::BL; break;
20374       }
20375       if (DestReg) {
20376         Res.first = DestReg;
20377         Res.second = &X86::GR8RegClass;
20378       }
20379     } else if (VT == MVT::i32 || VT == MVT::f32) {
20380       unsigned DestReg = 0;
20381       switch (Res.first) {
20382       default: break;
20383       case X86::AX: DestReg = X86::EAX; break;
20384       case X86::DX: DestReg = X86::EDX; break;
20385       case X86::CX: DestReg = X86::ECX; break;
20386       case X86::BX: DestReg = X86::EBX; break;
20387       case X86::SI: DestReg = X86::ESI; break;
20388       case X86::DI: DestReg = X86::EDI; break;
20389       case X86::BP: DestReg = X86::EBP; break;
20390       case X86::SP: DestReg = X86::ESP; break;
20391       }
20392       if (DestReg) {
20393         Res.first = DestReg;
20394         Res.second = &X86::GR32RegClass;
20395       }
20396     } else if (VT == MVT::i64 || VT == MVT::f64) {
20397       unsigned DestReg = 0;
20398       switch (Res.first) {
20399       default: break;
20400       case X86::AX: DestReg = X86::RAX; break;
20401       case X86::DX: DestReg = X86::RDX; break;
20402       case X86::CX: DestReg = X86::RCX; break;
20403       case X86::BX: DestReg = X86::RBX; break;
20404       case X86::SI: DestReg = X86::RSI; break;
20405       case X86::DI: DestReg = X86::RDI; break;
20406       case X86::BP: DestReg = X86::RBP; break;
20407       case X86::SP: DestReg = X86::RSP; break;
20408       }
20409       if (DestReg) {
20410         Res.first = DestReg;
20411         Res.second = &X86::GR64RegClass;
20412       }
20413     }
20414   } else if (Res.second == &X86::FR32RegClass ||
20415              Res.second == &X86::FR64RegClass ||
20416              Res.second == &X86::VR128RegClass ||
20417              Res.second == &X86::VR256RegClass ||
20418              Res.second == &X86::FR32XRegClass ||
20419              Res.second == &X86::FR64XRegClass ||
20420              Res.second == &X86::VR128XRegClass ||
20421              Res.second == &X86::VR256XRegClass ||
20422              Res.second == &X86::VR512RegClass) {
20423     // Handle references to XMM physical registers that got mapped into the
20424     // wrong class.  This can happen with constraints like {xmm0} where the
20425     // target independent register mapper will just pick the first match it can
20426     // find, ignoring the required type.
20427
20428     if (VT == MVT::f32 || VT == MVT::i32)
20429       Res.second = &X86::FR32RegClass;
20430     else if (VT == MVT::f64 || VT == MVT::i64)
20431       Res.second = &X86::FR64RegClass;
20432     else if (X86::VR128RegClass.hasType(VT))
20433       Res.second = &X86::VR128RegClass;
20434     else if (X86::VR256RegClass.hasType(VT))
20435       Res.second = &X86::VR256RegClass;
20436     else if (X86::VR512RegClass.hasType(VT))
20437       Res.second = &X86::VR512RegClass;
20438   }
20439
20440   return Res;
20441 }