Move the segmented stack switch to a function attribute
[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 "X86CallingConv.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.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->isTargetKnownWindowsMSVC())
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->isTargetKnownWindowsMSVC()) {
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->isTargetWindowsGNU()) {
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   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                      MVT::i64 : MVT::i32, Custom);
640
641   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
642     // f32 and f64 use SSE.
643     // Set up the FP register classes.
644     addRegisterClass(MVT::f32, &X86::FR32RegClass);
645     addRegisterClass(MVT::f64, &X86::FR64RegClass);
646
647     // Use ANDPD to simulate FABS.
648     setOperationAction(ISD::FABS , MVT::f64, Custom);
649     setOperationAction(ISD::FABS , MVT::f32, Custom);
650
651     // Use XORP to simulate FNEG.
652     setOperationAction(ISD::FNEG , MVT::f64, Custom);
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     // Use ANDPD and ORPD to simulate FCOPYSIGN.
656     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
657     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
658
659     // Lower this to FGETSIGNx86 plus an AND.
660     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
661     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
662
663     // We don't support sin/cos/fmod
664     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
665     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
666     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
670
671     // Expand FP immediates into loads from the stack, except for the special
672     // cases we handle.
673     addLegalFPImmediate(APFloat(+0.0)); // xorpd
674     addLegalFPImmediate(APFloat(+0.0f)); // xorps
675   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
676     // Use SSE for f32, x87 for f64.
677     // Set up the FP register classes.
678     addRegisterClass(MVT::f32, &X86::FR32RegClass);
679     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
680
681     // Use ANDPS to simulate FABS.
682     setOperationAction(ISD::FABS , MVT::f32, Custom);
683
684     // Use XORP to simulate FNEG.
685     setOperationAction(ISD::FNEG , MVT::f32, Custom);
686
687     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
688
689     // Use ANDPS and ORPS to simulate FCOPYSIGN.
690     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
691     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
692
693     // We don't support sin/cos/fmod
694     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
695     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
696     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697
698     // Special cases we handle for FP constants.
699     addLegalFPImmediate(APFloat(+0.0f)); // xorps
700     addLegalFPImmediate(APFloat(+0.0)); // FLD0
701     addLegalFPImmediate(APFloat(+1.0)); // FLD1
702     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
703     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
704
705     if (!TM.Options.UnsafeFPMath) {
706       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
707       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
708       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
709     }
710   } else if (!TM.Options.UseSoftFloat) {
711     // f32 and f64 in x87.
712     // Set up the FP register classes.
713     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
714     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
715
716     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
717     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
718     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
720
721     if (!TM.Options.UnsafeFPMath) {
722       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
723       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
724       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
726       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
728     }
729     addLegalFPImmediate(APFloat(+0.0)); // FLD0
730     addLegalFPImmediate(APFloat(+1.0)); // FLD1
731     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
732     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
733     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
737   }
738
739   // We don't support FMA.
740   setOperationAction(ISD::FMA, MVT::f64, Expand);
741   setOperationAction(ISD::FMA, MVT::f32, Expand);
742
743   // Long double always uses X87.
744   if (!TM.Options.UseSoftFloat) {
745     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
746     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
747     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
748     {
749       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
750       addLegalFPImmediate(TmpFlt);  // FLD0
751       TmpFlt.changeSign();
752       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
753
754       bool ignored;
755       APFloat TmpFlt2(+1.0);
756       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
757                       &ignored);
758       addLegalFPImmediate(TmpFlt2);  // FLD1
759       TmpFlt2.changeSign();
760       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
761     }
762
763     if (!TM.Options.UnsafeFPMath) {
764       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
765       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
766       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
767     }
768
769     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
770     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
771     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
772     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
773     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
774     setOperationAction(ISD::FMA, MVT::f80, Expand);
775   }
776
777   // Always use a library call for pow.
778   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
779   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
781
782   setOperationAction(ISD::FLOG, MVT::f80, Expand);
783   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785   setOperationAction(ISD::FEXP, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
787
788   // First set operation action for all vector types to either promote
789   // (for widening) or expand (for scalarization). Then we will selectively
790   // turn on ones that can be effectively codegen'd.
791   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
792            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
793     MVT VT = (MVT::SimpleValueType)i;
794     setOperationAction(ISD::ADD , VT, Expand);
795     setOperationAction(ISD::SUB , VT, Expand);
796     setOperationAction(ISD::FADD, VT, Expand);
797     setOperationAction(ISD::FNEG, VT, Expand);
798     setOperationAction(ISD::FSUB, VT, Expand);
799     setOperationAction(ISD::MUL , VT, Expand);
800     setOperationAction(ISD::FMUL, VT, Expand);
801     setOperationAction(ISD::SDIV, VT, Expand);
802     setOperationAction(ISD::UDIV, VT, Expand);
803     setOperationAction(ISD::FDIV, VT, Expand);
804     setOperationAction(ISD::SREM, VT, Expand);
805     setOperationAction(ISD::UREM, VT, Expand);
806     setOperationAction(ISD::LOAD, VT, Expand);
807     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
809     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
810     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
811     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::FABS, VT, Expand);
813     setOperationAction(ISD::FSIN, VT, Expand);
814     setOperationAction(ISD::FSINCOS, VT, Expand);
815     setOperationAction(ISD::FCOS, VT, Expand);
816     setOperationAction(ISD::FSINCOS, VT, Expand);
817     setOperationAction(ISD::FREM, VT, Expand);
818     setOperationAction(ISD::FMA,  VT, Expand);
819     setOperationAction(ISD::FPOWI, VT, Expand);
820     setOperationAction(ISD::FSQRT, VT, Expand);
821     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
822     setOperationAction(ISD::FFLOOR, VT, Expand);
823     setOperationAction(ISD::FCEIL, VT, Expand);
824     setOperationAction(ISD::FTRUNC, VT, Expand);
825     setOperationAction(ISD::FRINT, VT, Expand);
826     setOperationAction(ISD::FNEARBYINT, VT, Expand);
827     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
828     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
829     setOperationAction(ISD::SDIVREM, VT, Expand);
830     setOperationAction(ISD::UDIVREM, VT, Expand);
831     setOperationAction(ISD::FPOW, VT, Expand);
832     setOperationAction(ISD::CTPOP, VT, Expand);
833     setOperationAction(ISD::CTTZ, VT, Expand);
834     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
835     setOperationAction(ISD::CTLZ, VT, Expand);
836     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
837     setOperationAction(ISD::SHL, VT, Expand);
838     setOperationAction(ISD::SRA, VT, Expand);
839     setOperationAction(ISD::SRL, VT, Expand);
840     setOperationAction(ISD::ROTL, VT, Expand);
841     setOperationAction(ISD::ROTR, VT, Expand);
842     setOperationAction(ISD::BSWAP, VT, Expand);
843     setOperationAction(ISD::SETCC, VT, Expand);
844     setOperationAction(ISD::FLOG, VT, Expand);
845     setOperationAction(ISD::FLOG2, VT, Expand);
846     setOperationAction(ISD::FLOG10, VT, Expand);
847     setOperationAction(ISD::FEXP, VT, Expand);
848     setOperationAction(ISD::FEXP2, VT, Expand);
849     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
850     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
851     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
852     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
853     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
854     setOperationAction(ISD::TRUNCATE, VT, Expand);
855     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
856     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
857     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
858     setOperationAction(ISD::VSELECT, VT, Expand);
859     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
860              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
861       setTruncStoreAction(VT,
862                           (MVT::SimpleValueType)InnerVT, Expand);
863     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
864     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
865     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
866   }
867
868   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
869   // with -msoft-float, disable use of MMX as well.
870   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
871     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
872     // No operations on x86mmx supported, everything uses intrinsics.
873   }
874
875   // MMX-sized vectors (other than x86mmx) are expected to be expanded
876   // into smaller operations.
877   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
878   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
879   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
880   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
881   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
882   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
883   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
884   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
885   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
886   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
887   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
888   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
889   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
890   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
891   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
892   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
893   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
894   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
897   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
898   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
899   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
900   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
902   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
903   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
906
907   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
908     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
909
910     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
911     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
912     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
915     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
916     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
917     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
918     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
919     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
920     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
921     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
922   }
923
924   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
925     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
926
927     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
928     // registers cannot be used even for integer operations.
929     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
930     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
931     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
932     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
933
934     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
935     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
936     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
937     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
938     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
939     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
940     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
941     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
942     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
943     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
944     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
945     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
946     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
947     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
948     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
950     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
951     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
952
953     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
954     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
955     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
956     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
957
958     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
959     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
960     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
963
964     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
965     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
966       MVT VT = (MVT::SimpleValueType)i;
967       // Do not attempt to custom lower non-power-of-2 vectors
968       if (!isPowerOf2_32(VT.getVectorNumElements()))
969         continue;
970       // Do not attempt to custom lower non-128-bit vectors
971       if (!VT.is128BitVector())
972         continue;
973       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
974       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
975       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
976     }
977
978     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
979     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
980     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
981     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
983     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
984
985     if (Subtarget->is64Bit()) {
986       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
987       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
988     }
989
990     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
991     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
992       MVT VT = (MVT::SimpleValueType)i;
993
994       // Do not attempt to promote non-128-bit vectors
995       if (!VT.is128BitVector())
996         continue;
997
998       setOperationAction(ISD::AND,    VT, Promote);
999       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1000       setOperationAction(ISD::OR,     VT, Promote);
1001       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1002       setOperationAction(ISD::XOR,    VT, Promote);
1003       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1004       setOperationAction(ISD::LOAD,   VT, Promote);
1005       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1006       setOperationAction(ISD::SELECT, VT, Promote);
1007       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1008     }
1009
1010     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1011
1012     // Custom lower v2i64 and v2f64 selects.
1013     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1014     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1015     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1016     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1017
1018     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1019     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1020
1021     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1022     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1023     // As there is no 64-bit GPR available, we need build a special custom
1024     // sequence to convert from v2i32 to v2f32.
1025     if (!Subtarget->is64Bit())
1026       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1027
1028     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1029     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1030
1031     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1032   }
1033
1034   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1035     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1036     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1037     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1038     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1039     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1040     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1041     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1042     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1043     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1044     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1045
1046     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1047     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1048     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1049     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1050     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1051     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1052     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1053     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1054     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1055     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1056
1057     // FIXME: Do we need to handle scalar-to-vector here?
1058     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1059
1060     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1061     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1062     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1063     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1065
1066     // i8 and i16 vectors are custom , because the source register and source
1067     // source memory operand types are not the same width.  f32 vectors are
1068     // custom since the immediate controlling the insert encodes additional
1069     // information.
1070     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1071     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1072     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1074
1075     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1076     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1077     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1079
1080     // FIXME: these should be Legal but thats only for the case where
1081     // the index is constant.  For now custom expand to deal with that.
1082     if (Subtarget->is64Bit()) {
1083       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1084       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1085     }
1086   }
1087
1088   if (Subtarget->hasSSE2()) {
1089     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1090     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1091
1092     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1093     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1094
1095     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1096     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1097
1098     // In the customized shift lowering, the legal cases in AVX2 will be
1099     // recognized.
1100     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1101     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1102
1103     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1104     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1105
1106     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1107
1108     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1109     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1110   }
1111
1112   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1113     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1114     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1115     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1116     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1119
1120     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1121     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1122     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1123
1124     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1125     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1126     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1127     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1129     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1130     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1131     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1132     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1133     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1134     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1135     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1136
1137     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1138     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1139     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1140     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1142     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1143     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1144     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1145     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1146     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1147     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1148     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1149
1150     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1151     // even though v8i16 is a legal type.
1152     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1153     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1154     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1155
1156     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1157     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1158     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1159
1160     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1161     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1162
1163     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1164
1165     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1172     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1173
1174     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1175
1176     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1177     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1180
1181     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1182     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1183     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1184
1185     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1186     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1189
1190     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1193     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1196     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1199     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1202
1203     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1204       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1208       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1210     }
1211
1212     if (Subtarget->hasInt256()) {
1213       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1217
1218       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1222
1223       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1224       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1225       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1226       // Don't lower v32i8 because there is no 128-bit byte mul
1227
1228       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1229
1230       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1231     } else {
1232       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1236
1237       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1241
1242       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1243       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1244       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1245       // Don't lower v32i8 because there is no 128-bit byte mul
1246     }
1247
1248     // In the customized shift lowering, the legal cases in AVX2 will be
1249     // recognized.
1250     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1251     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1252
1253     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1254     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1255
1256     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1257
1258     // Custom lower several nodes for 256-bit types.
1259     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1260              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1261       MVT VT = (MVT::SimpleValueType)i;
1262
1263       // Extract subvector is special because the value type
1264       // (result) is 128-bit but the source is 256-bit wide.
1265       if (VT.is128BitVector())
1266         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1267
1268       // Do not attempt to custom lower other non-256-bit vectors
1269       if (!VT.is256BitVector())
1270         continue;
1271
1272       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1273       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1274       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1275       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1276       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1277       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1278       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1279     }
1280
1281     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1282     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1283       MVT VT = (MVT::SimpleValueType)i;
1284
1285       // Do not attempt to promote non-256-bit vectors
1286       if (!VT.is256BitVector())
1287         continue;
1288
1289       setOperationAction(ISD::AND,    VT, Promote);
1290       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1291       setOperationAction(ISD::OR,     VT, Promote);
1292       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1293       setOperationAction(ISD::XOR,    VT, Promote);
1294       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1295       setOperationAction(ISD::LOAD,   VT, Promote);
1296       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1297       setOperationAction(ISD::SELECT, VT, Promote);
1298       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1299     }
1300   }
1301
1302   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1303     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1304     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1307
1308     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1309     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1310     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1311
1312     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1313     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1314     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1315     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1316     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1317     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1318     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1323
1324     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1329     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1330
1331     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1336     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1337     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1338     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1339     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1340
1341     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1342     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1343     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1345     if (Subtarget->is64Bit()) {
1346       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1347       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1348       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1349       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1350     }
1351     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1352     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1359     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1360     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1361
1362     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1363     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1368     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1369     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1370     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1373     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1375
1376     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1382
1383     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1384     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1385
1386     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1387
1388     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1389     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1390     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1391     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, 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 MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1807   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1808   return ScratchRegs;
1809 }
1810
1811 SDValue
1812 X86TargetLowering::LowerReturn(SDValue Chain,
1813                                CallingConv::ID CallConv, bool isVarArg,
1814                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1815                                const SmallVectorImpl<SDValue> &OutVals,
1816                                SDLoc dl, SelectionDAG &DAG) const {
1817   MachineFunction &MF = DAG.getMachineFunction();
1818   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1819
1820   SmallVector<CCValAssign, 16> RVLocs;
1821   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1822                  RVLocs, *DAG.getContext());
1823   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1824
1825   SDValue Flag;
1826   SmallVector<SDValue, 6> RetOps;
1827   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1828   // Operand #1 = Bytes To Pop
1829   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1830                    MVT::i16));
1831
1832   // Copy the result values into the output registers.
1833   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1834     CCValAssign &VA = RVLocs[i];
1835     assert(VA.isRegLoc() && "Can only return in registers!");
1836     SDValue ValToCopy = OutVals[i];
1837     EVT ValVT = ValToCopy.getValueType();
1838
1839     // Promote values to the appropriate types
1840     if (VA.getLocInfo() == CCValAssign::SExt)
1841       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1842     else if (VA.getLocInfo() == CCValAssign::ZExt)
1843       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1844     else if (VA.getLocInfo() == CCValAssign::AExt)
1845       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1846     else if (VA.getLocInfo() == CCValAssign::BCvt)
1847       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1848
1849     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1850            "Unexpected FP-extend for return value.");  
1851
1852     // If this is x86-64, and we disabled SSE, we can't return FP values,
1853     // or SSE or MMX vectors.
1854     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1855          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1856           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1857       report_fatal_error("SSE register return with SSE disabled");
1858     }
1859     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1860     // llvm-gcc has never done it right and no one has noticed, so this
1861     // should be OK for now.
1862     if (ValVT == MVT::f64 &&
1863         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1864       report_fatal_error("SSE2 register return with SSE2 disabled");
1865
1866     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1867     // the RET instruction and handled by the FP Stackifier.
1868     if (VA.getLocReg() == X86::ST0 ||
1869         VA.getLocReg() == X86::ST1) {
1870       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1871       // change the value to the FP stack register class.
1872       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1873         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1874       RetOps.push_back(ValToCopy);
1875       // Don't emit a copytoreg.
1876       continue;
1877     }
1878
1879     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1880     // which is returned in RAX / RDX.
1881     if (Subtarget->is64Bit()) {
1882       if (ValVT == MVT::x86mmx) {
1883         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1884           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1885           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1886                                   ValToCopy);
1887           // If we don't have SSE2 available, convert to v4f32 so the generated
1888           // register is legal.
1889           if (!Subtarget->hasSSE2())
1890             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1891         }
1892       }
1893     }
1894
1895     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1896     Flag = Chain.getValue(1);
1897     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1898   }
1899
1900   // The x86-64 ABIs require that for returning structs by value we copy
1901   // the sret argument into %rax/%eax (depending on ABI) for the return.
1902   // Win32 requires us to put the sret argument to %eax as well.
1903   // We saved the argument into a virtual register in the entry block,
1904   // so now we copy the value out and into %rax/%eax.
1905   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1906       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1907     MachineFunction &MF = DAG.getMachineFunction();
1908     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1909     unsigned Reg = FuncInfo->getSRetReturnReg();
1910     assert(Reg &&
1911            "SRetReturnReg should have been set in LowerFormalArguments().");
1912     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1913
1914     unsigned RetValReg
1915         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1916           X86::RAX : X86::EAX;
1917     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1918     Flag = Chain.getValue(1);
1919
1920     // RAX/EAX now acts like a return value.
1921     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1922   }
1923
1924   RetOps[0] = Chain;  // Update chain.
1925
1926   // Add the flag if we have it.
1927   if (Flag.getNode())
1928     RetOps.push_back(Flag);
1929
1930   return DAG.getNode(X86ISD::RET_FLAG, dl,
1931                      MVT::Other, &RetOps[0], RetOps.size());
1932 }
1933
1934 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1935   if (N->getNumValues() != 1)
1936     return false;
1937   if (!N->hasNUsesOfValue(1, 0))
1938     return false;
1939
1940   SDValue TCChain = Chain;
1941   SDNode *Copy = *N->use_begin();
1942   if (Copy->getOpcode() == ISD::CopyToReg) {
1943     // If the copy has a glue operand, we conservatively assume it isn't safe to
1944     // perform a tail call.
1945     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1946       return false;
1947     TCChain = Copy->getOperand(0);
1948   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1949     return false;
1950
1951   bool HasRet = false;
1952   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1953        UI != UE; ++UI) {
1954     if (UI->getOpcode() != X86ISD::RET_FLAG)
1955       return false;
1956     HasRet = true;
1957   }
1958
1959   if (!HasRet)
1960     return false;
1961
1962   Chain = TCChain;
1963   return true;
1964 }
1965
1966 MVT
1967 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1968                                             ISD::NodeType ExtendKind) const {
1969   MVT ReturnMVT;
1970   // TODO: Is this also valid on 32-bit?
1971   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1972     ReturnMVT = MVT::i8;
1973   else
1974     ReturnMVT = MVT::i32;
1975
1976   MVT MinVT = getRegisterType(ReturnMVT);
1977   return VT.bitsLT(MinVT) ? MinVT : VT;
1978 }
1979
1980 /// LowerCallResult - Lower the result values of a call into the
1981 /// appropriate copies out of appropriate physical registers.
1982 ///
1983 SDValue
1984 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1985                                    CallingConv::ID CallConv, bool isVarArg,
1986                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1987                                    SDLoc dl, SelectionDAG &DAG,
1988                                    SmallVectorImpl<SDValue> &InVals) const {
1989
1990   // Assign locations to each value returned by this call.
1991   SmallVector<CCValAssign, 16> RVLocs;
1992   bool Is64Bit = Subtarget->is64Bit();
1993   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1994                  getTargetMachine(), RVLocs, *DAG.getContext());
1995   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1996
1997   // Copy all of the result registers out of their specified physreg.
1998   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1999     CCValAssign &VA = RVLocs[i];
2000     EVT CopyVT = VA.getValVT();
2001
2002     // If this is x86-64, and we disabled SSE, we can't return FP values
2003     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2004         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2005       report_fatal_error("SSE register return with SSE disabled");
2006     }
2007
2008     SDValue Val;
2009
2010     // If this is a call to a function that returns an fp value on the floating
2011     // point stack, we must guarantee the value is popped from the stack, so
2012     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2013     // if the return value is not used. We use the FpPOP_RETVAL instruction
2014     // instead.
2015     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2016       // If we prefer to use the value in xmm registers, copy it out as f80 and
2017       // use a truncate to move it from fp stack reg to xmm reg.
2018       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2019       SDValue Ops[] = { Chain, InFlag };
2020       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2021                                          MVT::Other, MVT::Glue, Ops), 1);
2022       Val = Chain.getValue(0);
2023
2024       // Round the f80 to the right size, which also moves it to the appropriate
2025       // xmm register.
2026       if (CopyVT != VA.getValVT())
2027         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2028                           // This truncation won't change the value.
2029                           DAG.getIntPtrConstant(1));
2030     } else {
2031       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2032                                  CopyVT, InFlag).getValue(1);
2033       Val = Chain.getValue(0);
2034     }
2035     InFlag = Chain.getValue(2);
2036     InVals.push_back(Val);
2037   }
2038
2039   return Chain;
2040 }
2041
2042 //===----------------------------------------------------------------------===//
2043 //                C & StdCall & Fast Calling Convention implementation
2044 //===----------------------------------------------------------------------===//
2045 //  StdCall calling convention seems to be standard for many Windows' API
2046 //  routines and around. It differs from C calling convention just a little:
2047 //  callee should clean up the stack, not caller. Symbols should be also
2048 //  decorated in some fancy way :) It doesn't support any vector arguments.
2049 //  For info on fast calling convention see Fast Calling Convention (tail call)
2050 //  implementation LowerX86_32FastCCCallTo.
2051
2052 /// CallIsStructReturn - Determines whether a call uses struct return
2053 /// semantics.
2054 enum StructReturnType {
2055   NotStructReturn,
2056   RegStructReturn,
2057   StackStructReturn
2058 };
2059 static StructReturnType
2060 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2061   if (Outs.empty())
2062     return NotStructReturn;
2063
2064   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2065   if (!Flags.isSRet())
2066     return NotStructReturn;
2067   if (Flags.isInReg())
2068     return RegStructReturn;
2069   return StackStructReturn;
2070 }
2071
2072 /// ArgsAreStructReturn - Determines whether a function uses struct
2073 /// return semantics.
2074 static StructReturnType
2075 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2076   if (Ins.empty())
2077     return NotStructReturn;
2078
2079   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2080   if (!Flags.isSRet())
2081     return NotStructReturn;
2082   if (Flags.isInReg())
2083     return RegStructReturn;
2084   return StackStructReturn;
2085 }
2086
2087 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2088 /// by "Src" to address "Dst" with size and alignment information specified by
2089 /// the specific parameter attribute. The copy will be passed as a byval
2090 /// function parameter.
2091 static SDValue
2092 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2093                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2094                           SDLoc dl) {
2095   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2096
2097   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2098                        /*isVolatile*/false, /*AlwaysInline=*/true,
2099                        MachinePointerInfo(), MachinePointerInfo());
2100 }
2101
2102 /// IsTailCallConvention - Return true if the calling convention is one that
2103 /// supports tail call optimization.
2104 static bool IsTailCallConvention(CallingConv::ID CC) {
2105   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2106           CC == CallingConv::HiPE);
2107 }
2108
2109 /// \brief Return true if the calling convention is a C calling convention.
2110 static bool IsCCallConvention(CallingConv::ID CC) {
2111   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2112           CC == CallingConv::X86_64_SysV);
2113 }
2114
2115 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2116   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2117     return false;
2118
2119   CallSite CS(CI);
2120   CallingConv::ID CalleeCC = CS.getCallingConv();
2121   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2122     return false;
2123
2124   return true;
2125 }
2126
2127 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2128 /// a tailcall target by changing its ABI.
2129 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2130                                    bool GuaranteedTailCallOpt) {
2131   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2132 }
2133
2134 SDValue
2135 X86TargetLowering::LowerMemArgument(SDValue Chain,
2136                                     CallingConv::ID CallConv,
2137                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2138                                     SDLoc dl, SelectionDAG &DAG,
2139                                     const CCValAssign &VA,
2140                                     MachineFrameInfo *MFI,
2141                                     unsigned i) const {
2142   // Create the nodes corresponding to a load from this parameter slot.
2143   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2144   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2145                               getTargetMachine().Options.GuaranteedTailCallOpt);
2146   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2147   EVT ValVT;
2148
2149   // If value is passed by pointer we have address passed instead of the value
2150   // itself.
2151   if (VA.getLocInfo() == CCValAssign::Indirect)
2152     ValVT = VA.getLocVT();
2153   else
2154     ValVT = VA.getValVT();
2155
2156   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2157   // changed with more analysis.
2158   // In case of tail call optimization mark all arguments mutable. Since they
2159   // could be overwritten by lowering of arguments in case of a tail call.
2160   if (Flags.isByVal()) {
2161     unsigned Bytes = Flags.getByValSize();
2162     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2163     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2164     return DAG.getFrameIndex(FI, getPointerTy());
2165   } else {
2166     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2167                                     VA.getLocMemOffset(), isImmutable);
2168     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2169     return DAG.getLoad(ValVT, dl, Chain, FIN,
2170                        MachinePointerInfo::getFixedStack(FI),
2171                        false, false, false, 0);
2172   }
2173 }
2174
2175 SDValue
2176 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2177                                         CallingConv::ID CallConv,
2178                                         bool isVarArg,
2179                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2180                                         SDLoc dl,
2181                                         SelectionDAG &DAG,
2182                                         SmallVectorImpl<SDValue> &InVals)
2183                                           const {
2184   MachineFunction &MF = DAG.getMachineFunction();
2185   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2186
2187   const Function* Fn = MF.getFunction();
2188   if (Fn->hasExternalLinkage() &&
2189       Subtarget->isTargetCygMing() &&
2190       Fn->getName() == "main")
2191     FuncInfo->setForceFramePointer(true);
2192
2193   MachineFrameInfo *MFI = MF.getFrameInfo();
2194   bool Is64Bit = Subtarget->is64Bit();
2195   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2196
2197   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2198          "Var args not supported with calling convention fastcc, ghc or hipe");
2199
2200   // Assign locations to all of the incoming arguments.
2201   SmallVector<CCValAssign, 16> ArgLocs;
2202   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2203                  ArgLocs, *DAG.getContext());
2204
2205   // Allocate shadow area for Win64
2206   if (IsWin64)
2207     CCInfo.AllocateStack(32, 8);
2208
2209   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2210
2211   unsigned LastVal = ~0U;
2212   SDValue ArgValue;
2213   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2214     CCValAssign &VA = ArgLocs[i];
2215     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2216     // places.
2217     assert(VA.getValNo() != LastVal &&
2218            "Don't support value assigned to multiple locs yet");
2219     (void)LastVal;
2220     LastVal = VA.getValNo();
2221
2222     if (VA.isRegLoc()) {
2223       EVT RegVT = VA.getLocVT();
2224       const TargetRegisterClass *RC;
2225       if (RegVT == MVT::i32)
2226         RC = &X86::GR32RegClass;
2227       else if (Is64Bit && RegVT == MVT::i64)
2228         RC = &X86::GR64RegClass;
2229       else if (RegVT == MVT::f32)
2230         RC = &X86::FR32RegClass;
2231       else if (RegVT == MVT::f64)
2232         RC = &X86::FR64RegClass;
2233       else if (RegVT.is512BitVector())
2234         RC = &X86::VR512RegClass;
2235       else if (RegVT.is256BitVector())
2236         RC = &X86::VR256RegClass;
2237       else if (RegVT.is128BitVector())
2238         RC = &X86::VR128RegClass;
2239       else if (RegVT == MVT::x86mmx)
2240         RC = &X86::VR64RegClass;
2241       else if (RegVT == MVT::i1)
2242         RC = &X86::VK1RegClass;
2243       else if (RegVT == MVT::v8i1)
2244         RC = &X86::VK8RegClass;
2245       else if (RegVT == MVT::v16i1)
2246         RC = &X86::VK16RegClass;
2247       else
2248         llvm_unreachable("Unknown argument type!");
2249
2250       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2251       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2252
2253       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2254       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2255       // right size.
2256       if (VA.getLocInfo() == CCValAssign::SExt)
2257         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2258                                DAG.getValueType(VA.getValVT()));
2259       else if (VA.getLocInfo() == CCValAssign::ZExt)
2260         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2261                                DAG.getValueType(VA.getValVT()));
2262       else if (VA.getLocInfo() == CCValAssign::BCvt)
2263         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2264
2265       if (VA.isExtInLoc()) {
2266         // Handle MMX values passed in XMM regs.
2267         if (RegVT.isVector())
2268           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2269         else
2270           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2271       }
2272     } else {
2273       assert(VA.isMemLoc());
2274       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2275     }
2276
2277     // If value is passed via pointer - do a load.
2278     if (VA.getLocInfo() == CCValAssign::Indirect)
2279       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2280                              MachinePointerInfo(), false, false, false, 0);
2281
2282     InVals.push_back(ArgValue);
2283   }
2284
2285   // The x86-64 ABIs require that for returning structs by value we copy
2286   // the sret argument into %rax/%eax (depending on ABI) for the return.
2287   // Win32 requires us to put the sret argument to %eax as well.
2288   // Save the argument into a virtual register so that we can access it
2289   // from the return points.
2290   if (MF.getFunction()->hasStructRetAttr() &&
2291       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2292     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2293     unsigned Reg = FuncInfo->getSRetReturnReg();
2294     if (!Reg) {
2295       MVT PtrTy = getPointerTy();
2296       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2297       FuncInfo->setSRetReturnReg(Reg);
2298     }
2299     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2300     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2301   }
2302
2303   unsigned StackSize = CCInfo.getNextStackOffset();
2304   // Align stack specially for tail calls.
2305   if (FuncIsMadeTailCallSafe(CallConv,
2306                              MF.getTarget().Options.GuaranteedTailCallOpt))
2307     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2308
2309   // If the function takes variable number of arguments, make a frame index for
2310   // the start of the first vararg value... for expansion of llvm.va_start.
2311   if (isVarArg) {
2312     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2313                     CallConv != CallingConv::X86_ThisCall)) {
2314       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2315     }
2316     if (Is64Bit) {
2317       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2318
2319       // FIXME: We should really autogenerate these arrays
2320       static const MCPhysReg GPR64ArgRegsWin64[] = {
2321         X86::RCX, X86::RDX, X86::R8,  X86::R9
2322       };
2323       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2324         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2325       };
2326       static const MCPhysReg XMMArgRegs64Bit[] = {
2327         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2328         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2329       };
2330       const MCPhysReg *GPR64ArgRegs;
2331       unsigned NumXMMRegs = 0;
2332
2333       if (IsWin64) {
2334         // The XMM registers which might contain var arg parameters are shadowed
2335         // in their paired GPR.  So we only need to save the GPR to their home
2336         // slots.
2337         TotalNumIntRegs = 4;
2338         GPR64ArgRegs = GPR64ArgRegsWin64;
2339       } else {
2340         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2341         GPR64ArgRegs = GPR64ArgRegs64Bit;
2342
2343         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2344                                                 TotalNumXMMRegs);
2345       }
2346       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2347                                                        TotalNumIntRegs);
2348
2349       bool NoImplicitFloatOps = Fn->getAttributes().
2350         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2351       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2352              "SSE register cannot be used when SSE is disabled!");
2353       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2354                NoImplicitFloatOps) &&
2355              "SSE register cannot be used when SSE is disabled!");
2356       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2357           !Subtarget->hasSSE1())
2358         // Kernel mode asks for SSE to be disabled, so don't push them
2359         // on the stack.
2360         TotalNumXMMRegs = 0;
2361
2362       if (IsWin64) {
2363         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2364         // Get to the caller-allocated home save location.  Add 8 to account
2365         // for the return address.
2366         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2367         FuncInfo->setRegSaveFrameIndex(
2368           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2369         // Fixup to set vararg frame on shadow area (4 x i64).
2370         if (NumIntRegs < 4)
2371           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2372       } else {
2373         // For X86-64, if there are vararg parameters that are passed via
2374         // registers, then we must store them to their spots on the stack so
2375         // they may be loaded by deferencing the result of va_next.
2376         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2377         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2378         FuncInfo->setRegSaveFrameIndex(
2379           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2380                                false));
2381       }
2382
2383       // Store the integer parameter registers.
2384       SmallVector<SDValue, 8> MemOps;
2385       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2386                                         getPointerTy());
2387       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2388       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2389         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2390                                   DAG.getIntPtrConstant(Offset));
2391         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2392                                      &X86::GR64RegClass);
2393         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2394         SDValue Store =
2395           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2396                        MachinePointerInfo::getFixedStack(
2397                          FuncInfo->getRegSaveFrameIndex(), Offset),
2398                        false, false, 0);
2399         MemOps.push_back(Store);
2400         Offset += 8;
2401       }
2402
2403       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2404         // Now store the XMM (fp + vector) parameter registers.
2405         SmallVector<SDValue, 11> SaveXMMOps;
2406         SaveXMMOps.push_back(Chain);
2407
2408         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2409         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2410         SaveXMMOps.push_back(ALVal);
2411
2412         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2413                                FuncInfo->getRegSaveFrameIndex()));
2414         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2415                                FuncInfo->getVarArgsFPOffset()));
2416
2417         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2418           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2419                                        &X86::VR128RegClass);
2420           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2421           SaveXMMOps.push_back(Val);
2422         }
2423         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2424                                      MVT::Other,
2425                                      &SaveXMMOps[0], SaveXMMOps.size()));
2426       }
2427
2428       if (!MemOps.empty())
2429         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2430                             &MemOps[0], MemOps.size());
2431     }
2432   }
2433
2434   // Some CCs need callee pop.
2435   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2436                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2437     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2438   } else {
2439     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2440     // If this is an sret function, the return should pop the hidden pointer.
2441     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2442         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2443         argsAreStructReturn(Ins) == StackStructReturn)
2444       FuncInfo->setBytesToPopOnReturn(4);
2445   }
2446
2447   if (!Is64Bit) {
2448     // RegSaveFrameIndex is X86-64 only.
2449     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2450     if (CallConv == CallingConv::X86_FastCall ||
2451         CallConv == CallingConv::X86_ThisCall)
2452       // fastcc functions can't have varargs.
2453       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2454   }
2455
2456   FuncInfo->setArgumentStackSize(StackSize);
2457
2458   return Chain;
2459 }
2460
2461 SDValue
2462 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2463                                     SDValue StackPtr, SDValue Arg,
2464                                     SDLoc dl, SelectionDAG &DAG,
2465                                     const CCValAssign &VA,
2466                                     ISD::ArgFlagsTy Flags) const {
2467   unsigned LocMemOffset = VA.getLocMemOffset();
2468   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2469   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2470   if (Flags.isByVal())
2471     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2472
2473   return DAG.getStore(Chain, dl, Arg, PtrOff,
2474                       MachinePointerInfo::getStack(LocMemOffset),
2475                       false, false, 0);
2476 }
2477
2478 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2479 /// optimization is performed and it is required.
2480 SDValue
2481 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2482                                            SDValue &OutRetAddr, SDValue Chain,
2483                                            bool IsTailCall, bool Is64Bit,
2484                                            int FPDiff, SDLoc dl) const {
2485   // Adjust the Return address stack slot.
2486   EVT VT = getPointerTy();
2487   OutRetAddr = getReturnAddressFrameIndex(DAG);
2488
2489   // Load the "old" Return address.
2490   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2491                            false, false, false, 0);
2492   return SDValue(OutRetAddr.getNode(), 1);
2493 }
2494
2495 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2496 /// optimization is performed and it is required (FPDiff!=0).
2497 static SDValue
2498 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2499                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2500                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2501   // Store the return address to the appropriate stack slot.
2502   if (!FPDiff) return Chain;
2503   // Calculate the new stack slot for the return address.
2504   int NewReturnAddrFI =
2505     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2506                                          false);
2507   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2508   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2509                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2510                        false, false, 0);
2511   return Chain;
2512 }
2513
2514 SDValue
2515 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2516                              SmallVectorImpl<SDValue> &InVals) const {
2517   SelectionDAG &DAG                     = CLI.DAG;
2518   SDLoc &dl                             = CLI.DL;
2519   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2520   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2521   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2522   SDValue Chain                         = CLI.Chain;
2523   SDValue Callee                        = CLI.Callee;
2524   CallingConv::ID CallConv              = CLI.CallConv;
2525   bool &isTailCall                      = CLI.IsTailCall;
2526   bool isVarArg                         = CLI.IsVarArg;
2527
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   bool Is64Bit        = Subtarget->is64Bit();
2530   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2531   StructReturnType SR = callIsStructReturn(Outs);
2532   bool IsSibcall      = false;
2533
2534   if (MF.getTarget().Options.DisableTailCalls)
2535     isTailCall = false;
2536
2537   if (isTailCall) {
2538     // Check if it's really possible to do a tail call.
2539     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2540                     isVarArg, SR != NotStructReturn,
2541                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2542                     Outs, OutVals, Ins, DAG);
2543
2544     // 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 MCPhysReg 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   unsigned NumNonConsts = 0;
5810   unsigned NumConsts = 0;
5811   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5812     SDValue In = Op.getOperand(idx);
5813     if (In.getOpcode() == ISD::UNDEF)
5814       continue;
5815     if (!isa<ConstantSDNode>(In)) {
5816       AllContants = false;
5817       NonConstIdx = idx;
5818       NumNonConsts++;
5819     }
5820     else {
5821       NumConsts++;
5822       if (cast<ConstantSDNode>(In)->getZExtValue())
5823       Immediate |= (1ULL << idx);
5824     }
5825     if (In != Op.getOperand(0))
5826       IsSplat = false;
5827   }
5828
5829   if (AllContants) {
5830     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5831       DAG.getConstant(Immediate, MVT::i16));
5832     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5833                        DAG.getIntPtrConstant(0));
5834   }
5835
5836   if (NumNonConsts == 1 && NonConstIdx != 0) {
5837     SDValue DstVec;
5838     if (NumConsts) {
5839       SDValue VecAsImm = DAG.getConstant(Immediate,
5840                                          MVT::getIntegerVT(VT.getSizeInBits()));
5841       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5842     }
5843     else 
5844       DstVec = DAG.getUNDEF(VT);
5845     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5846                        Op.getOperand(NonConstIdx),
5847                        DAG.getIntPtrConstant(NonConstIdx));
5848   }
5849   if (!IsSplat && (NonConstIdx != 0))
5850     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5851   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5852   SDValue Select;
5853   if (IsSplat)
5854     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5855                           DAG.getConstant(-1, SelectVT),
5856                           DAG.getConstant(0, SelectVT));
5857   else
5858     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5859                          DAG.getConstant((Immediate | 1), SelectVT),
5860                          DAG.getConstant(Immediate, SelectVT));
5861   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5862 }
5863
5864 SDValue
5865 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5866   SDLoc dl(Op);
5867
5868   MVT VT = Op.getSimpleValueType();
5869   MVT ExtVT = VT.getVectorElementType();
5870   unsigned NumElems = Op.getNumOperands();
5871
5872   // Generate vectors for predicate vectors.
5873   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5874     return LowerBUILD_VECTORvXi1(Op, DAG);
5875
5876   // Vectors containing all zeros can be matched by pxor and xorps later
5877   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5878     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5879     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5880     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5881       return Op;
5882
5883     return getZeroVector(VT, Subtarget, DAG, dl);
5884   }
5885
5886   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5887   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5888   // vpcmpeqd on 256-bit vectors.
5889   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5890     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5891       return Op;
5892
5893     if (!VT.is512BitVector())
5894       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5895   }
5896
5897   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5898   if (Broadcast.getNode())
5899     return Broadcast;
5900
5901   unsigned EVTBits = ExtVT.getSizeInBits();
5902
5903   unsigned NumZero  = 0;
5904   unsigned NumNonZero = 0;
5905   unsigned NonZeros = 0;
5906   bool IsAllConstants = true;
5907   SmallSet<SDValue, 8> Values;
5908   for (unsigned i = 0; i < NumElems; ++i) {
5909     SDValue Elt = Op.getOperand(i);
5910     if (Elt.getOpcode() == ISD::UNDEF)
5911       continue;
5912     Values.insert(Elt);
5913     if (Elt.getOpcode() != ISD::Constant &&
5914         Elt.getOpcode() != ISD::ConstantFP)
5915       IsAllConstants = false;
5916     if (X86::isZeroNode(Elt))
5917       NumZero++;
5918     else {
5919       NonZeros |= (1 << i);
5920       NumNonZero++;
5921     }
5922   }
5923
5924   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5925   if (NumNonZero == 0)
5926     return DAG.getUNDEF(VT);
5927
5928   // Special case for single non-zero, non-undef, element.
5929   if (NumNonZero == 1) {
5930     unsigned Idx = countTrailingZeros(NonZeros);
5931     SDValue Item = Op.getOperand(Idx);
5932
5933     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5934     // the value are obviously zero, truncate the value to i32 and do the
5935     // insertion that way.  Only do this if the value is non-constant or if the
5936     // value is a constant being inserted into element 0.  It is cheaper to do
5937     // a constant pool load than it is to do a movd + shuffle.
5938     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5939         (!IsAllConstants || Idx == 0)) {
5940       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5941         // Handle SSE only.
5942         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5943         EVT VecVT = MVT::v4i32;
5944         unsigned VecElts = 4;
5945
5946         // Truncate the value (which may itself be a constant) to i32, and
5947         // convert it to a vector with movd (S2V+shuffle to zero extend).
5948         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5949         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5950         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5951
5952         // Now we have our 32-bit value zero extended in the low element of
5953         // a vector.  If Idx != 0, swizzle it into place.
5954         if (Idx != 0) {
5955           SmallVector<int, 4> Mask;
5956           Mask.push_back(Idx);
5957           for (unsigned i = 1; i != VecElts; ++i)
5958             Mask.push_back(i);
5959           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5960                                       &Mask[0]);
5961         }
5962         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5963       }
5964     }
5965
5966     // If we have a constant or non-constant insertion into the low element of
5967     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5968     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5969     // depending on what the source datatype is.
5970     if (Idx == 0) {
5971       if (NumZero == 0)
5972         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5973
5974       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5975           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5976         if (VT.is256BitVector() || VT.is512BitVector()) {
5977           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5978           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5979                              Item, DAG.getIntPtrConstant(0));
5980         }
5981         assert(VT.is128BitVector() && "Expected an SSE value type!");
5982         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5983         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5984         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5985       }
5986
5987       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5988         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5989         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5990         if (VT.is256BitVector()) {
5991           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5992           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5993         } else {
5994           assert(VT.is128BitVector() && "Expected an SSE value type!");
5995           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5996         }
5997         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5998       }
5999     }
6000
6001     // Is it a vector logical left shift?
6002     if (NumElems == 2 && Idx == 1 &&
6003         X86::isZeroNode(Op.getOperand(0)) &&
6004         !X86::isZeroNode(Op.getOperand(1))) {
6005       unsigned NumBits = VT.getSizeInBits();
6006       return getVShift(true, VT,
6007                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6008                                    VT, Op.getOperand(1)),
6009                        NumBits/2, DAG, *this, dl);
6010     }
6011
6012     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6013       return SDValue();
6014
6015     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6016     // is a non-constant being inserted into an element other than the low one,
6017     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6018     // movd/movss) to move this into the low element, then shuffle it into
6019     // place.
6020     if (EVTBits == 32) {
6021       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6022
6023       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6024       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6025       SmallVector<int, 8> MaskVec;
6026       for (unsigned i = 0; i != NumElems; ++i)
6027         MaskVec.push_back(i == Idx ? 0 : 1);
6028       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6029     }
6030   }
6031
6032   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6033   if (Values.size() == 1) {
6034     if (EVTBits == 32) {
6035       // Instead of a shuffle like this:
6036       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6037       // Check if it's possible to issue this instead.
6038       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6039       unsigned Idx = countTrailingZeros(NonZeros);
6040       SDValue Item = Op.getOperand(Idx);
6041       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6042         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6043     }
6044     return SDValue();
6045   }
6046
6047   // A vector full of immediates; various special cases are already
6048   // handled, so this is best done with a single constant-pool load.
6049   if (IsAllConstants)
6050     return SDValue();
6051
6052   // For AVX-length vectors, build the individual 128-bit pieces and use
6053   // shuffles to put them in place.
6054   if (VT.is256BitVector() || VT.is512BitVector()) {
6055     SmallVector<SDValue, 64> V;
6056     for (unsigned i = 0; i != NumElems; ++i)
6057       V.push_back(Op.getOperand(i));
6058
6059     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6060
6061     // Build both the lower and upper subvector.
6062     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6063     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6064                                 NumElems/2);
6065
6066     // Recreate the wider vector with the lower and upper part.
6067     if (VT.is256BitVector())
6068       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6069     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6070   }
6071
6072   // Let legalizer expand 2-wide build_vectors.
6073   if (EVTBits == 64) {
6074     if (NumNonZero == 1) {
6075       // One half is zero or undef.
6076       unsigned Idx = countTrailingZeros(NonZeros);
6077       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6078                                  Op.getOperand(Idx));
6079       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6080     }
6081     return SDValue();
6082   }
6083
6084   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6085   if (EVTBits == 8 && NumElems == 16) {
6086     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6087                                         Subtarget, *this);
6088     if (V.getNode()) return V;
6089   }
6090
6091   if (EVTBits == 16 && NumElems == 8) {
6092     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6093                                       Subtarget, *this);
6094     if (V.getNode()) return V;
6095   }
6096
6097   // If element VT is == 32 bits, turn it into a number of shuffles.
6098   SmallVector<SDValue, 8> V(NumElems);
6099   if (NumElems == 4 && NumZero > 0) {
6100     for (unsigned i = 0; i < 4; ++i) {
6101       bool isZero = !(NonZeros & (1 << i));
6102       if (isZero)
6103         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6104       else
6105         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6106     }
6107
6108     for (unsigned i = 0; i < 2; ++i) {
6109       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6110         default: break;
6111         case 0:
6112           V[i] = V[i*2];  // Must be a zero vector.
6113           break;
6114         case 1:
6115           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6116           break;
6117         case 2:
6118           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6119           break;
6120         case 3:
6121           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6122           break;
6123       }
6124     }
6125
6126     bool Reverse1 = (NonZeros & 0x3) == 2;
6127     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6128     int MaskVec[] = {
6129       Reverse1 ? 1 : 0,
6130       Reverse1 ? 0 : 1,
6131       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6132       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6133     };
6134     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6135   }
6136
6137   if (Values.size() > 1 && VT.is128BitVector()) {
6138     // Check for a build vector of consecutive loads.
6139     for (unsigned i = 0; i < NumElems; ++i)
6140       V[i] = Op.getOperand(i);
6141
6142     // Check for elements which are consecutive loads.
6143     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6144     if (LD.getNode())
6145       return LD;
6146
6147     // Check for a build vector from mostly shuffle plus few inserting.
6148     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6149     if (Sh.getNode())
6150       return Sh;
6151
6152     // For SSE 4.1, use insertps to put the high elements into the low element.
6153     if (getSubtarget()->hasSSE41()) {
6154       SDValue Result;
6155       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6156         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6157       else
6158         Result = DAG.getUNDEF(VT);
6159
6160       for (unsigned i = 1; i < NumElems; ++i) {
6161         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6162         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6163                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6164       }
6165       return Result;
6166     }
6167
6168     // Otherwise, expand into a number of unpckl*, start by extending each of
6169     // our (non-undef) elements to the full vector width with the element in the
6170     // bottom slot of the vector (which generates no code for SSE).
6171     for (unsigned i = 0; i < NumElems; ++i) {
6172       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6173         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6174       else
6175         V[i] = DAG.getUNDEF(VT);
6176     }
6177
6178     // Next, we iteratively mix elements, e.g. for v4f32:
6179     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6180     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6181     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6182     unsigned EltStride = NumElems >> 1;
6183     while (EltStride != 0) {
6184       for (unsigned i = 0; i < EltStride; ++i) {
6185         // If V[i+EltStride] is undef and this is the first round of mixing,
6186         // then it is safe to just drop this shuffle: V[i] is already in the
6187         // right place, the one element (since it's the first round) being
6188         // inserted as undef can be dropped.  This isn't safe for successive
6189         // rounds because they will permute elements within both vectors.
6190         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6191             EltStride == NumElems/2)
6192           continue;
6193
6194         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6195       }
6196       EltStride >>= 1;
6197     }
6198     return V[0];
6199   }
6200   return SDValue();
6201 }
6202
6203 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6204 // to create 256-bit vectors from two other 128-bit ones.
6205 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6206   SDLoc dl(Op);
6207   MVT ResVT = Op.getSimpleValueType();
6208
6209   assert((ResVT.is256BitVector() ||
6210           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6211
6212   SDValue V1 = Op.getOperand(0);
6213   SDValue V2 = Op.getOperand(1);
6214   unsigned NumElems = ResVT.getVectorNumElements();
6215   if(ResVT.is256BitVector())
6216     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6217
6218   if (Op.getNumOperands() == 4) {
6219     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6220                                 ResVT.getVectorNumElements()/2);
6221     SDValue V3 = Op.getOperand(2);
6222     SDValue V4 = Op.getOperand(3);
6223     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6224       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6225   }
6226   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6227 }
6228
6229 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6230   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6231   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6232          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6233           Op.getNumOperands() == 4)));
6234
6235   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6236   // from two other 128-bit ones.
6237
6238   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6239   return LowerAVXCONCAT_VECTORS(Op, DAG);
6240 }
6241
6242 // Try to lower a shuffle node into a simple blend instruction.
6243 static SDValue
6244 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6245                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6246   SDValue V1 = SVOp->getOperand(0);
6247   SDValue V2 = SVOp->getOperand(1);
6248   SDLoc dl(SVOp);
6249   MVT VT = SVOp->getSimpleValueType(0);
6250   MVT EltVT = VT.getVectorElementType();
6251   unsigned NumElems = VT.getVectorNumElements();
6252
6253   // There is no blend with immediate in AVX-512.
6254   if (VT.is512BitVector())
6255     return SDValue();
6256
6257   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6258     return SDValue();
6259   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6260     return SDValue();
6261
6262   // Check the mask for BLEND and build the value.
6263   unsigned MaskValue = 0;
6264   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6265   unsigned NumLanes = (NumElems-1)/8 + 1;
6266   unsigned NumElemsInLane = NumElems / NumLanes;
6267
6268   // Blend for v16i16 should be symetric for the both lanes.
6269   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6270
6271     int SndLaneEltIdx = (NumLanes == 2) ?
6272       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6273     int EltIdx = SVOp->getMaskElt(i);
6274
6275     if ((EltIdx < 0 || EltIdx == (int)i) &&
6276         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6277       continue;
6278
6279     if (((unsigned)EltIdx == (i + NumElems)) &&
6280         (SndLaneEltIdx < 0 ||
6281          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6282       MaskValue |= (1<<i);
6283     else
6284       return SDValue();
6285   }
6286
6287   // Convert i32 vectors to floating point if it is not AVX2.
6288   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6289   MVT BlendVT = VT;
6290   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6291     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6292                                NumElems);
6293     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6294     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6295   }
6296
6297   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6298                             DAG.getConstant(MaskValue, MVT::i32));
6299   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6300 }
6301
6302 /// In vector type \p VT, return true if the element at index \p InputIdx
6303 /// falls on a different 128-bit lane than \p OutputIdx.
6304 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6305                                      unsigned OutputIdx) {
6306   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6307   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6308 }
6309
6310 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6311 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6312 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6313 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6314 /// zero.
6315 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6316                          SelectionDAG &DAG) {
6317   MVT VT = V1.getSimpleValueType();
6318   assert(VT.is128BitVector() || VT.is256BitVector());
6319
6320   MVT EltVT = VT.getVectorElementType();
6321   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6322   unsigned NumElts = VT.getVectorNumElements();
6323
6324   SmallVector<SDValue, 32> PshufbMask;
6325   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6326     int InputIdx = MaskVals[OutputIdx];
6327     unsigned InputByteIdx;
6328
6329     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6330       InputByteIdx = 0x80;
6331     else {
6332       // Cross lane is not allowed.
6333       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6334         return SDValue();
6335       InputByteIdx = InputIdx * EltSizeInBytes;
6336       // Index is an byte offset within the 128-bit lane.
6337       InputByteIdx &= 0xf;
6338     }
6339
6340     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6341       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6342       if (InputByteIdx != 0x80)
6343         ++InputByteIdx;
6344     }
6345   }
6346
6347   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6348   if (ShufVT != VT)
6349     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6350   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6351                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6352                                  PshufbMask.data(), PshufbMask.size()));
6353 }
6354
6355 // v8i16 shuffles - Prefer shuffles in the following order:
6356 // 1. [all]   pshuflw, pshufhw, optional move
6357 // 2. [ssse3] 1 x pshufb
6358 // 3. [ssse3] 2 x pshufb + 1 x por
6359 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6360 static SDValue
6361 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6362                          SelectionDAG &DAG) {
6363   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6364   SDValue V1 = SVOp->getOperand(0);
6365   SDValue V2 = SVOp->getOperand(1);
6366   SDLoc dl(SVOp);
6367   SmallVector<int, 8> MaskVals;
6368
6369   // Determine if more than 1 of the words in each of the low and high quadwords
6370   // of the result come from the same quadword of one of the two inputs.  Undef
6371   // mask values count as coming from any quadword, for better codegen.
6372   //
6373   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6374   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6375   unsigned LoQuad[] = { 0, 0, 0, 0 };
6376   unsigned HiQuad[] = { 0, 0, 0, 0 };
6377   // Indices of quads used.
6378   std::bitset<4> InputQuads;
6379   for (unsigned i = 0; i < 8; ++i) {
6380     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6381     int EltIdx = SVOp->getMaskElt(i);
6382     MaskVals.push_back(EltIdx);
6383     if (EltIdx < 0) {
6384       ++Quad[0];
6385       ++Quad[1];
6386       ++Quad[2];
6387       ++Quad[3];
6388       continue;
6389     }
6390     ++Quad[EltIdx / 4];
6391     InputQuads.set(EltIdx / 4);
6392   }
6393
6394   int BestLoQuad = -1;
6395   unsigned MaxQuad = 1;
6396   for (unsigned i = 0; i < 4; ++i) {
6397     if (LoQuad[i] > MaxQuad) {
6398       BestLoQuad = i;
6399       MaxQuad = LoQuad[i];
6400     }
6401   }
6402
6403   int BestHiQuad = -1;
6404   MaxQuad = 1;
6405   for (unsigned i = 0; i < 4; ++i) {
6406     if (HiQuad[i] > MaxQuad) {
6407       BestHiQuad = i;
6408       MaxQuad = HiQuad[i];
6409     }
6410   }
6411
6412   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6413   // of the two input vectors, shuffle them into one input vector so only a
6414   // single pshufb instruction is necessary. If there are more than 2 input
6415   // quads, disable the next transformation since it does not help SSSE3.
6416   bool V1Used = InputQuads[0] || InputQuads[1];
6417   bool V2Used = InputQuads[2] || InputQuads[3];
6418   if (Subtarget->hasSSSE3()) {
6419     if (InputQuads.count() == 2 && V1Used && V2Used) {
6420       BestLoQuad = InputQuads[0] ? 0 : 1;
6421       BestHiQuad = InputQuads[2] ? 2 : 3;
6422     }
6423     if (InputQuads.count() > 2) {
6424       BestLoQuad = -1;
6425       BestHiQuad = -1;
6426     }
6427   }
6428
6429   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6430   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6431   // words from all 4 input quadwords.
6432   SDValue NewV;
6433   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6434     int MaskV[] = {
6435       BestLoQuad < 0 ? 0 : BestLoQuad,
6436       BestHiQuad < 0 ? 1 : BestHiQuad
6437     };
6438     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6439                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6440                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6441     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6442
6443     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6444     // source words for the shuffle, to aid later transformations.
6445     bool AllWordsInNewV = true;
6446     bool InOrder[2] = { true, true };
6447     for (unsigned i = 0; i != 8; ++i) {
6448       int idx = MaskVals[i];
6449       if (idx != (int)i)
6450         InOrder[i/4] = false;
6451       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6452         continue;
6453       AllWordsInNewV = false;
6454       break;
6455     }
6456
6457     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6458     if (AllWordsInNewV) {
6459       for (int i = 0; i != 8; ++i) {
6460         int idx = MaskVals[i];
6461         if (idx < 0)
6462           continue;
6463         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6464         if ((idx != i) && idx < 4)
6465           pshufhw = false;
6466         if ((idx != i) && idx > 3)
6467           pshuflw = false;
6468       }
6469       V1 = NewV;
6470       V2Used = false;
6471       BestLoQuad = 0;
6472       BestHiQuad = 1;
6473     }
6474
6475     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6476     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6477     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6478       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6479       unsigned TargetMask = 0;
6480       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6481                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6482       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6483       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6484                              getShufflePSHUFLWImmediate(SVOp);
6485       V1 = NewV.getOperand(0);
6486       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6487     }
6488   }
6489
6490   // Promote splats to a larger type which usually leads to more efficient code.
6491   // FIXME: Is this true if pshufb is available?
6492   if (SVOp->isSplat())
6493     return PromoteSplat(SVOp, DAG);
6494
6495   // If we have SSSE3, and all words of the result are from 1 input vector,
6496   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6497   // is present, fall back to case 4.
6498   if (Subtarget->hasSSSE3()) {
6499     SmallVector<SDValue,16> pshufbMask;
6500
6501     // If we have elements from both input vectors, set the high bit of the
6502     // shuffle mask element to zero out elements that come from V2 in the V1
6503     // mask, and elements that come from V1 in the V2 mask, so that the two
6504     // results can be OR'd together.
6505     bool TwoInputs = V1Used && V2Used;
6506     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6507     if (!TwoInputs)
6508       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6509
6510     // Calculate the shuffle mask for the second input, shuffle it, and
6511     // OR it with the first shuffled input.
6512     CommuteVectorShuffleMask(MaskVals, 8);
6513     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6514     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6515     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6516   }
6517
6518   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6519   // and update MaskVals with new element order.
6520   std::bitset<8> InOrder;
6521   if (BestLoQuad >= 0) {
6522     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6523     for (int i = 0; i != 4; ++i) {
6524       int idx = MaskVals[i];
6525       if (idx < 0) {
6526         InOrder.set(i);
6527       } else if ((idx / 4) == BestLoQuad) {
6528         MaskV[i] = idx & 3;
6529         InOrder.set(i);
6530       }
6531     }
6532     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6533                                 &MaskV[0]);
6534
6535     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6536       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6537       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6538                                   NewV.getOperand(0),
6539                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6540     }
6541   }
6542
6543   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6544   // and update MaskVals with the new element order.
6545   if (BestHiQuad >= 0) {
6546     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6547     for (unsigned i = 4; i != 8; ++i) {
6548       int idx = MaskVals[i];
6549       if (idx < 0) {
6550         InOrder.set(i);
6551       } else if ((idx / 4) == BestHiQuad) {
6552         MaskV[i] = (idx & 3) + 4;
6553         InOrder.set(i);
6554       }
6555     }
6556     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6557                                 &MaskV[0]);
6558
6559     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6560       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6561       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6562                                   NewV.getOperand(0),
6563                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6564     }
6565   }
6566
6567   // In case BestHi & BestLo were both -1, which means each quadword has a word
6568   // from each of the four input quadwords, calculate the InOrder bitvector now
6569   // before falling through to the insert/extract cleanup.
6570   if (BestLoQuad == -1 && BestHiQuad == -1) {
6571     NewV = V1;
6572     for (int i = 0; i != 8; ++i)
6573       if (MaskVals[i] < 0 || MaskVals[i] == i)
6574         InOrder.set(i);
6575   }
6576
6577   // The other elements are put in the right place using pextrw and pinsrw.
6578   for (unsigned i = 0; i != 8; ++i) {
6579     if (InOrder[i])
6580       continue;
6581     int EltIdx = MaskVals[i];
6582     if (EltIdx < 0)
6583       continue;
6584     SDValue ExtOp = (EltIdx < 8) ?
6585       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6586                   DAG.getIntPtrConstant(EltIdx)) :
6587       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6588                   DAG.getIntPtrConstant(EltIdx - 8));
6589     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6590                        DAG.getIntPtrConstant(i));
6591   }
6592   return NewV;
6593 }
6594
6595 /// \brief v16i16 shuffles
6596 ///
6597 /// FIXME: We only support generation of a single pshufb currently.  We can
6598 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6599 /// well (e.g 2 x pshufb + 1 x por).
6600 static SDValue
6601 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6602   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6603   SDValue V1 = SVOp->getOperand(0);
6604   SDValue V2 = SVOp->getOperand(1);
6605   SDLoc dl(SVOp);
6606
6607   if (V2.getOpcode() != ISD::UNDEF)
6608     return SDValue();
6609
6610   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6611   return getPSHUFB(MaskVals, V1, dl, DAG);
6612 }
6613
6614 // v16i8 shuffles - Prefer shuffles in the following order:
6615 // 1. [ssse3] 1 x pshufb
6616 // 2. [ssse3] 2 x pshufb + 1 x por
6617 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6618 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6619                                         const X86Subtarget* Subtarget,
6620                                         SelectionDAG &DAG) {
6621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6622   SDValue V1 = SVOp->getOperand(0);
6623   SDValue V2 = SVOp->getOperand(1);
6624   SDLoc dl(SVOp);
6625   ArrayRef<int> MaskVals = SVOp->getMask();
6626
6627   // Promote splats to a larger type which usually leads to more efficient code.
6628   // FIXME: Is this true if pshufb is available?
6629   if (SVOp->isSplat())
6630     return PromoteSplat(SVOp, DAG);
6631
6632   // If we have SSSE3, case 1 is generated when all result bytes come from
6633   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6634   // present, fall back to case 3.
6635
6636   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6637   if (Subtarget->hasSSSE3()) {
6638     SmallVector<SDValue,16> pshufbMask;
6639
6640     // If all result elements are from one input vector, then only translate
6641     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6642     //
6643     // Otherwise, we have elements from both input vectors, and must zero out
6644     // elements that come from V2 in the first mask, and V1 in the second mask
6645     // so that we can OR them together.
6646     for (unsigned i = 0; i != 16; ++i) {
6647       int EltIdx = MaskVals[i];
6648       if (EltIdx < 0 || EltIdx >= 16)
6649         EltIdx = 0x80;
6650       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6651     }
6652     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6653                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6654                                  MVT::v16i8, &pshufbMask[0], 16));
6655
6656     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6657     // the 2nd operand if it's undefined or zero.
6658     if (V2.getOpcode() == ISD::UNDEF ||
6659         ISD::isBuildVectorAllZeros(V2.getNode()))
6660       return V1;
6661
6662     // Calculate the shuffle mask for the second input, shuffle it, and
6663     // OR it with the first shuffled input.
6664     pshufbMask.clear();
6665     for (unsigned i = 0; i != 16; ++i) {
6666       int EltIdx = MaskVals[i];
6667       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6668       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6669     }
6670     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6671                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6672                                  MVT::v16i8, &pshufbMask[0], 16));
6673     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6674   }
6675
6676   // No SSSE3 - Calculate in place words and then fix all out of place words
6677   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6678   // the 16 different words that comprise the two doublequadword input vectors.
6679   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6680   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6681   SDValue NewV = V1;
6682   for (int i = 0; i != 8; ++i) {
6683     int Elt0 = MaskVals[i*2];
6684     int Elt1 = MaskVals[i*2+1];
6685
6686     // This word of the result is all undef, skip it.
6687     if (Elt0 < 0 && Elt1 < 0)
6688       continue;
6689
6690     // This word of the result is already in the correct place, skip it.
6691     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6692       continue;
6693
6694     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6695     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6696     SDValue InsElt;
6697
6698     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6699     // using a single extract together, load it and store it.
6700     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6701       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6702                            DAG.getIntPtrConstant(Elt1 / 2));
6703       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6704                         DAG.getIntPtrConstant(i));
6705       continue;
6706     }
6707
6708     // If Elt1 is defined, extract it from the appropriate source.  If the
6709     // source byte is not also odd, shift the extracted word left 8 bits
6710     // otherwise clear the bottom 8 bits if we need to do an or.
6711     if (Elt1 >= 0) {
6712       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6713                            DAG.getIntPtrConstant(Elt1 / 2));
6714       if ((Elt1 & 1) == 0)
6715         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6716                              DAG.getConstant(8,
6717                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6718       else if (Elt0 >= 0)
6719         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6720                              DAG.getConstant(0xFF00, MVT::i16));
6721     }
6722     // If Elt0 is defined, extract it from the appropriate source.  If the
6723     // source byte is not also even, shift the extracted word right 8 bits. If
6724     // Elt1 was also defined, OR the extracted values together before
6725     // inserting them in the result.
6726     if (Elt0 >= 0) {
6727       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6728                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6729       if ((Elt0 & 1) != 0)
6730         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6731                               DAG.getConstant(8,
6732                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6733       else if (Elt1 >= 0)
6734         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6735                              DAG.getConstant(0x00FF, MVT::i16));
6736       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6737                          : InsElt0;
6738     }
6739     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6740                        DAG.getIntPtrConstant(i));
6741   }
6742   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6743 }
6744
6745 // v32i8 shuffles - Translate to VPSHUFB if possible.
6746 static
6747 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6748                                  const X86Subtarget *Subtarget,
6749                                  SelectionDAG &DAG) {
6750   MVT VT = SVOp->getSimpleValueType(0);
6751   SDValue V1 = SVOp->getOperand(0);
6752   SDValue V2 = SVOp->getOperand(1);
6753   SDLoc dl(SVOp);
6754   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6755
6756   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6757   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6758   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6759
6760   // VPSHUFB may be generated if
6761   // (1) one of input vector is undefined or zeroinitializer.
6762   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6763   // And (2) the mask indexes don't cross the 128-bit lane.
6764   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6765       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6766     return SDValue();
6767
6768   if (V1IsAllZero && !V2IsAllZero) {
6769     CommuteVectorShuffleMask(MaskVals, 32);
6770     V1 = V2;
6771   }
6772   return getPSHUFB(MaskVals, V1, dl, DAG);
6773 }
6774
6775 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6776 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6777 /// done when every pair / quad of shuffle mask elements point to elements in
6778 /// the right sequence. e.g.
6779 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6780 static
6781 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6782                                  SelectionDAG &DAG) {
6783   MVT VT = SVOp->getSimpleValueType(0);
6784   SDLoc dl(SVOp);
6785   unsigned NumElems = VT.getVectorNumElements();
6786   MVT NewVT;
6787   unsigned Scale;
6788   switch (VT.SimpleTy) {
6789   default: llvm_unreachable("Unexpected!");
6790   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6791   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6792   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6793   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6794   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6795   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6796   }
6797
6798   SmallVector<int, 8> MaskVec;
6799   for (unsigned i = 0; i != NumElems; i += Scale) {
6800     int StartIdx = -1;
6801     for (unsigned j = 0; j != Scale; ++j) {
6802       int EltIdx = SVOp->getMaskElt(i+j);
6803       if (EltIdx < 0)
6804         continue;
6805       if (StartIdx < 0)
6806         StartIdx = (EltIdx / Scale);
6807       if (EltIdx != (int)(StartIdx*Scale + j))
6808         return SDValue();
6809     }
6810     MaskVec.push_back(StartIdx);
6811   }
6812
6813   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6814   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6815   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6816 }
6817
6818 /// getVZextMovL - Return a zero-extending vector move low node.
6819 ///
6820 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6821                             SDValue SrcOp, SelectionDAG &DAG,
6822                             const X86Subtarget *Subtarget, SDLoc dl) {
6823   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6824     LoadSDNode *LD = NULL;
6825     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6826       LD = dyn_cast<LoadSDNode>(SrcOp);
6827     if (!LD) {
6828       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6829       // instead.
6830       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6831       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6832           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6833           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6834           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6835         // PR2108
6836         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6837         return DAG.getNode(ISD::BITCAST, dl, VT,
6838                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6839                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6840                                                    OpVT,
6841                                                    SrcOp.getOperand(0)
6842                                                           .getOperand(0))));
6843       }
6844     }
6845   }
6846
6847   return DAG.getNode(ISD::BITCAST, dl, VT,
6848                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6849                                  DAG.getNode(ISD::BITCAST, dl,
6850                                              OpVT, SrcOp)));
6851 }
6852
6853 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6854 /// which could not be matched by any known target speficic shuffle
6855 static SDValue
6856 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6857
6858   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6859   if (NewOp.getNode())
6860     return NewOp;
6861
6862   MVT VT = SVOp->getSimpleValueType(0);
6863
6864   unsigned NumElems = VT.getVectorNumElements();
6865   unsigned NumLaneElems = NumElems / 2;
6866
6867   SDLoc dl(SVOp);
6868   MVT EltVT = VT.getVectorElementType();
6869   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6870   SDValue Output[2];
6871
6872   SmallVector<int, 16> Mask;
6873   for (unsigned l = 0; l < 2; ++l) {
6874     // Build a shuffle mask for the output, discovering on the fly which
6875     // input vectors to use as shuffle operands (recorded in InputUsed).
6876     // If building a suitable shuffle vector proves too hard, then bail
6877     // out with UseBuildVector set.
6878     bool UseBuildVector = false;
6879     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6880     unsigned LaneStart = l * NumLaneElems;
6881     for (unsigned i = 0; i != NumLaneElems; ++i) {
6882       // The mask element.  This indexes into the input.
6883       int Idx = SVOp->getMaskElt(i+LaneStart);
6884       if (Idx < 0) {
6885         // the mask element does not index into any input vector.
6886         Mask.push_back(-1);
6887         continue;
6888       }
6889
6890       // The input vector this mask element indexes into.
6891       int Input = Idx / NumLaneElems;
6892
6893       // Turn the index into an offset from the start of the input vector.
6894       Idx -= Input * NumLaneElems;
6895
6896       // Find or create a shuffle vector operand to hold this input.
6897       unsigned OpNo;
6898       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6899         if (InputUsed[OpNo] == Input)
6900           // This input vector is already an operand.
6901           break;
6902         if (InputUsed[OpNo] < 0) {
6903           // Create a new operand for this input vector.
6904           InputUsed[OpNo] = Input;
6905           break;
6906         }
6907       }
6908
6909       if (OpNo >= array_lengthof(InputUsed)) {
6910         // More than two input vectors used!  Give up on trying to create a
6911         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6912         UseBuildVector = true;
6913         break;
6914       }
6915
6916       // Add the mask index for the new shuffle vector.
6917       Mask.push_back(Idx + OpNo * NumLaneElems);
6918     }
6919
6920     if (UseBuildVector) {
6921       SmallVector<SDValue, 16> SVOps;
6922       for (unsigned i = 0; i != NumLaneElems; ++i) {
6923         // The mask element.  This indexes into the input.
6924         int Idx = SVOp->getMaskElt(i+LaneStart);
6925         if (Idx < 0) {
6926           SVOps.push_back(DAG.getUNDEF(EltVT));
6927           continue;
6928         }
6929
6930         // The input vector this mask element indexes into.
6931         int Input = Idx / NumElems;
6932
6933         // Turn the index into an offset from the start of the input vector.
6934         Idx -= Input * NumElems;
6935
6936         // Extract the vector element by hand.
6937         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6938                                     SVOp->getOperand(Input),
6939                                     DAG.getIntPtrConstant(Idx)));
6940       }
6941
6942       // Construct the output using a BUILD_VECTOR.
6943       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6944                               SVOps.size());
6945     } else if (InputUsed[0] < 0) {
6946       // No input vectors were used! The result is undefined.
6947       Output[l] = DAG.getUNDEF(NVT);
6948     } else {
6949       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6950                                         (InputUsed[0] % 2) * NumLaneElems,
6951                                         DAG, dl);
6952       // If only one input was used, use an undefined vector for the other.
6953       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6954         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6955                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6956       // At least one input vector was used. Create a new shuffle vector.
6957       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6958     }
6959
6960     Mask.clear();
6961   }
6962
6963   // Concatenate the result back
6964   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6965 }
6966
6967 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6968 /// 4 elements, and match them with several different shuffle types.
6969 static SDValue
6970 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6971   SDValue V1 = SVOp->getOperand(0);
6972   SDValue V2 = SVOp->getOperand(1);
6973   SDLoc dl(SVOp);
6974   MVT VT = SVOp->getSimpleValueType(0);
6975
6976   assert(VT.is128BitVector() && "Unsupported vector size");
6977
6978   std::pair<int, int> Locs[4];
6979   int Mask1[] = { -1, -1, -1, -1 };
6980   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6981
6982   unsigned NumHi = 0;
6983   unsigned NumLo = 0;
6984   for (unsigned i = 0; i != 4; ++i) {
6985     int Idx = PermMask[i];
6986     if (Idx < 0) {
6987       Locs[i] = std::make_pair(-1, -1);
6988     } else {
6989       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6990       if (Idx < 4) {
6991         Locs[i] = std::make_pair(0, NumLo);
6992         Mask1[NumLo] = Idx;
6993         NumLo++;
6994       } else {
6995         Locs[i] = std::make_pair(1, NumHi);
6996         if (2+NumHi < 4)
6997           Mask1[2+NumHi] = Idx;
6998         NumHi++;
6999       }
7000     }
7001   }
7002
7003   if (NumLo <= 2 && NumHi <= 2) {
7004     // If no more than two elements come from either vector. This can be
7005     // implemented with two shuffles. First shuffle gather the elements.
7006     // The second shuffle, which takes the first shuffle as both of its
7007     // vector operands, put the elements into the right order.
7008     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7009
7010     int Mask2[] = { -1, -1, -1, -1 };
7011
7012     for (unsigned i = 0; i != 4; ++i)
7013       if (Locs[i].first != -1) {
7014         unsigned Idx = (i < 2) ? 0 : 4;
7015         Idx += Locs[i].first * 2 + Locs[i].second;
7016         Mask2[i] = Idx;
7017       }
7018
7019     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7020   }
7021
7022   if (NumLo == 3 || NumHi == 3) {
7023     // Otherwise, we must have three elements from one vector, call it X, and
7024     // one element from the other, call it Y.  First, use a shufps to build an
7025     // intermediate vector with the one element from Y and the element from X
7026     // that will be in the same half in the final destination (the indexes don't
7027     // matter). Then, use a shufps to build the final vector, taking the half
7028     // containing the element from Y from the intermediate, and the other half
7029     // from X.
7030     if (NumHi == 3) {
7031       // Normalize it so the 3 elements come from V1.
7032       CommuteVectorShuffleMask(PermMask, 4);
7033       std::swap(V1, V2);
7034     }
7035
7036     // Find the element from V2.
7037     unsigned HiIndex;
7038     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7039       int Val = PermMask[HiIndex];
7040       if (Val < 0)
7041         continue;
7042       if (Val >= 4)
7043         break;
7044     }
7045
7046     Mask1[0] = PermMask[HiIndex];
7047     Mask1[1] = -1;
7048     Mask1[2] = PermMask[HiIndex^1];
7049     Mask1[3] = -1;
7050     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7051
7052     if (HiIndex >= 2) {
7053       Mask1[0] = PermMask[0];
7054       Mask1[1] = PermMask[1];
7055       Mask1[2] = HiIndex & 1 ? 6 : 4;
7056       Mask1[3] = HiIndex & 1 ? 4 : 6;
7057       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7058     }
7059
7060     Mask1[0] = HiIndex & 1 ? 2 : 0;
7061     Mask1[1] = HiIndex & 1 ? 0 : 2;
7062     Mask1[2] = PermMask[2];
7063     Mask1[3] = PermMask[3];
7064     if (Mask1[2] >= 0)
7065       Mask1[2] += 4;
7066     if (Mask1[3] >= 0)
7067       Mask1[3] += 4;
7068     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7069   }
7070
7071   // Break it into (shuffle shuffle_hi, shuffle_lo).
7072   int LoMask[] = { -1, -1, -1, -1 };
7073   int HiMask[] = { -1, -1, -1, -1 };
7074
7075   int *MaskPtr = LoMask;
7076   unsigned MaskIdx = 0;
7077   unsigned LoIdx = 0;
7078   unsigned HiIdx = 2;
7079   for (unsigned i = 0; i != 4; ++i) {
7080     if (i == 2) {
7081       MaskPtr = HiMask;
7082       MaskIdx = 1;
7083       LoIdx = 0;
7084       HiIdx = 2;
7085     }
7086     int Idx = PermMask[i];
7087     if (Idx < 0) {
7088       Locs[i] = std::make_pair(-1, -1);
7089     } else if (Idx < 4) {
7090       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7091       MaskPtr[LoIdx] = Idx;
7092       LoIdx++;
7093     } else {
7094       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7095       MaskPtr[HiIdx] = Idx;
7096       HiIdx++;
7097     }
7098   }
7099
7100   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7101   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7102   int MaskOps[] = { -1, -1, -1, -1 };
7103   for (unsigned i = 0; i != 4; ++i)
7104     if (Locs[i].first != -1)
7105       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7106   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7107 }
7108
7109 static bool MayFoldVectorLoad(SDValue V) {
7110   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7111     V = V.getOperand(0);
7112
7113   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7114     V = V.getOperand(0);
7115   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7116       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7117     // BUILD_VECTOR (load), undef
7118     V = V.getOperand(0);
7119
7120   return MayFoldLoad(V);
7121 }
7122
7123 static
7124 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7125   MVT VT = Op.getSimpleValueType();
7126
7127   // Canonizalize to v2f64.
7128   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7129   return DAG.getNode(ISD::BITCAST, dl, VT,
7130                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7131                                           V1, DAG));
7132 }
7133
7134 static
7135 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7136                         bool HasSSE2) {
7137   SDValue V1 = Op.getOperand(0);
7138   SDValue V2 = Op.getOperand(1);
7139   MVT VT = Op.getSimpleValueType();
7140
7141   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7142
7143   if (HasSSE2 && VT == MVT::v2f64)
7144     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7145
7146   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7147   return DAG.getNode(ISD::BITCAST, dl, VT,
7148                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7149                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7150                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7151 }
7152
7153 static
7154 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7155   SDValue V1 = Op.getOperand(0);
7156   SDValue V2 = Op.getOperand(1);
7157   MVT VT = Op.getSimpleValueType();
7158
7159   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7160          "unsupported shuffle type");
7161
7162   if (V2.getOpcode() == ISD::UNDEF)
7163     V2 = V1;
7164
7165   // v4i32 or v4f32
7166   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7167 }
7168
7169 static
7170 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7171   SDValue V1 = Op.getOperand(0);
7172   SDValue V2 = Op.getOperand(1);
7173   MVT VT = Op.getSimpleValueType();
7174   unsigned NumElems = VT.getVectorNumElements();
7175
7176   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7177   // operand of these instructions is only memory, so check if there's a
7178   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7179   // same masks.
7180   bool CanFoldLoad = false;
7181
7182   // Trivial case, when V2 comes from a load.
7183   if (MayFoldVectorLoad(V2))
7184     CanFoldLoad = true;
7185
7186   // When V1 is a load, it can be folded later into a store in isel, example:
7187   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7188   //    turns into:
7189   //  (MOVLPSmr addr:$src1, VR128:$src2)
7190   // So, recognize this potential and also use MOVLPS or MOVLPD
7191   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7192     CanFoldLoad = true;
7193
7194   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7195   if (CanFoldLoad) {
7196     if (HasSSE2 && NumElems == 2)
7197       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7198
7199     if (NumElems == 4)
7200       // If we don't care about the second element, proceed to use movss.
7201       if (SVOp->getMaskElt(1) != -1)
7202         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7203   }
7204
7205   // movl and movlp will both match v2i64, but v2i64 is never matched by
7206   // movl earlier because we make it strict to avoid messing with the movlp load
7207   // folding logic (see the code above getMOVLP call). Match it here then,
7208   // this is horrible, but will stay like this until we move all shuffle
7209   // matching to x86 specific nodes. Note that for the 1st condition all
7210   // types are matched with movsd.
7211   if (HasSSE2) {
7212     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7213     // as to remove this logic from here, as much as possible
7214     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7215       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7216     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7217   }
7218
7219   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7220
7221   // Invert the operand order and use SHUFPS to match it.
7222   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7223                               getShuffleSHUFImmediate(SVOp), DAG);
7224 }
7225
7226 // Reduce a vector shuffle to zext.
7227 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7228                                     SelectionDAG &DAG) {
7229   // PMOVZX is only available from SSE41.
7230   if (!Subtarget->hasSSE41())
7231     return SDValue();
7232
7233   MVT VT = Op.getSimpleValueType();
7234
7235   // Only AVX2 support 256-bit vector integer extending.
7236   if (!Subtarget->hasInt256() && VT.is256BitVector())
7237     return SDValue();
7238
7239   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7240   SDLoc DL(Op);
7241   SDValue V1 = Op.getOperand(0);
7242   SDValue V2 = Op.getOperand(1);
7243   unsigned NumElems = VT.getVectorNumElements();
7244
7245   // Extending is an unary operation and the element type of the source vector
7246   // won't be equal to or larger than i64.
7247   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7248       VT.getVectorElementType() == MVT::i64)
7249     return SDValue();
7250
7251   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7252   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7253   while ((1U << Shift) < NumElems) {
7254     if (SVOp->getMaskElt(1U << Shift) == 1)
7255       break;
7256     Shift += 1;
7257     // The maximal ratio is 8, i.e. from i8 to i64.
7258     if (Shift > 3)
7259       return SDValue();
7260   }
7261
7262   // Check the shuffle mask.
7263   unsigned Mask = (1U << Shift) - 1;
7264   for (unsigned i = 0; i != NumElems; ++i) {
7265     int EltIdx = SVOp->getMaskElt(i);
7266     if ((i & Mask) != 0 && EltIdx != -1)
7267       return SDValue();
7268     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7269       return SDValue();
7270   }
7271
7272   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7273   MVT NeVT = MVT::getIntegerVT(NBits);
7274   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7275
7276   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7277     return SDValue();
7278
7279   // Simplify the operand as it's prepared to be fed into shuffle.
7280   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7281   if (V1.getOpcode() == ISD::BITCAST &&
7282       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7283       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7284       V1.getOperand(0).getOperand(0)
7285         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7286     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7287     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7288     ConstantSDNode *CIdx =
7289       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7290     // If it's foldable, i.e. normal load with single use, we will let code
7291     // selection to fold it. Otherwise, we will short the conversion sequence.
7292     if (CIdx && CIdx->getZExtValue() == 0 &&
7293         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7294       MVT FullVT = V.getSimpleValueType();
7295       MVT V1VT = V1.getSimpleValueType();
7296       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7297         // The "ext_vec_elt" node is wider than the result node.
7298         // In this case we should extract subvector from V.
7299         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7300         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7301         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7302                                         FullVT.getVectorNumElements()/Ratio);
7303         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7304                         DAG.getIntPtrConstant(0));
7305       }
7306       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7307     }
7308   }
7309
7310   return DAG.getNode(ISD::BITCAST, DL, VT,
7311                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7312 }
7313
7314 static SDValue
7315 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7316                        SelectionDAG &DAG) {
7317   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7318   MVT VT = Op.getSimpleValueType();
7319   SDLoc dl(Op);
7320   SDValue V1 = Op.getOperand(0);
7321   SDValue V2 = Op.getOperand(1);
7322
7323   if (isZeroShuffle(SVOp))
7324     return getZeroVector(VT, Subtarget, DAG, dl);
7325
7326   // Handle splat operations
7327   if (SVOp->isSplat()) {
7328     // Use vbroadcast whenever the splat comes from a foldable load
7329     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7330     if (Broadcast.getNode())
7331       return Broadcast;
7332   }
7333
7334   // Check integer expanding shuffles.
7335   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7336   if (NewOp.getNode())
7337     return NewOp;
7338
7339   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7340   // do it!
7341   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7342       VT == MVT::v16i16 || VT == MVT::v32i8) {
7343     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7344     if (NewOp.getNode())
7345       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7346   } else if ((VT == MVT::v4i32 ||
7347              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7348     // FIXME: Figure out a cleaner way to do this.
7349     // Try to make use of movq to zero out the top part.
7350     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7351       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7352       if (NewOp.getNode()) {
7353         MVT NewVT = NewOp.getSimpleValueType();
7354         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7355                                NewVT, true, false))
7356           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7357                               DAG, Subtarget, dl);
7358       }
7359     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7360       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7361       if (NewOp.getNode()) {
7362         MVT NewVT = NewOp.getSimpleValueType();
7363         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7364           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7365                               DAG, Subtarget, dl);
7366       }
7367     }
7368   }
7369   return SDValue();
7370 }
7371
7372 SDValue
7373 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7374   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7375   SDValue V1 = Op.getOperand(0);
7376   SDValue V2 = Op.getOperand(1);
7377   MVT VT = Op.getSimpleValueType();
7378   SDLoc dl(Op);
7379   unsigned NumElems = VT.getVectorNumElements();
7380   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7381   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7382   bool V1IsSplat = false;
7383   bool V2IsSplat = false;
7384   bool HasSSE2 = Subtarget->hasSSE2();
7385   bool HasFp256    = Subtarget->hasFp256();
7386   bool HasInt256   = Subtarget->hasInt256();
7387   MachineFunction &MF = DAG.getMachineFunction();
7388   bool OptForSize = MF.getFunction()->getAttributes().
7389     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7390
7391   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7392
7393   if (V1IsUndef && V2IsUndef)
7394     return DAG.getUNDEF(VT);
7395
7396   // When we create a shuffle node we put the UNDEF node to second operand,
7397   // but in some cases the first operand may be transformed to UNDEF.
7398   // In this case we should just commute the node.
7399   if (V1IsUndef)
7400     return CommuteVectorShuffle(SVOp, DAG);
7401
7402   // Vector shuffle lowering takes 3 steps:
7403   //
7404   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7405   //    narrowing and commutation of operands should be handled.
7406   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7407   //    shuffle nodes.
7408   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7409   //    so the shuffle can be broken into other shuffles and the legalizer can
7410   //    try the lowering again.
7411   //
7412   // The general idea is that no vector_shuffle operation should be left to
7413   // be matched during isel, all of them must be converted to a target specific
7414   // node here.
7415
7416   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7417   // narrowing and commutation of operands should be handled. The actual code
7418   // doesn't include all of those, work in progress...
7419   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7420   if (NewOp.getNode())
7421     return NewOp;
7422
7423   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7424
7425   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7426   // unpckh_undef). Only use pshufd if speed is more important than size.
7427   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7428     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7429   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7430     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7431
7432   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7433       V2IsUndef && MayFoldVectorLoad(V1))
7434     return getMOVDDup(Op, dl, V1, DAG);
7435
7436   if (isMOVHLPS_v_undef_Mask(M, VT))
7437     return getMOVHighToLow(Op, dl, DAG);
7438
7439   // Use to match splats
7440   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7441       (VT == MVT::v2f64 || VT == MVT::v2i64))
7442     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7443
7444   if (isPSHUFDMask(M, VT)) {
7445     // The actual implementation will match the mask in the if above and then
7446     // during isel it can match several different instructions, not only pshufd
7447     // as its name says, sad but true, emulate the behavior for now...
7448     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7449       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7450
7451     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7452
7453     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7454       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7455
7456     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7457       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7458                                   DAG);
7459
7460     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7461                                 TargetMask, DAG);
7462   }
7463
7464   if (isPALIGNRMask(M, VT, Subtarget))
7465     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7466                                 getShufflePALIGNRImmediate(SVOp),
7467                                 DAG);
7468
7469   // Check if this can be converted into a logical shift.
7470   bool isLeft = false;
7471   unsigned ShAmt = 0;
7472   SDValue ShVal;
7473   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7474   if (isShift && ShVal.hasOneUse()) {
7475     // If the shifted value has multiple uses, it may be cheaper to use
7476     // v_set0 + movlhps or movhlps, etc.
7477     MVT EltVT = VT.getVectorElementType();
7478     ShAmt *= EltVT.getSizeInBits();
7479     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7480   }
7481
7482   if (isMOVLMask(M, VT)) {
7483     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7484       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7485     if (!isMOVLPMask(M, VT)) {
7486       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7487         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7488
7489       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7490         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7491     }
7492   }
7493
7494   // FIXME: fold these into legal mask.
7495   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7496     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7497
7498   if (isMOVHLPSMask(M, VT))
7499     return getMOVHighToLow(Op, dl, DAG);
7500
7501   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7502     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7503
7504   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7505     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7506
7507   if (isMOVLPMask(M, VT))
7508     return getMOVLP(Op, dl, DAG, HasSSE2);
7509
7510   if (ShouldXformToMOVHLPS(M, VT) ||
7511       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7512     return CommuteVectorShuffle(SVOp, DAG);
7513
7514   if (isShift) {
7515     // No better options. Use a vshldq / vsrldq.
7516     MVT EltVT = VT.getVectorElementType();
7517     ShAmt *= EltVT.getSizeInBits();
7518     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7519   }
7520
7521   bool Commuted = false;
7522   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7523   // 1,1,1,1 -> v8i16 though.
7524   V1IsSplat = isSplatVector(V1.getNode());
7525   V2IsSplat = isSplatVector(V2.getNode());
7526
7527   // Canonicalize the splat or undef, if present, to be on the RHS.
7528   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7529     CommuteVectorShuffleMask(M, NumElems);
7530     std::swap(V1, V2);
7531     std::swap(V1IsSplat, V2IsSplat);
7532     Commuted = true;
7533   }
7534
7535   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7536     // Shuffling low element of v1 into undef, just return v1.
7537     if (V2IsUndef)
7538       return V1;
7539     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7540     // the instruction selector will not match, so get a canonical MOVL with
7541     // swapped operands to undo the commute.
7542     return getMOVL(DAG, dl, VT, V2, V1);
7543   }
7544
7545   if (isUNPCKLMask(M, VT, HasInt256))
7546     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7547
7548   if (isUNPCKHMask(M, VT, HasInt256))
7549     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7550
7551   if (V2IsSplat) {
7552     // Normalize mask so all entries that point to V2 points to its first
7553     // element then try to match unpck{h|l} again. If match, return a
7554     // new vector_shuffle with the corrected mask.p
7555     SmallVector<int, 8> NewMask(M.begin(), M.end());
7556     NormalizeMask(NewMask, NumElems);
7557     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7558       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7559     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7560       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7561   }
7562
7563   if (Commuted) {
7564     // Commute is back and try unpck* again.
7565     // FIXME: this seems wrong.
7566     CommuteVectorShuffleMask(M, NumElems);
7567     std::swap(V1, V2);
7568     std::swap(V1IsSplat, V2IsSplat);
7569
7570     if (isUNPCKLMask(M, VT, HasInt256))
7571       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7572
7573     if (isUNPCKHMask(M, VT, HasInt256))
7574       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7575   }
7576
7577   // Normalize the node to match x86 shuffle ops if needed
7578   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7579     return CommuteVectorShuffle(SVOp, DAG);
7580
7581   // The checks below are all present in isShuffleMaskLegal, but they are
7582   // inlined here right now to enable us to directly emit target specific
7583   // nodes, and remove one by one until they don't return Op anymore.
7584
7585   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7586       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7587     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7588       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7589   }
7590
7591   if (isPSHUFHWMask(M, VT, HasInt256))
7592     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7593                                 getShufflePSHUFHWImmediate(SVOp),
7594                                 DAG);
7595
7596   if (isPSHUFLWMask(M, VT, HasInt256))
7597     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7598                                 getShufflePSHUFLWImmediate(SVOp),
7599                                 DAG);
7600
7601   if (isSHUFPMask(M, VT))
7602     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7603                                 getShuffleSHUFImmediate(SVOp), DAG);
7604
7605   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7606     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7607   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7608     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7609
7610   //===--------------------------------------------------------------------===//
7611   // Generate target specific nodes for 128 or 256-bit shuffles only
7612   // supported in the AVX instruction set.
7613   //
7614
7615   // Handle VMOVDDUPY permutations
7616   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7617     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7618
7619   // Handle VPERMILPS/D* permutations
7620   if (isVPERMILPMask(M, VT)) {
7621     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7622       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7623                                   getShuffleSHUFImmediate(SVOp), DAG);
7624     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7625                                 getShuffleSHUFImmediate(SVOp), DAG);
7626   }
7627
7628   // Handle VPERM2F128/VPERM2I128 permutations
7629   if (isVPERM2X128Mask(M, VT, HasFp256))
7630     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7631                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7632
7633   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7634   if (BlendOp.getNode())
7635     return BlendOp;
7636
7637   unsigned Imm8;
7638   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7639     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7640
7641   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7642       VT.is512BitVector()) {
7643     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7644     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7645     SmallVector<SDValue, 16> permclMask;
7646     for (unsigned i = 0; i != NumElems; ++i) {
7647       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7648     }
7649
7650     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7651                                 &permclMask[0], NumElems);
7652     if (V2IsUndef)
7653       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7654       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7655                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7656     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7657                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7658   }
7659
7660   //===--------------------------------------------------------------------===//
7661   // Since no target specific shuffle was selected for this generic one,
7662   // lower it into other known shuffles. FIXME: this isn't true yet, but
7663   // this is the plan.
7664   //
7665
7666   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7667   if (VT == MVT::v8i16) {
7668     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7669     if (NewOp.getNode())
7670       return NewOp;
7671   }
7672
7673   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7674     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7675     if (NewOp.getNode())
7676       return NewOp;
7677   }
7678
7679   if (VT == MVT::v16i8) {
7680     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7681     if (NewOp.getNode())
7682       return NewOp;
7683   }
7684
7685   if (VT == MVT::v32i8) {
7686     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7687     if (NewOp.getNode())
7688       return NewOp;
7689   }
7690
7691   // Handle all 128-bit wide vectors with 4 elements, and match them with
7692   // several different shuffle types.
7693   if (NumElems == 4 && VT.is128BitVector())
7694     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7695
7696   // Handle general 256-bit shuffles
7697   if (VT.is256BitVector())
7698     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7699
7700   return SDValue();
7701 }
7702
7703 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7704   MVT VT = Op.getSimpleValueType();
7705   SDLoc dl(Op);
7706
7707   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7708     return SDValue();
7709
7710   if (VT.getSizeInBits() == 8) {
7711     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7712                                   Op.getOperand(0), Op.getOperand(1));
7713     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7714                                   DAG.getValueType(VT));
7715     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7716   }
7717
7718   if (VT.getSizeInBits() == 16) {
7719     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7720     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7721     if (Idx == 0)
7722       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7723                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7724                                      DAG.getNode(ISD::BITCAST, dl,
7725                                                  MVT::v4i32,
7726                                                  Op.getOperand(0)),
7727                                      Op.getOperand(1)));
7728     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7729                                   Op.getOperand(0), Op.getOperand(1));
7730     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7731                                   DAG.getValueType(VT));
7732     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7733   }
7734
7735   if (VT == MVT::f32) {
7736     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7737     // the result back to FR32 register. It's only worth matching if the
7738     // result has a single use which is a store or a bitcast to i32.  And in
7739     // the case of a store, it's not worth it if the index is a constant 0,
7740     // because a MOVSSmr can be used instead, which is smaller and faster.
7741     if (!Op.hasOneUse())
7742       return SDValue();
7743     SDNode *User = *Op.getNode()->use_begin();
7744     if ((User->getOpcode() != ISD::STORE ||
7745          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7746           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7747         (User->getOpcode() != ISD::BITCAST ||
7748          User->getValueType(0) != MVT::i32))
7749       return SDValue();
7750     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7751                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7752                                               Op.getOperand(0)),
7753                                               Op.getOperand(1));
7754     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7755   }
7756
7757   if (VT == MVT::i32 || VT == MVT::i64) {
7758     // ExtractPS/pextrq works with constant index.
7759     if (isa<ConstantSDNode>(Op.getOperand(1)))
7760       return Op;
7761   }
7762   return SDValue();
7763 }
7764
7765 /// Extract one bit from mask vector, like v16i1 or v8i1.
7766 /// AVX-512 feature.
7767 SDValue
7768 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7769   SDValue Vec = Op.getOperand(0);
7770   SDLoc dl(Vec);
7771   MVT VecVT = Vec.getSimpleValueType();
7772   SDValue Idx = Op.getOperand(1);
7773   MVT EltVT = Op.getSimpleValueType();
7774
7775   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7776
7777   // variable index can't be handled in mask registers,
7778   // extend vector to VR512
7779   if (!isa<ConstantSDNode>(Idx)) {
7780     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7781     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7782     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7783                               ExtVT.getVectorElementType(), Ext, Idx);
7784     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7785   }
7786
7787   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7788   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7789   unsigned MaxSift = rc->getSize()*8 - 1;
7790   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7791                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7792   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7793                     DAG.getConstant(MaxSift, MVT::i8));
7794   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7795                        DAG.getIntPtrConstant(0));
7796 }
7797
7798 SDValue
7799 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7800                                            SelectionDAG &DAG) const {
7801   SDLoc dl(Op);
7802   SDValue Vec = Op.getOperand(0);
7803   MVT VecVT = Vec.getSimpleValueType();
7804   SDValue Idx = Op.getOperand(1);
7805
7806   if (Op.getSimpleValueType() == MVT::i1)
7807     return ExtractBitFromMaskVector(Op, DAG);
7808
7809   if (!isa<ConstantSDNode>(Idx)) {
7810     if (VecVT.is512BitVector() ||
7811         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7812          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7813
7814       MVT MaskEltVT =
7815         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7816       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7817                                     MaskEltVT.getSizeInBits());
7818
7819       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7820       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7821                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7822                                 Idx, DAG.getConstant(0, getPointerTy()));
7823       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7824       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7825                         Perm, DAG.getConstant(0, getPointerTy()));
7826     }
7827     return SDValue();
7828   }
7829
7830   // If this is a 256-bit vector result, first extract the 128-bit vector and
7831   // then extract the element from the 128-bit vector.
7832   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7833
7834     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7835     // Get the 128-bit vector.
7836     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7837     MVT EltVT = VecVT.getVectorElementType();
7838
7839     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7840
7841     //if (IdxVal >= NumElems/2)
7842     //  IdxVal -= NumElems/2;
7843     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7844     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7845                        DAG.getConstant(IdxVal, MVT::i32));
7846   }
7847
7848   assert(VecVT.is128BitVector() && "Unexpected vector length");
7849
7850   if (Subtarget->hasSSE41()) {
7851     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7852     if (Res.getNode())
7853       return Res;
7854   }
7855
7856   MVT VT = Op.getSimpleValueType();
7857   // TODO: handle v16i8.
7858   if (VT.getSizeInBits() == 16) {
7859     SDValue Vec = Op.getOperand(0);
7860     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7861     if (Idx == 0)
7862       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7863                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7864                                      DAG.getNode(ISD::BITCAST, dl,
7865                                                  MVT::v4i32, Vec),
7866                                      Op.getOperand(1)));
7867     // Transform it so it match pextrw which produces a 32-bit result.
7868     MVT EltVT = MVT::i32;
7869     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7870                                   Op.getOperand(0), Op.getOperand(1));
7871     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7872                                   DAG.getValueType(VT));
7873     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7874   }
7875
7876   if (VT.getSizeInBits() == 32) {
7877     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7878     if (Idx == 0)
7879       return Op;
7880
7881     // SHUFPS the element to the lowest double word, then movss.
7882     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7883     MVT VVT = Op.getOperand(0).getSimpleValueType();
7884     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7885                                        DAG.getUNDEF(VVT), Mask);
7886     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7887                        DAG.getIntPtrConstant(0));
7888   }
7889
7890   if (VT.getSizeInBits() == 64) {
7891     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7892     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7893     //        to match extract_elt for f64.
7894     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7895     if (Idx == 0)
7896       return Op;
7897
7898     // UNPCKHPD the element to the lowest double word, then movsd.
7899     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7900     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7901     int Mask[2] = { 1, -1 };
7902     MVT VVT = Op.getOperand(0).getSimpleValueType();
7903     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7904                                        DAG.getUNDEF(VVT), Mask);
7905     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7906                        DAG.getIntPtrConstant(0));
7907   }
7908
7909   return SDValue();
7910 }
7911
7912 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7913   MVT VT = Op.getSimpleValueType();
7914   MVT EltVT = VT.getVectorElementType();
7915   SDLoc dl(Op);
7916
7917   SDValue N0 = Op.getOperand(0);
7918   SDValue N1 = Op.getOperand(1);
7919   SDValue N2 = Op.getOperand(2);
7920
7921   if (!VT.is128BitVector())
7922     return SDValue();
7923
7924   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7925       isa<ConstantSDNode>(N2)) {
7926     unsigned Opc;
7927     if (VT == MVT::v8i16)
7928       Opc = X86ISD::PINSRW;
7929     else if (VT == MVT::v16i8)
7930       Opc = X86ISD::PINSRB;
7931     else
7932       Opc = X86ISD::PINSRB;
7933
7934     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7935     // argument.
7936     if (N1.getValueType() != MVT::i32)
7937       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7938     if (N2.getValueType() != MVT::i32)
7939       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7940     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7941   }
7942
7943   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7944     // Bits [7:6] of the constant are the source select.  This will always be
7945     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7946     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7947     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7948     // Bits [5:4] of the constant are the destination select.  This is the
7949     //  value of the incoming immediate.
7950     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7951     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7952     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7953     // Create this as a scalar to vector..
7954     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7955     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7956   }
7957
7958   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7959     // PINSR* works with constant index.
7960     return Op;
7961   }
7962   return SDValue();
7963 }
7964
7965 /// Insert one bit to mask vector, like v16i1 or v8i1.
7966 /// AVX-512 feature.
7967 SDValue 
7968 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
7969   SDLoc dl(Op);
7970   SDValue Vec = Op.getOperand(0);
7971   SDValue Elt = Op.getOperand(1);
7972   SDValue Idx = Op.getOperand(2);
7973   MVT VecVT = Vec.getSimpleValueType();
7974
7975   if (!isa<ConstantSDNode>(Idx)) {
7976     // Non constant index. Extend source and destination,
7977     // insert element and then truncate the result.
7978     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7979     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
7980     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
7981       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
7982       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
7983     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
7984   }
7985
7986   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7987   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
7988   if (Vec.getOpcode() == ISD::UNDEF)
7989     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
7990                        DAG.getConstant(IdxVal, MVT::i8));
7991   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7992   unsigned MaxSift = rc->getSize()*8 - 1;
7993   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
7994                     DAG.getConstant(MaxSift, MVT::i8));
7995   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
7996                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7997   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
7998 }
7999 SDValue
8000 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8001   MVT VT = Op.getSimpleValueType();
8002   MVT EltVT = VT.getVectorElementType();
8003   
8004   if (EltVT == MVT::i1)
8005     return InsertBitToMaskVector(Op, DAG);
8006
8007   SDLoc dl(Op);
8008   SDValue N0 = Op.getOperand(0);
8009   SDValue N1 = Op.getOperand(1);
8010   SDValue N2 = Op.getOperand(2);
8011
8012   // If this is a 256-bit vector result, first extract the 128-bit vector,
8013   // insert the element into the extracted half and then place it back.
8014   if (VT.is256BitVector() || VT.is512BitVector()) {
8015     if (!isa<ConstantSDNode>(N2))
8016       return SDValue();
8017
8018     // Get the desired 128-bit vector half.
8019     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8020     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8021
8022     // Insert the element into the desired half.
8023     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8024     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8025
8026     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8027                     DAG.getConstant(IdxIn128, MVT::i32));
8028
8029     // Insert the changed part back to the 256-bit vector
8030     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8031   }
8032
8033   if (Subtarget->hasSSE41())
8034     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8035
8036   if (EltVT == MVT::i8)
8037     return SDValue();
8038
8039   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8040     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8041     // as its second argument.
8042     if (N1.getValueType() != MVT::i32)
8043       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8044     if (N2.getValueType() != MVT::i32)
8045       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8046     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8047   }
8048   return SDValue();
8049 }
8050
8051 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8052   SDLoc dl(Op);
8053   MVT OpVT = Op.getSimpleValueType();
8054
8055   // If this is a 256-bit vector result, first insert into a 128-bit
8056   // vector and then insert into the 256-bit vector.
8057   if (!OpVT.is128BitVector()) {
8058     // Insert into a 128-bit vector.
8059     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8060     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8061                                  OpVT.getVectorNumElements() / SizeFactor);
8062
8063     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8064
8065     // Insert the 128-bit vector.
8066     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8067   }
8068
8069   if (OpVT == MVT::v1i64 &&
8070       Op.getOperand(0).getValueType() == MVT::i64)
8071     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8072
8073   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8074   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8075   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8076                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8077 }
8078
8079 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8080 // a simple subregister reference or explicit instructions to grab
8081 // upper bits of a vector.
8082 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8083                                       SelectionDAG &DAG) {
8084   SDLoc dl(Op);
8085   SDValue In =  Op.getOperand(0);
8086   SDValue Idx = Op.getOperand(1);
8087   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8088   MVT ResVT   = Op.getSimpleValueType();
8089   MVT InVT    = In.getSimpleValueType();
8090
8091   if (Subtarget->hasFp256()) {
8092     if (ResVT.is128BitVector() &&
8093         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8094         isa<ConstantSDNode>(Idx)) {
8095       return Extract128BitVector(In, IdxVal, DAG, dl);
8096     }
8097     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8098         isa<ConstantSDNode>(Idx)) {
8099       return Extract256BitVector(In, IdxVal, DAG, dl);
8100     }
8101   }
8102   return SDValue();
8103 }
8104
8105 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8106 // simple superregister reference or explicit instructions to insert
8107 // the upper bits of a vector.
8108 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8109                                      SelectionDAG &DAG) {
8110   if (Subtarget->hasFp256()) {
8111     SDLoc dl(Op.getNode());
8112     SDValue Vec = Op.getNode()->getOperand(0);
8113     SDValue SubVec = Op.getNode()->getOperand(1);
8114     SDValue Idx = Op.getNode()->getOperand(2);
8115
8116     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8117          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8118         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8119         isa<ConstantSDNode>(Idx)) {
8120       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8121       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8122     }
8123
8124     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8125         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8126         isa<ConstantSDNode>(Idx)) {
8127       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8128       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8129     }
8130   }
8131   return SDValue();
8132 }
8133
8134 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8135 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8136 // one of the above mentioned nodes. It has to be wrapped because otherwise
8137 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8138 // be used to form addressing mode. These wrapped nodes will be selected
8139 // into MOV32ri.
8140 SDValue
8141 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8142   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8143
8144   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8145   // global base reg.
8146   unsigned char OpFlag = 0;
8147   unsigned WrapperKind = X86ISD::Wrapper;
8148   CodeModel::Model M = getTargetMachine().getCodeModel();
8149
8150   if (Subtarget->isPICStyleRIPRel() &&
8151       (M == CodeModel::Small || M == CodeModel::Kernel))
8152     WrapperKind = X86ISD::WrapperRIP;
8153   else if (Subtarget->isPICStyleGOT())
8154     OpFlag = X86II::MO_GOTOFF;
8155   else if (Subtarget->isPICStyleStubPIC())
8156     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8157
8158   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8159                                              CP->getAlignment(),
8160                                              CP->getOffset(), OpFlag);
8161   SDLoc DL(CP);
8162   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8163   // With PIC, the address is actually $g + Offset.
8164   if (OpFlag) {
8165     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8166                          DAG.getNode(X86ISD::GlobalBaseReg,
8167                                      SDLoc(), getPointerTy()),
8168                          Result);
8169   }
8170
8171   return Result;
8172 }
8173
8174 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8175   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8176
8177   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8178   // global base reg.
8179   unsigned char OpFlag = 0;
8180   unsigned WrapperKind = X86ISD::Wrapper;
8181   CodeModel::Model M = getTargetMachine().getCodeModel();
8182
8183   if (Subtarget->isPICStyleRIPRel() &&
8184       (M == CodeModel::Small || M == CodeModel::Kernel))
8185     WrapperKind = X86ISD::WrapperRIP;
8186   else if (Subtarget->isPICStyleGOT())
8187     OpFlag = X86II::MO_GOTOFF;
8188   else if (Subtarget->isPICStyleStubPIC())
8189     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8190
8191   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8192                                           OpFlag);
8193   SDLoc DL(JT);
8194   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8195
8196   // With PIC, the address is actually $g + Offset.
8197   if (OpFlag)
8198     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8199                          DAG.getNode(X86ISD::GlobalBaseReg,
8200                                      SDLoc(), getPointerTy()),
8201                          Result);
8202
8203   return Result;
8204 }
8205
8206 SDValue
8207 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8208   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8209
8210   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8211   // global base reg.
8212   unsigned char OpFlag = 0;
8213   unsigned WrapperKind = X86ISD::Wrapper;
8214   CodeModel::Model M = getTargetMachine().getCodeModel();
8215
8216   if (Subtarget->isPICStyleRIPRel() &&
8217       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8218     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8219       OpFlag = X86II::MO_GOTPCREL;
8220     WrapperKind = X86ISD::WrapperRIP;
8221   } else if (Subtarget->isPICStyleGOT()) {
8222     OpFlag = X86II::MO_GOT;
8223   } else if (Subtarget->isPICStyleStubPIC()) {
8224     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8225   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8226     OpFlag = X86II::MO_DARWIN_NONLAZY;
8227   }
8228
8229   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8230
8231   SDLoc DL(Op);
8232   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8233
8234   // With PIC, the address is actually $g + Offset.
8235   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8236       !Subtarget->is64Bit()) {
8237     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8238                          DAG.getNode(X86ISD::GlobalBaseReg,
8239                                      SDLoc(), getPointerTy()),
8240                          Result);
8241   }
8242
8243   // For symbols that require a load from a stub to get the address, emit the
8244   // load.
8245   if (isGlobalStubReference(OpFlag))
8246     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8247                          MachinePointerInfo::getGOT(), false, false, false, 0);
8248
8249   return Result;
8250 }
8251
8252 SDValue
8253 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8254   // Create the TargetBlockAddressAddress node.
8255   unsigned char OpFlags =
8256     Subtarget->ClassifyBlockAddressReference();
8257   CodeModel::Model M = getTargetMachine().getCodeModel();
8258   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8259   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8260   SDLoc dl(Op);
8261   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8262                                              OpFlags);
8263
8264   if (Subtarget->isPICStyleRIPRel() &&
8265       (M == CodeModel::Small || M == CodeModel::Kernel))
8266     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8267   else
8268     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8269
8270   // With PIC, the address is actually $g + Offset.
8271   if (isGlobalRelativeToPICBase(OpFlags)) {
8272     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8273                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8274                          Result);
8275   }
8276
8277   return Result;
8278 }
8279
8280 SDValue
8281 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8282                                       int64_t Offset, SelectionDAG &DAG) const {
8283   // Create the TargetGlobalAddress node, folding in the constant
8284   // offset if it is legal.
8285   unsigned char OpFlags =
8286     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8287   CodeModel::Model M = getTargetMachine().getCodeModel();
8288   SDValue Result;
8289   if (OpFlags == X86II::MO_NO_FLAG &&
8290       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8291     // A direct static reference to a global.
8292     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8293     Offset = 0;
8294   } else {
8295     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8296   }
8297
8298   if (Subtarget->isPICStyleRIPRel() &&
8299       (M == CodeModel::Small || M == CodeModel::Kernel))
8300     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8301   else
8302     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8303
8304   // With PIC, the address is actually $g + Offset.
8305   if (isGlobalRelativeToPICBase(OpFlags)) {
8306     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8307                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8308                          Result);
8309   }
8310
8311   // For globals that require a load from a stub to get the address, emit the
8312   // load.
8313   if (isGlobalStubReference(OpFlags))
8314     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8315                          MachinePointerInfo::getGOT(), false, false, false, 0);
8316
8317   // If there was a non-zero offset that we didn't fold, create an explicit
8318   // addition for it.
8319   if (Offset != 0)
8320     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8321                          DAG.getConstant(Offset, getPointerTy()));
8322
8323   return Result;
8324 }
8325
8326 SDValue
8327 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8328   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8329   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8330   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8331 }
8332
8333 static SDValue
8334 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8335            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8336            unsigned char OperandFlags, bool LocalDynamic = false) {
8337   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8338   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8339   SDLoc dl(GA);
8340   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8341                                            GA->getValueType(0),
8342                                            GA->getOffset(),
8343                                            OperandFlags);
8344
8345   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8346                                            : X86ISD::TLSADDR;
8347
8348   if (InFlag) {
8349     SDValue Ops[] = { Chain,  TGA, *InFlag };
8350     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8351   } else {
8352     SDValue Ops[]  = { Chain, TGA };
8353     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8354   }
8355
8356   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8357   MFI->setAdjustsStack(true);
8358
8359   SDValue Flag = Chain.getValue(1);
8360   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8361 }
8362
8363 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8364 static SDValue
8365 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8366                                 const EVT PtrVT) {
8367   SDValue InFlag;
8368   SDLoc dl(GA);  // ? function entry point might be better
8369   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8370                                    DAG.getNode(X86ISD::GlobalBaseReg,
8371                                                SDLoc(), PtrVT), InFlag);
8372   InFlag = Chain.getValue(1);
8373
8374   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8375 }
8376
8377 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8378 static SDValue
8379 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8380                                 const EVT PtrVT) {
8381   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8382                     X86::RAX, X86II::MO_TLSGD);
8383 }
8384
8385 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8386                                            SelectionDAG &DAG,
8387                                            const EVT PtrVT,
8388                                            bool is64Bit) {
8389   SDLoc dl(GA);
8390
8391   // Get the start address of the TLS block for this module.
8392   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8393       .getInfo<X86MachineFunctionInfo>();
8394   MFI->incNumLocalDynamicTLSAccesses();
8395
8396   SDValue Base;
8397   if (is64Bit) {
8398     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8399                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8400   } else {
8401     SDValue InFlag;
8402     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8403         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8404     InFlag = Chain.getValue(1);
8405     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8406                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8407   }
8408
8409   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8410   // of Base.
8411
8412   // Build x@dtpoff.
8413   unsigned char OperandFlags = X86II::MO_DTPOFF;
8414   unsigned WrapperKind = X86ISD::Wrapper;
8415   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8416                                            GA->getValueType(0),
8417                                            GA->getOffset(), OperandFlags);
8418   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8419
8420   // Add x@dtpoff with the base.
8421   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8422 }
8423
8424 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8425 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8426                                    const EVT PtrVT, TLSModel::Model model,
8427                                    bool is64Bit, bool isPIC) {
8428   SDLoc dl(GA);
8429
8430   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8431   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8432                                                          is64Bit ? 257 : 256));
8433
8434   SDValue ThreadPointer =
8435       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8436                   MachinePointerInfo(Ptr), false, false, false, 0);
8437
8438   unsigned char OperandFlags = 0;
8439   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8440   // initialexec.
8441   unsigned WrapperKind = X86ISD::Wrapper;
8442   if (model == TLSModel::LocalExec) {
8443     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8444   } else if (model == TLSModel::InitialExec) {
8445     if (is64Bit) {
8446       OperandFlags = X86II::MO_GOTTPOFF;
8447       WrapperKind = X86ISD::WrapperRIP;
8448     } else {
8449       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8450     }
8451   } else {
8452     llvm_unreachable("Unexpected model");
8453   }
8454
8455   // emit "addl x@ntpoff,%eax" (local exec)
8456   // or "addl x@indntpoff,%eax" (initial exec)
8457   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8458   SDValue TGA =
8459       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8460                                  GA->getOffset(), OperandFlags);
8461   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8462
8463   if (model == TLSModel::InitialExec) {
8464     if (isPIC && !is64Bit) {
8465       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8466                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8467                            Offset);
8468     }
8469
8470     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8471                          MachinePointerInfo::getGOT(), false, false, false, 0);
8472   }
8473
8474   // The address of the thread local variable is the add of the thread
8475   // pointer with the offset of the variable.
8476   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8477 }
8478
8479 SDValue
8480 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8481
8482   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8483   const GlobalValue *GV = GA->getGlobal();
8484
8485   if (Subtarget->isTargetELF()) {
8486     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8487
8488     switch (model) {
8489       case TLSModel::GeneralDynamic:
8490         if (Subtarget->is64Bit())
8491           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8492         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8493       case TLSModel::LocalDynamic:
8494         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8495                                            Subtarget->is64Bit());
8496       case TLSModel::InitialExec:
8497       case TLSModel::LocalExec:
8498         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8499                                    Subtarget->is64Bit(),
8500                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8501     }
8502     llvm_unreachable("Unknown TLS model.");
8503   }
8504
8505   if (Subtarget->isTargetDarwin()) {
8506     // Darwin only has one model of TLS.  Lower to that.
8507     unsigned char OpFlag = 0;
8508     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8509                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8510
8511     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8512     // global base reg.
8513     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8514                   !Subtarget->is64Bit();
8515     if (PIC32)
8516       OpFlag = X86II::MO_TLVP_PIC_BASE;
8517     else
8518       OpFlag = X86II::MO_TLVP;
8519     SDLoc DL(Op);
8520     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8521                                                 GA->getValueType(0),
8522                                                 GA->getOffset(), OpFlag);
8523     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8524
8525     // With PIC32, the address is actually $g + Offset.
8526     if (PIC32)
8527       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8528                            DAG.getNode(X86ISD::GlobalBaseReg,
8529                                        SDLoc(), getPointerTy()),
8530                            Offset);
8531
8532     // Lowering the machine isd will make sure everything is in the right
8533     // location.
8534     SDValue Chain = DAG.getEntryNode();
8535     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8536     SDValue Args[] = { Chain, Offset };
8537     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8538
8539     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8540     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8541     MFI->setAdjustsStack(true);
8542
8543     // And our return value (tls address) is in the standard call return value
8544     // location.
8545     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8546     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8547                               Chain.getValue(1));
8548   }
8549
8550   if (Subtarget->isTargetKnownWindowsMSVC() ||
8551       Subtarget->isTargetWindowsGNU()) {
8552     // Just use the implicit TLS architecture
8553     // Need to generate someting similar to:
8554     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8555     //                                  ; from TEB
8556     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8557     //   mov     rcx, qword [rdx+rcx*8]
8558     //   mov     eax, .tls$:tlsvar
8559     //   [rax+rcx] contains the address
8560     // Windows 64bit: gs:0x58
8561     // Windows 32bit: fs:__tls_array
8562
8563     // If GV is an alias then use the aliasee for determining
8564     // thread-localness.
8565     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8566       GV = GA->getAliasedGlobal();
8567     SDLoc dl(GA);
8568     SDValue Chain = DAG.getEntryNode();
8569
8570     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8571     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8572     // use its literal value of 0x2C.
8573     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8574                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8575                                                              256)
8576                                         : Type::getInt32PtrTy(*DAG.getContext(),
8577                                                               257));
8578
8579     SDValue TlsArray =
8580         Subtarget->is64Bit()
8581             ? DAG.getIntPtrConstant(0x58)
8582             : (Subtarget->isTargetWindowsGNU()
8583                    ? DAG.getIntPtrConstant(0x2C)
8584                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8585
8586     SDValue ThreadPointer =
8587         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8588                     MachinePointerInfo(Ptr), false, false, false, 0);
8589
8590     // Load the _tls_index variable
8591     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8592     if (Subtarget->is64Bit())
8593       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8594                            IDX, MachinePointerInfo(), MVT::i32,
8595                            false, false, 0);
8596     else
8597       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8598                         false, false, false, 0);
8599
8600     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8601                                     getPointerTy());
8602     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8603
8604     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8605     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8606                       false, false, false, 0);
8607
8608     // Get the offset of start of .tls section
8609     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8610                                              GA->getValueType(0),
8611                                              GA->getOffset(), X86II::MO_SECREL);
8612     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8613
8614     // The address of the thread local variable is the add of the thread
8615     // pointer with the offset of the variable.
8616     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8617   }
8618
8619   llvm_unreachable("TLS not implemented for this target.");
8620 }
8621
8622 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8623 /// and take a 2 x i32 value to shift plus a shift amount.
8624 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8625   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8626   MVT VT = Op.getSimpleValueType();
8627   unsigned VTBits = VT.getSizeInBits();
8628   SDLoc dl(Op);
8629   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8630   SDValue ShOpLo = Op.getOperand(0);
8631   SDValue ShOpHi = Op.getOperand(1);
8632   SDValue ShAmt  = Op.getOperand(2);
8633   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8634   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8635   // during isel.
8636   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8637                                   DAG.getConstant(VTBits - 1, MVT::i8));
8638   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8639                                      DAG.getConstant(VTBits - 1, MVT::i8))
8640                        : DAG.getConstant(0, VT);
8641
8642   SDValue Tmp2, Tmp3;
8643   if (Op.getOpcode() == ISD::SHL_PARTS) {
8644     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8645     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8646   } else {
8647     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8648     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8649   }
8650
8651   // If the shift amount is larger or equal than the width of a part we can't
8652   // rely on the results of shld/shrd. Insert a test and select the appropriate
8653   // values for large shift amounts.
8654   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8655                                 DAG.getConstant(VTBits, MVT::i8));
8656   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8657                              AndNode, DAG.getConstant(0, MVT::i8));
8658
8659   SDValue Hi, Lo;
8660   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8661   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8662   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8663
8664   if (Op.getOpcode() == ISD::SHL_PARTS) {
8665     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8666     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8667   } else {
8668     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8669     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8670   }
8671
8672   SDValue Ops[2] = { Lo, Hi };
8673   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8674 }
8675
8676 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8677                                            SelectionDAG &DAG) const {
8678   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8679
8680   if (SrcVT.isVector())
8681     return SDValue();
8682
8683   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8684          "Unknown SINT_TO_FP to lower!");
8685
8686   // These are really Legal; return the operand so the caller accepts it as
8687   // Legal.
8688   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8689     return Op;
8690   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8691       Subtarget->is64Bit()) {
8692     return Op;
8693   }
8694
8695   SDLoc dl(Op);
8696   unsigned Size = SrcVT.getSizeInBits()/8;
8697   MachineFunction &MF = DAG.getMachineFunction();
8698   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8699   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8700   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8701                                StackSlot,
8702                                MachinePointerInfo::getFixedStack(SSFI),
8703                                false, false, 0);
8704   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8705 }
8706
8707 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8708                                      SDValue StackSlot,
8709                                      SelectionDAG &DAG) const {
8710   // Build the FILD
8711   SDLoc DL(Op);
8712   SDVTList Tys;
8713   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8714   if (useSSE)
8715     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8716   else
8717     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8718
8719   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8720
8721   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8722   MachineMemOperand *MMO;
8723   if (FI) {
8724     int SSFI = FI->getIndex();
8725     MMO =
8726       DAG.getMachineFunction()
8727       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8728                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8729   } else {
8730     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8731     StackSlot = StackSlot.getOperand(1);
8732   }
8733   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8734   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8735                                            X86ISD::FILD, DL,
8736                                            Tys, Ops, array_lengthof(Ops),
8737                                            SrcVT, MMO);
8738
8739   if (useSSE) {
8740     Chain = Result.getValue(1);
8741     SDValue InFlag = Result.getValue(2);
8742
8743     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8744     // shouldn't be necessary except that RFP cannot be live across
8745     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8746     MachineFunction &MF = DAG.getMachineFunction();
8747     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8748     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8749     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8750     Tys = DAG.getVTList(MVT::Other);
8751     SDValue Ops[] = {
8752       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8753     };
8754     MachineMemOperand *MMO =
8755       DAG.getMachineFunction()
8756       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8757                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8758
8759     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8760                                     Ops, array_lengthof(Ops),
8761                                     Op.getValueType(), MMO);
8762     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8763                          MachinePointerInfo::getFixedStack(SSFI),
8764                          false, false, false, 0);
8765   }
8766
8767   return Result;
8768 }
8769
8770 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8771 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8772                                                SelectionDAG &DAG) const {
8773   // This algorithm is not obvious. Here it is what we're trying to output:
8774   /*
8775      movq       %rax,  %xmm0
8776      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8777      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8778      #ifdef __SSE3__
8779        haddpd   %xmm0, %xmm0
8780      #else
8781        pshufd   $0x4e, %xmm0, %xmm1
8782        addpd    %xmm1, %xmm0
8783      #endif
8784   */
8785
8786   SDLoc dl(Op);
8787   LLVMContext *Context = DAG.getContext();
8788
8789   // Build some magic constants.
8790   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8791   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8792   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8793
8794   SmallVector<Constant*,2> CV1;
8795   CV1.push_back(
8796     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8797                                       APInt(64, 0x4330000000000000ULL))));
8798   CV1.push_back(
8799     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8800                                       APInt(64, 0x4530000000000000ULL))));
8801   Constant *C1 = ConstantVector::get(CV1);
8802   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8803
8804   // Load the 64-bit value into an XMM register.
8805   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8806                             Op.getOperand(0));
8807   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8808                               MachinePointerInfo::getConstantPool(),
8809                               false, false, false, 16);
8810   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8811                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8812                               CLod0);
8813
8814   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8815                               MachinePointerInfo::getConstantPool(),
8816                               false, false, false, 16);
8817   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8818   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8819   SDValue Result;
8820
8821   if (Subtarget->hasSSE3()) {
8822     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8823     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8824   } else {
8825     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8826     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8827                                            S2F, 0x4E, DAG);
8828     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8829                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8830                          Sub);
8831   }
8832
8833   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8834                      DAG.getIntPtrConstant(0));
8835 }
8836
8837 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8838 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8839                                                SelectionDAG &DAG) const {
8840   SDLoc dl(Op);
8841   // FP constant to bias correct the final result.
8842   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8843                                    MVT::f64);
8844
8845   // Load the 32-bit value into an XMM register.
8846   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8847                              Op.getOperand(0));
8848
8849   // Zero out the upper parts of the register.
8850   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8851
8852   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8853                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8854                      DAG.getIntPtrConstant(0));
8855
8856   // Or the load with the bias.
8857   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8858                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8859                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8860                                                    MVT::v2f64, Load)),
8861                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8862                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8863                                                    MVT::v2f64, Bias)));
8864   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8865                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8866                    DAG.getIntPtrConstant(0));
8867
8868   // Subtract the bias.
8869   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8870
8871   // Handle final rounding.
8872   EVT DestVT = Op.getValueType();
8873
8874   if (DestVT.bitsLT(MVT::f64))
8875     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8876                        DAG.getIntPtrConstant(0));
8877   if (DestVT.bitsGT(MVT::f64))
8878     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8879
8880   // Handle final rounding.
8881   return Sub;
8882 }
8883
8884 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8885                                                SelectionDAG &DAG) const {
8886   SDValue N0 = Op.getOperand(0);
8887   MVT SVT = N0.getSimpleValueType();
8888   SDLoc dl(Op);
8889
8890   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8891           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8892          "Custom UINT_TO_FP is not supported!");
8893
8894   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8895   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8896                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8897 }
8898
8899 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8900                                            SelectionDAG &DAG) const {
8901   SDValue N0 = Op.getOperand(0);
8902   SDLoc dl(Op);
8903
8904   if (Op.getValueType().isVector())
8905     return lowerUINT_TO_FP_vec(Op, DAG);
8906
8907   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8908   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8909   // the optimization here.
8910   if (DAG.SignBitIsZero(N0))
8911     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8912
8913   MVT SrcVT = N0.getSimpleValueType();
8914   MVT DstVT = Op.getSimpleValueType();
8915   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8916     return LowerUINT_TO_FP_i64(Op, DAG);
8917   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8918     return LowerUINT_TO_FP_i32(Op, DAG);
8919   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8920     return SDValue();
8921
8922   // Make a 64-bit buffer, and use it to build an FILD.
8923   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8924   if (SrcVT == MVT::i32) {
8925     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8926     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8927                                      getPointerTy(), StackSlot, WordOff);
8928     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8929                                   StackSlot, MachinePointerInfo(),
8930                                   false, false, 0);
8931     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8932                                   OffsetSlot, MachinePointerInfo(),
8933                                   false, false, 0);
8934     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8935     return Fild;
8936   }
8937
8938   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8939   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8940                                StackSlot, MachinePointerInfo(),
8941                                false, false, 0);
8942   // For i64 source, we need to add the appropriate power of 2 if the input
8943   // was negative.  This is the same as the optimization in
8944   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8945   // we must be careful to do the computation in x87 extended precision, not
8946   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8947   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8948   MachineMemOperand *MMO =
8949     DAG.getMachineFunction()
8950     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8951                           MachineMemOperand::MOLoad, 8, 8);
8952
8953   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8954   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8955   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8956                                          array_lengthof(Ops), MVT::i64, MMO);
8957
8958   APInt FF(32, 0x5F800000ULL);
8959
8960   // Check whether the sign bit is set.
8961   SDValue SignSet = DAG.getSetCC(dl,
8962                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8963                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8964                                  ISD::SETLT);
8965
8966   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8967   SDValue FudgePtr = DAG.getConstantPool(
8968                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8969                                          getPointerTy());
8970
8971   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8972   SDValue Zero = DAG.getIntPtrConstant(0);
8973   SDValue Four = DAG.getIntPtrConstant(4);
8974   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8975                                Zero, Four);
8976   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8977
8978   // Load the value out, extending it from f32 to f80.
8979   // FIXME: Avoid the extend by constructing the right constant pool?
8980   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8981                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8982                                  MVT::f32, false, false, 4);
8983   // Extend everything to 80 bits to force it to be done on x87.
8984   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8985   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8986 }
8987
8988 std::pair<SDValue,SDValue>
8989 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8990                                     bool IsSigned, bool IsReplace) const {
8991   SDLoc DL(Op);
8992
8993   EVT DstTy = Op.getValueType();
8994
8995   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8996     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8997     DstTy = MVT::i64;
8998   }
8999
9000   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9001          DstTy.getSimpleVT() >= MVT::i16 &&
9002          "Unknown FP_TO_INT to lower!");
9003
9004   // These are really Legal.
9005   if (DstTy == MVT::i32 &&
9006       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9007     return std::make_pair(SDValue(), SDValue());
9008   if (Subtarget->is64Bit() &&
9009       DstTy == MVT::i64 &&
9010       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9011     return std::make_pair(SDValue(), SDValue());
9012
9013   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9014   // stack slot, or into the FTOL runtime function.
9015   MachineFunction &MF = DAG.getMachineFunction();
9016   unsigned MemSize = DstTy.getSizeInBits()/8;
9017   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9018   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9019
9020   unsigned Opc;
9021   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9022     Opc = X86ISD::WIN_FTOL;
9023   else
9024     switch (DstTy.getSimpleVT().SimpleTy) {
9025     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9026     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9027     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9028     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9029     }
9030
9031   SDValue Chain = DAG.getEntryNode();
9032   SDValue Value = Op.getOperand(0);
9033   EVT TheVT = Op.getOperand(0).getValueType();
9034   // FIXME This causes a redundant load/store if the SSE-class value is already
9035   // in memory, such as if it is on the callstack.
9036   if (isScalarFPTypeInSSEReg(TheVT)) {
9037     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9038     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9039                          MachinePointerInfo::getFixedStack(SSFI),
9040                          false, false, 0);
9041     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9042     SDValue Ops[] = {
9043       Chain, StackSlot, DAG.getValueType(TheVT)
9044     };
9045
9046     MachineMemOperand *MMO =
9047       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9048                               MachineMemOperand::MOLoad, MemSize, MemSize);
9049     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9050                                     array_lengthof(Ops), DstTy, MMO);
9051     Chain = Value.getValue(1);
9052     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9053     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9054   }
9055
9056   MachineMemOperand *MMO =
9057     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9058                             MachineMemOperand::MOStore, MemSize, MemSize);
9059
9060   if (Opc != X86ISD::WIN_FTOL) {
9061     // Build the FP_TO_INT*_IN_MEM
9062     SDValue Ops[] = { Chain, Value, StackSlot };
9063     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9064                                            Ops, array_lengthof(Ops), DstTy,
9065                                            MMO);
9066     return std::make_pair(FIST, StackSlot);
9067   } else {
9068     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9069       DAG.getVTList(MVT::Other, MVT::Glue),
9070       Chain, Value);
9071     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9072       MVT::i32, ftol.getValue(1));
9073     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9074       MVT::i32, eax.getValue(2));
9075     SDValue Ops[] = { eax, edx };
9076     SDValue pair = IsReplace
9077       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9078       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9079     return std::make_pair(pair, SDValue());
9080   }
9081 }
9082
9083 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9084                               const X86Subtarget *Subtarget) {
9085   MVT VT = Op->getSimpleValueType(0);
9086   SDValue In = Op->getOperand(0);
9087   MVT InVT = In.getSimpleValueType();
9088   SDLoc dl(Op);
9089
9090   // Optimize vectors in AVX mode:
9091   //
9092   //   v8i16 -> v8i32
9093   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9094   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9095   //   Concat upper and lower parts.
9096   //
9097   //   v4i32 -> v4i64
9098   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9099   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9100   //   Concat upper and lower parts.
9101   //
9102
9103   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9104       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9105       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9106     return SDValue();
9107
9108   if (Subtarget->hasInt256())
9109     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9110
9111   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9112   SDValue Undef = DAG.getUNDEF(InVT);
9113   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9114   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9115   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9116
9117   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9118                              VT.getVectorNumElements()/2);
9119
9120   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9121   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9122
9123   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9124 }
9125
9126 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9127                                         SelectionDAG &DAG) {
9128   MVT VT = Op->getSimpleValueType(0);
9129   SDValue In = Op->getOperand(0);
9130   MVT InVT = In.getSimpleValueType();
9131   SDLoc DL(Op);
9132   unsigned int NumElts = VT.getVectorNumElements();
9133   if (NumElts != 8 && NumElts != 16)
9134     return SDValue();
9135
9136   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9137     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9138
9139   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9141   // Now we have only mask extension
9142   assert(InVT.getVectorElementType() == MVT::i1);
9143   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9144   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9145   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9146   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9147   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9148                            MachinePointerInfo::getConstantPool(),
9149                            false, false, false, Alignment);
9150
9151   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9152   if (VT.is512BitVector())
9153     return Brcst;
9154   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9155 }
9156
9157 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9158                                SelectionDAG &DAG) {
9159   if (Subtarget->hasFp256()) {
9160     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9161     if (Res.getNode())
9162       return Res;
9163   }
9164
9165   return SDValue();
9166 }
9167
9168 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9169                                 SelectionDAG &DAG) {
9170   SDLoc DL(Op);
9171   MVT VT = Op.getSimpleValueType();
9172   SDValue In = Op.getOperand(0);
9173   MVT SVT = In.getSimpleValueType();
9174
9175   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9176     return LowerZERO_EXTEND_AVX512(Op, DAG);
9177
9178   if (Subtarget->hasFp256()) {
9179     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9180     if (Res.getNode())
9181       return Res;
9182   }
9183
9184   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9185          VT.getVectorNumElements() != SVT.getVectorNumElements());
9186   return SDValue();
9187 }
9188
9189 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9190   SDLoc DL(Op);
9191   MVT VT = Op.getSimpleValueType();
9192   SDValue In = Op.getOperand(0);
9193   MVT InVT = In.getSimpleValueType();
9194
9195   if (VT == MVT::i1) {
9196     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9197            "Invalid scalar TRUNCATE operation");
9198     if (InVT == MVT::i32)
9199       return SDValue();
9200     if (InVT.getSizeInBits() == 64)
9201       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9202     else if (InVT.getSizeInBits() < 32)
9203       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9204     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9205   }
9206   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9207          "Invalid TRUNCATE operation");
9208
9209   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9210     if (VT.getVectorElementType().getSizeInBits() >=8)
9211       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9212
9213     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9214     unsigned NumElts = InVT.getVectorNumElements();
9215     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9216     if (InVT.getSizeInBits() < 512) {
9217       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9218       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9219       InVT = ExtVT;
9220     }
9221     
9222     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9223     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9224     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9225     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9226     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9227                            MachinePointerInfo::getConstantPool(),
9228                            false, false, false, Alignment);
9229     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9230     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9231     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9232   }
9233
9234   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9235     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9236     if (Subtarget->hasInt256()) {
9237       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9238       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9239       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9240                                 ShufMask);
9241       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9242                          DAG.getIntPtrConstant(0));
9243     }
9244
9245     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9246                                DAG.getIntPtrConstant(0));
9247     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9248                                DAG.getIntPtrConstant(2));
9249     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9250     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9251     static const int ShufMask[] = {0, 2, 4, 6};
9252     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9253   }
9254
9255   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9256     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9257     if (Subtarget->hasInt256()) {
9258       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9259
9260       SmallVector<SDValue,32> pshufbMask;
9261       for (unsigned i = 0; i < 2; ++i) {
9262         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9263         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9264         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9265         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9266         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9267         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9268         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9269         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9270         for (unsigned j = 0; j < 8; ++j)
9271           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9272       }
9273       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9274                                &pshufbMask[0], 32);
9275       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9276       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9277
9278       static const int ShufMask[] = {0,  2,  -1,  -1};
9279       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9280                                 &ShufMask[0]);
9281       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9282                        DAG.getIntPtrConstant(0));
9283       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9284     }
9285
9286     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9287                                DAG.getIntPtrConstant(0));
9288
9289     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9290                                DAG.getIntPtrConstant(4));
9291
9292     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9293     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9294
9295     // The PSHUFB mask:
9296     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9297                                    -1, -1, -1, -1, -1, -1, -1, -1};
9298
9299     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9300     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9301     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9302
9303     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9304     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9305
9306     // The MOVLHPS Mask:
9307     static const int ShufMask2[] = {0, 1, 4, 5};
9308     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9309     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9310   }
9311
9312   // Handle truncation of V256 to V128 using shuffles.
9313   if (!VT.is128BitVector() || !InVT.is256BitVector())
9314     return SDValue();
9315
9316   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9317
9318   unsigned NumElems = VT.getVectorNumElements();
9319   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9320
9321   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9322   // Prepare truncation shuffle mask
9323   for (unsigned i = 0; i != NumElems; ++i)
9324     MaskVec[i] = i * 2;
9325   SDValue V = DAG.getVectorShuffle(NVT, DL,
9326                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9327                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9328   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9329                      DAG.getIntPtrConstant(0));
9330 }
9331
9332 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9333                                            SelectionDAG &DAG) const {
9334   assert(!Op.getSimpleValueType().isVector());
9335
9336   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9337     /*IsSigned=*/ true, /*IsReplace=*/ false);
9338   SDValue FIST = Vals.first, StackSlot = Vals.second;
9339   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9340   if (FIST.getNode() == 0) return Op;
9341
9342   if (StackSlot.getNode())
9343     // Load the result.
9344     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9345                        FIST, StackSlot, MachinePointerInfo(),
9346                        false, false, false, 0);
9347
9348   // The node is the result.
9349   return FIST;
9350 }
9351
9352 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9353                                            SelectionDAG &DAG) const {
9354   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9355     /*IsSigned=*/ false, /*IsReplace=*/ false);
9356   SDValue FIST = Vals.first, StackSlot = Vals.second;
9357   assert(FIST.getNode() && "Unexpected failure");
9358
9359   if (StackSlot.getNode())
9360     // Load the result.
9361     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9362                        FIST, StackSlot, MachinePointerInfo(),
9363                        false, false, false, 0);
9364
9365   // The node is the result.
9366   return FIST;
9367 }
9368
9369 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9370   SDLoc DL(Op);
9371   MVT VT = Op.getSimpleValueType();
9372   SDValue In = Op.getOperand(0);
9373   MVT SVT = In.getSimpleValueType();
9374
9375   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9376
9377   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9378                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9379                                  In, DAG.getUNDEF(SVT)));
9380 }
9381
9382 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9383   LLVMContext *Context = DAG.getContext();
9384   SDLoc dl(Op);
9385   MVT VT = Op.getSimpleValueType();
9386   MVT EltVT = VT;
9387   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9388   if (VT.isVector()) {
9389     EltVT = VT.getVectorElementType();
9390     NumElts = VT.getVectorNumElements();
9391   }
9392   Constant *C;
9393   if (EltVT == MVT::f64)
9394     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9395                                           APInt(64, ~(1ULL << 63))));
9396   else
9397     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9398                                           APInt(32, ~(1U << 31))));
9399   C = ConstantVector::getSplat(NumElts, C);
9400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9401   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9402   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9403   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9404                              MachinePointerInfo::getConstantPool(),
9405                              false, false, false, Alignment);
9406   if (VT.isVector()) {
9407     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9408     return DAG.getNode(ISD::BITCAST, dl, VT,
9409                        DAG.getNode(ISD::AND, dl, ANDVT,
9410                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9411                                                Op.getOperand(0)),
9412                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9413   }
9414   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9415 }
9416
9417 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9418   LLVMContext *Context = DAG.getContext();
9419   SDLoc dl(Op);
9420   MVT VT = Op.getSimpleValueType();
9421   MVT EltVT = VT;
9422   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9423   if (VT.isVector()) {
9424     EltVT = VT.getVectorElementType();
9425     NumElts = VT.getVectorNumElements();
9426   }
9427   Constant *C;
9428   if (EltVT == MVT::f64)
9429     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9430                                           APInt(64, 1ULL << 63)));
9431   else
9432     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9433                                           APInt(32, 1U << 31)));
9434   C = ConstantVector::getSplat(NumElts, C);
9435   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9436   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9437   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9438   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9439                              MachinePointerInfo::getConstantPool(),
9440                              false, false, false, Alignment);
9441   if (VT.isVector()) {
9442     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9443     return DAG.getNode(ISD::BITCAST, dl, VT,
9444                        DAG.getNode(ISD::XOR, dl, XORVT,
9445                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9446                                                Op.getOperand(0)),
9447                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9448   }
9449
9450   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9451 }
9452
9453 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9455   LLVMContext *Context = DAG.getContext();
9456   SDValue Op0 = Op.getOperand(0);
9457   SDValue Op1 = Op.getOperand(1);
9458   SDLoc dl(Op);
9459   MVT VT = Op.getSimpleValueType();
9460   MVT SrcVT = Op1.getSimpleValueType();
9461
9462   // If second operand is smaller, extend it first.
9463   if (SrcVT.bitsLT(VT)) {
9464     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9465     SrcVT = VT;
9466   }
9467   // And if it is bigger, shrink it first.
9468   if (SrcVT.bitsGT(VT)) {
9469     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9470     SrcVT = VT;
9471   }
9472
9473   // At this point the operands and the result should have the same
9474   // type, and that won't be f80 since that is not custom lowered.
9475
9476   // First get the sign bit of second operand.
9477   SmallVector<Constant*,4> CV;
9478   if (SrcVT == MVT::f64) {
9479     const fltSemantics &Sem = APFloat::IEEEdouble;
9480     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9481     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9482   } else {
9483     const fltSemantics &Sem = APFloat::IEEEsingle;
9484     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9485     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9486     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9487     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9488   }
9489   Constant *C = ConstantVector::get(CV);
9490   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9491   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9492                               MachinePointerInfo::getConstantPool(),
9493                               false, false, false, 16);
9494   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9495
9496   // Shift sign bit right or left if the two operands have different types.
9497   if (SrcVT.bitsGT(VT)) {
9498     // Op0 is MVT::f32, Op1 is MVT::f64.
9499     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9500     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9501                           DAG.getConstant(32, MVT::i32));
9502     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9503     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9504                           DAG.getIntPtrConstant(0));
9505   }
9506
9507   // Clear first operand sign bit.
9508   CV.clear();
9509   if (VT == MVT::f64) {
9510     const fltSemantics &Sem = APFloat::IEEEdouble;
9511     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9512                                                    APInt(64, ~(1ULL << 63)))));
9513     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9514   } else {
9515     const fltSemantics &Sem = APFloat::IEEEsingle;
9516     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9517                                                    APInt(32, ~(1U << 31)))));
9518     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9519     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9521   }
9522   C = ConstantVector::get(CV);
9523   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9524   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9525                               MachinePointerInfo::getConstantPool(),
9526                               false, false, false, 16);
9527   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9528
9529   // Or the value with the sign bit.
9530   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9531 }
9532
9533 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9534   SDValue N0 = Op.getOperand(0);
9535   SDLoc dl(Op);
9536   MVT VT = Op.getSimpleValueType();
9537
9538   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9539   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9540                                   DAG.getConstant(1, VT));
9541   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9542 }
9543
9544 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9545 //
9546 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9547                                       SelectionDAG &DAG) {
9548   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9549
9550   if (!Subtarget->hasSSE41())
9551     return SDValue();
9552
9553   if (!Op->hasOneUse())
9554     return SDValue();
9555
9556   SDNode *N = Op.getNode();
9557   SDLoc DL(N);
9558
9559   SmallVector<SDValue, 8> Opnds;
9560   DenseMap<SDValue, unsigned> VecInMap;
9561   SmallVector<SDValue, 8> VecIns;
9562   EVT VT = MVT::Other;
9563
9564   // Recognize a special case where a vector is casted into wide integer to
9565   // test all 0s.
9566   Opnds.push_back(N->getOperand(0));
9567   Opnds.push_back(N->getOperand(1));
9568
9569   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9570     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9571     // BFS traverse all OR'd operands.
9572     if (I->getOpcode() == ISD::OR) {
9573       Opnds.push_back(I->getOperand(0));
9574       Opnds.push_back(I->getOperand(1));
9575       // Re-evaluate the number of nodes to be traversed.
9576       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9577       continue;
9578     }
9579
9580     // Quit if a non-EXTRACT_VECTOR_ELT
9581     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9582       return SDValue();
9583
9584     // Quit if without a constant index.
9585     SDValue Idx = I->getOperand(1);
9586     if (!isa<ConstantSDNode>(Idx))
9587       return SDValue();
9588
9589     SDValue ExtractedFromVec = I->getOperand(0);
9590     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9591     if (M == VecInMap.end()) {
9592       VT = ExtractedFromVec.getValueType();
9593       // Quit if not 128/256-bit vector.
9594       if (!VT.is128BitVector() && !VT.is256BitVector())
9595         return SDValue();
9596       // Quit if not the same type.
9597       if (VecInMap.begin() != VecInMap.end() &&
9598           VT != VecInMap.begin()->first.getValueType())
9599         return SDValue();
9600       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9601       VecIns.push_back(ExtractedFromVec);
9602     }
9603     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9604   }
9605
9606   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9607          "Not extracted from 128-/256-bit vector.");
9608
9609   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9610
9611   for (DenseMap<SDValue, unsigned>::const_iterator
9612         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9613     // Quit if not all elements are used.
9614     if (I->second != FullMask)
9615       return SDValue();
9616   }
9617
9618   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9619
9620   // Cast all vectors into TestVT for PTEST.
9621   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9622     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9623
9624   // If more than one full vectors are evaluated, OR them first before PTEST.
9625   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9626     // Each iteration will OR 2 nodes and append the result until there is only
9627     // 1 node left, i.e. the final OR'd value of all vectors.
9628     SDValue LHS = VecIns[Slot];
9629     SDValue RHS = VecIns[Slot + 1];
9630     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9631   }
9632
9633   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9634                      VecIns.back(), VecIns.back());
9635 }
9636
9637 /// Emit nodes that will be selected as "test Op0,Op0", or something
9638 /// equivalent.
9639 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9640                                     SelectionDAG &DAG) const {
9641   SDLoc dl(Op);
9642
9643   if (Op.getValueType() == MVT::i1)
9644     // KORTEST instruction should be selected
9645     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9646                        DAG.getConstant(0, Op.getValueType()));
9647
9648   // CF and OF aren't always set the way we want. Determine which
9649   // of these we need.
9650   bool NeedCF = false;
9651   bool NeedOF = false;
9652   switch (X86CC) {
9653   default: break;
9654   case X86::COND_A: case X86::COND_AE:
9655   case X86::COND_B: case X86::COND_BE:
9656     NeedCF = true;
9657     break;
9658   case X86::COND_G: case X86::COND_GE:
9659   case X86::COND_L: case X86::COND_LE:
9660   case X86::COND_O: case X86::COND_NO:
9661     NeedOF = true;
9662     break;
9663   }
9664   // See if we can use the EFLAGS value from the operand instead of
9665   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9666   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9667   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9668     // Emit a CMP with 0, which is the TEST pattern.
9669     //if (Op.getValueType() == MVT::i1)
9670     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9671     //                     DAG.getConstant(0, MVT::i1));
9672     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9673                        DAG.getConstant(0, Op.getValueType()));
9674   }
9675   unsigned Opcode = 0;
9676   unsigned NumOperands = 0;
9677
9678   // Truncate operations may prevent the merge of the SETCC instruction
9679   // and the arithmetic instruction before it. Attempt to truncate the operands
9680   // of the arithmetic instruction and use a reduced bit-width instruction.
9681   bool NeedTruncation = false;
9682   SDValue ArithOp = Op;
9683   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9684     SDValue Arith = Op->getOperand(0);
9685     // Both the trunc and the arithmetic op need to have one user each.
9686     if (Arith->hasOneUse())
9687       switch (Arith.getOpcode()) {
9688         default: break;
9689         case ISD::ADD:
9690         case ISD::SUB:
9691         case ISD::AND:
9692         case ISD::OR:
9693         case ISD::XOR: {
9694           NeedTruncation = true;
9695           ArithOp = Arith;
9696         }
9697       }
9698   }
9699
9700   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9701   // which may be the result of a CAST.  We use the variable 'Op', which is the
9702   // non-casted variable when we check for possible users.
9703   switch (ArithOp.getOpcode()) {
9704   case ISD::ADD:
9705     // Due to an isel shortcoming, be conservative if this add is likely to be
9706     // selected as part of a load-modify-store instruction. When the root node
9707     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9708     // uses of other nodes in the match, such as the ADD in this case. This
9709     // leads to the ADD being left around and reselected, with the result being
9710     // two adds in the output.  Alas, even if none our users are stores, that
9711     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9712     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9713     // climbing the DAG back to the root, and it doesn't seem to be worth the
9714     // effort.
9715     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9716          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9717       if (UI->getOpcode() != ISD::CopyToReg &&
9718           UI->getOpcode() != ISD::SETCC &&
9719           UI->getOpcode() != ISD::STORE)
9720         goto default_case;
9721
9722     if (ConstantSDNode *C =
9723         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9724       // An add of one will be selected as an INC.
9725       if (C->getAPIntValue() == 1) {
9726         Opcode = X86ISD::INC;
9727         NumOperands = 1;
9728         break;
9729       }
9730
9731       // An add of negative one (subtract of one) will be selected as a DEC.
9732       if (C->getAPIntValue().isAllOnesValue()) {
9733         Opcode = X86ISD::DEC;
9734         NumOperands = 1;
9735         break;
9736       }
9737     }
9738
9739     // Otherwise use a regular EFLAGS-setting add.
9740     Opcode = X86ISD::ADD;
9741     NumOperands = 2;
9742     break;
9743   case ISD::AND: {
9744     // If the primary and result isn't used, don't bother using X86ISD::AND,
9745     // because a TEST instruction will be better.
9746     bool NonFlagUse = false;
9747     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9748            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9749       SDNode *User = *UI;
9750       unsigned UOpNo = UI.getOperandNo();
9751       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9752         // Look pass truncate.
9753         UOpNo = User->use_begin().getOperandNo();
9754         User = *User->use_begin();
9755       }
9756
9757       if (User->getOpcode() != ISD::BRCOND &&
9758           User->getOpcode() != ISD::SETCC &&
9759           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9760         NonFlagUse = true;
9761         break;
9762       }
9763     }
9764
9765     if (!NonFlagUse)
9766       break;
9767   }
9768     // FALL THROUGH
9769   case ISD::SUB:
9770   case ISD::OR:
9771   case ISD::XOR:
9772     // Due to the ISEL shortcoming noted above, be conservative if this op is
9773     // likely to be selected as part of a load-modify-store instruction.
9774     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9775            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9776       if (UI->getOpcode() == ISD::STORE)
9777         goto default_case;
9778
9779     // Otherwise use a regular EFLAGS-setting instruction.
9780     switch (ArithOp.getOpcode()) {
9781     default: llvm_unreachable("unexpected operator!");
9782     case ISD::SUB: Opcode = X86ISD::SUB; break;
9783     case ISD::XOR: Opcode = X86ISD::XOR; break;
9784     case ISD::AND: Opcode = X86ISD::AND; break;
9785     case ISD::OR: {
9786       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9787         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9788         if (EFLAGS.getNode())
9789           return EFLAGS;
9790       }
9791       Opcode = X86ISD::OR;
9792       break;
9793     }
9794     }
9795
9796     NumOperands = 2;
9797     break;
9798   case X86ISD::ADD:
9799   case X86ISD::SUB:
9800   case X86ISD::INC:
9801   case X86ISD::DEC:
9802   case X86ISD::OR:
9803   case X86ISD::XOR:
9804   case X86ISD::AND:
9805     return SDValue(Op.getNode(), 1);
9806   default:
9807   default_case:
9808     break;
9809   }
9810
9811   // If we found that truncation is beneficial, perform the truncation and
9812   // update 'Op'.
9813   if (NeedTruncation) {
9814     EVT VT = Op.getValueType();
9815     SDValue WideVal = Op->getOperand(0);
9816     EVT WideVT = WideVal.getValueType();
9817     unsigned ConvertedOp = 0;
9818     // Use a target machine opcode to prevent further DAGCombine
9819     // optimizations that may separate the arithmetic operations
9820     // from the setcc node.
9821     switch (WideVal.getOpcode()) {
9822       default: break;
9823       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9824       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9825       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9826       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9827       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9828     }
9829
9830     if (ConvertedOp) {
9831       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9832       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9833         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9834         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9835         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9836       }
9837     }
9838   }
9839
9840   if (Opcode == 0)
9841     // Emit a CMP with 0, which is the TEST pattern.
9842     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9843                        DAG.getConstant(0, Op.getValueType()));
9844
9845   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9846   SmallVector<SDValue, 4> Ops;
9847   for (unsigned i = 0; i != NumOperands; ++i)
9848     Ops.push_back(Op.getOperand(i));
9849
9850   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9851   DAG.ReplaceAllUsesWith(Op, New);
9852   return SDValue(New.getNode(), 1);
9853 }
9854
9855 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9856 /// equivalent.
9857 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9858                                    SelectionDAG &DAG) const {
9859   SDLoc dl(Op0);
9860   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9861     if (C->getAPIntValue() == 0)
9862       return EmitTest(Op0, X86CC, DAG);
9863
9864      if (Op0.getValueType() == MVT::i1)
9865        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9866   }
9867  
9868   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9869        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9870     // Do the comparison at i32 if it's smaller, besides the Atom case. 
9871     // This avoids subregister aliasing issues. Keep the smaller reference 
9872     // if we're optimizing for size, however, as that'll allow better folding 
9873     // of memory operations.
9874     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9875         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9876              AttributeSet::FunctionIndex, Attribute::MinSize) &&
9877         !Subtarget->isAtom()) {
9878       unsigned ExtendOp =
9879           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9880       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9881       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9882     }
9883     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9884     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9885     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9886                               Op0, Op1);
9887     return SDValue(Sub.getNode(), 1);
9888   }
9889   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9890 }
9891
9892 /// Convert a comparison if required by the subtarget.
9893 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9894                                                  SelectionDAG &DAG) const {
9895   // If the subtarget does not support the FUCOMI instruction, floating-point
9896   // comparisons have to be converted.
9897   if (Subtarget->hasCMov() ||
9898       Cmp.getOpcode() != X86ISD::CMP ||
9899       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9900       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9901     return Cmp;
9902
9903   // The instruction selector will select an FUCOM instruction instead of
9904   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9905   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9906   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9907   SDLoc dl(Cmp);
9908   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9909   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9910   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9911                             DAG.getConstant(8, MVT::i8));
9912   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9913   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9914 }
9915
9916 static bool isAllOnes(SDValue V) {
9917   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9918   return C && C->isAllOnesValue();
9919 }
9920
9921 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9922 /// if it's possible.
9923 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9924                                      SDLoc dl, SelectionDAG &DAG) const {
9925   SDValue Op0 = And.getOperand(0);
9926   SDValue Op1 = And.getOperand(1);
9927   if (Op0.getOpcode() == ISD::TRUNCATE)
9928     Op0 = Op0.getOperand(0);
9929   if (Op1.getOpcode() == ISD::TRUNCATE)
9930     Op1 = Op1.getOperand(0);
9931
9932   SDValue LHS, RHS;
9933   if (Op1.getOpcode() == ISD::SHL)
9934     std::swap(Op0, Op1);
9935   if (Op0.getOpcode() == ISD::SHL) {
9936     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9937       if (And00C->getZExtValue() == 1) {
9938         // If we looked past a truncate, check that it's only truncating away
9939         // known zeros.
9940         unsigned BitWidth = Op0.getValueSizeInBits();
9941         unsigned AndBitWidth = And.getValueSizeInBits();
9942         if (BitWidth > AndBitWidth) {
9943           APInt Zeros, Ones;
9944           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9945           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9946             return SDValue();
9947         }
9948         LHS = Op1;
9949         RHS = Op0.getOperand(1);
9950       }
9951   } else if (Op1.getOpcode() == ISD::Constant) {
9952     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9953     uint64_t AndRHSVal = AndRHS->getZExtValue();
9954     SDValue AndLHS = Op0;
9955
9956     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9957       LHS = AndLHS.getOperand(0);
9958       RHS = AndLHS.getOperand(1);
9959     }
9960
9961     // Use BT if the immediate can't be encoded in a TEST instruction.
9962     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9963       LHS = AndLHS;
9964       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9965     }
9966   }
9967
9968   if (LHS.getNode()) {
9969     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9970     // instruction.  Since the shift amount is in-range-or-undefined, we know
9971     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9972     // the encoding for the i16 version is larger than the i32 version.
9973     // Also promote i16 to i32 for performance / code size reason.
9974     if (LHS.getValueType() == MVT::i8 ||
9975         LHS.getValueType() == MVT::i16)
9976       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9977
9978     // If the operand types disagree, extend the shift amount to match.  Since
9979     // BT ignores high bits (like shifts) we can use anyextend.
9980     if (LHS.getValueType() != RHS.getValueType())
9981       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9982
9983     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9984     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9985     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9986                        DAG.getConstant(Cond, MVT::i8), BT);
9987   }
9988
9989   return SDValue();
9990 }
9991
9992 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9993 /// mask CMPs.
9994 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9995                               SDValue &Op1) {
9996   unsigned SSECC;
9997   bool Swap = false;
9998
9999   // SSE Condition code mapping:
10000   //  0 - EQ
10001   //  1 - LT
10002   //  2 - LE
10003   //  3 - UNORD
10004   //  4 - NEQ
10005   //  5 - NLT
10006   //  6 - NLE
10007   //  7 - ORD
10008   switch (SetCCOpcode) {
10009   default: llvm_unreachable("Unexpected SETCC condition");
10010   case ISD::SETOEQ:
10011   case ISD::SETEQ:  SSECC = 0; break;
10012   case ISD::SETOGT:
10013   case ISD::SETGT:  Swap = true; // Fallthrough
10014   case ISD::SETLT:
10015   case ISD::SETOLT: SSECC = 1; break;
10016   case ISD::SETOGE:
10017   case ISD::SETGE:  Swap = true; // Fallthrough
10018   case ISD::SETLE:
10019   case ISD::SETOLE: SSECC = 2; break;
10020   case ISD::SETUO:  SSECC = 3; break;
10021   case ISD::SETUNE:
10022   case ISD::SETNE:  SSECC = 4; break;
10023   case ISD::SETULE: Swap = true; // Fallthrough
10024   case ISD::SETUGE: SSECC = 5; break;
10025   case ISD::SETULT: Swap = true; // Fallthrough
10026   case ISD::SETUGT: SSECC = 6; break;
10027   case ISD::SETO:   SSECC = 7; break;
10028   case ISD::SETUEQ:
10029   case ISD::SETONE: SSECC = 8; break;
10030   }
10031   if (Swap)
10032     std::swap(Op0, Op1);
10033
10034   return SSECC;
10035 }
10036
10037 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10038 // ones, and then concatenate the result back.
10039 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10040   MVT VT = Op.getSimpleValueType();
10041
10042   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10043          "Unsupported value type for operation");
10044
10045   unsigned NumElems = VT.getVectorNumElements();
10046   SDLoc dl(Op);
10047   SDValue CC = Op.getOperand(2);
10048
10049   // Extract the LHS vectors
10050   SDValue LHS = Op.getOperand(0);
10051   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10052   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10053
10054   // Extract the RHS vectors
10055   SDValue RHS = Op.getOperand(1);
10056   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10057   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10058
10059   // Issue the operation on the smaller types and concatenate the result back
10060   MVT EltVT = VT.getVectorElementType();
10061   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10062   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10063                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10064                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10065 }
10066
10067 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10068                                      const X86Subtarget *Subtarget) {
10069   SDValue Op0 = Op.getOperand(0);
10070   SDValue Op1 = Op.getOperand(1);
10071   SDValue CC = Op.getOperand(2);
10072   MVT VT = Op.getSimpleValueType();
10073   SDLoc dl(Op);
10074
10075   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10076          Op.getValueType().getScalarType() == MVT::i1 &&
10077          "Cannot set masked compare for this operation");
10078
10079   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10080   unsigned  Opc = 0;
10081   bool Unsigned = false;
10082   bool Swap = false;
10083   unsigned SSECC;
10084   switch (SetCCOpcode) {
10085   default: llvm_unreachable("Unexpected SETCC condition");
10086   case ISD::SETNE:  SSECC = 4; break;
10087   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10088   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10089   case ISD::SETLT:  Swap = true; //fall-through
10090   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10091   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10092   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10093   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10094   case ISD::SETULE: Unsigned = true; //fall-through
10095   case ISD::SETLE:  SSECC = 2; break;
10096   }
10097
10098   if (Swap)
10099     std::swap(Op0, Op1);
10100   if (Opc)
10101     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10102   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10103   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10104                      DAG.getConstant(SSECC, MVT::i8));
10105 }
10106
10107 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10108 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10109 /// return an empty value.
10110 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10111 {
10112   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10113   if (!BV)
10114     return SDValue();
10115
10116   MVT VT = Op1.getSimpleValueType();
10117   MVT EVT = VT.getVectorElementType();
10118   unsigned n = VT.getVectorNumElements();
10119   SmallVector<SDValue, 8> ULTOp1;
10120
10121   for (unsigned i = 0; i < n; ++i) {
10122     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10123     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10124       return SDValue();
10125
10126     // Avoid underflow.
10127     APInt Val = Elt->getAPIntValue();
10128     if (Val == 0)
10129       return SDValue();
10130
10131     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10132   }
10133
10134   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10135                      ULTOp1.size());
10136 }
10137
10138 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10139                            SelectionDAG &DAG) {
10140   SDValue Op0 = Op.getOperand(0);
10141   SDValue Op1 = Op.getOperand(1);
10142   SDValue CC = Op.getOperand(2);
10143   MVT VT = Op.getSimpleValueType();
10144   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10145   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10146   SDLoc dl(Op);
10147
10148   if (isFP) {
10149 #ifndef NDEBUG
10150     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10151     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10152 #endif
10153
10154     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10155     unsigned Opc = X86ISD::CMPP;
10156     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10157       assert(VT.getVectorNumElements() <= 16);
10158       Opc = X86ISD::CMPM;
10159     }
10160     // In the two special cases we can't handle, emit two comparisons.
10161     if (SSECC == 8) {
10162       unsigned CC0, CC1;
10163       unsigned CombineOpc;
10164       if (SetCCOpcode == ISD::SETUEQ) {
10165         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10166       } else {
10167         assert(SetCCOpcode == ISD::SETONE);
10168         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10169       }
10170
10171       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10172                                  DAG.getConstant(CC0, MVT::i8));
10173       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10174                                  DAG.getConstant(CC1, MVT::i8));
10175       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10176     }
10177     // Handle all other FP comparisons here.
10178     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10179                        DAG.getConstant(SSECC, MVT::i8));
10180   }
10181
10182   // Break 256-bit integer vector compare into smaller ones.
10183   if (VT.is256BitVector() && !Subtarget->hasInt256())
10184     return Lower256IntVSETCC(Op, DAG);
10185
10186   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10187   EVT OpVT = Op1.getValueType();
10188   if (Subtarget->hasAVX512()) {
10189     if (Op1.getValueType().is512BitVector() ||
10190         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10191       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10192
10193     // In AVX-512 architecture setcc returns mask with i1 elements,
10194     // But there is no compare instruction for i8 and i16 elements.
10195     // We are not talking about 512-bit operands in this case, these
10196     // types are illegal.
10197     if (MaskResult &&
10198         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10199          OpVT.getVectorElementType().getSizeInBits() >= 8))
10200       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10201                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10202   }
10203
10204   // We are handling one of the integer comparisons here.  Since SSE only has
10205   // GT and EQ comparisons for integer, swapping operands and multiple
10206   // operations may be required for some comparisons.
10207   unsigned Opc;
10208   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10209   bool Subus = false;
10210
10211   switch (SetCCOpcode) {
10212   default: llvm_unreachable("Unexpected SETCC condition");
10213   case ISD::SETNE:  Invert = true;
10214   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10215   case ISD::SETLT:  Swap = true;
10216   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10217   case ISD::SETGE:  Swap = true;
10218   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10219                     Invert = true; break;
10220   case ISD::SETULT: Swap = true;
10221   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10222                     FlipSigns = true; break;
10223   case ISD::SETUGE: Swap = true;
10224   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10225                     FlipSigns = true; Invert = true; break;
10226   }
10227
10228   // Special case: Use min/max operations for SETULE/SETUGE
10229   MVT VET = VT.getVectorElementType();
10230   bool hasMinMax =
10231        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10232     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10233
10234   if (hasMinMax) {
10235     switch (SetCCOpcode) {
10236     default: break;
10237     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10238     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10239     }
10240
10241     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10242   }
10243
10244   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10245   if (!MinMax && hasSubus) {
10246     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10247     // Op0 u<= Op1:
10248     //   t = psubus Op0, Op1
10249     //   pcmpeq t, <0..0>
10250     switch (SetCCOpcode) {
10251     default: break;
10252     case ISD::SETULT: {
10253       // If the comparison is against a constant we can turn this into a
10254       // setule.  With psubus, setule does not require a swap.  This is
10255       // beneficial because the constant in the register is no longer
10256       // destructed as the destination so it can be hoisted out of a loop.
10257       // Only do this pre-AVX since vpcmp* is no longer destructive.
10258       if (Subtarget->hasAVX())
10259         break;
10260       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10261       if (ULEOp1.getNode()) {
10262         Op1 = ULEOp1;
10263         Subus = true; Invert = false; Swap = false;
10264       }
10265       break;
10266     }
10267     // Psubus is better than flip-sign because it requires no inversion.
10268     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10269     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10270     }
10271
10272     if (Subus) {
10273       Opc = X86ISD::SUBUS;
10274       FlipSigns = false;
10275     }
10276   }
10277
10278   if (Swap)
10279     std::swap(Op0, Op1);
10280
10281   // Check that the operation in question is available (most are plain SSE2,
10282   // but PCMPGTQ and PCMPEQQ have different requirements).
10283   if (VT == MVT::v2i64) {
10284     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10285       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10286
10287       // First cast everything to the right type.
10288       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10289       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10290
10291       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10292       // bits of the inputs before performing those operations. The lower
10293       // compare is always unsigned.
10294       SDValue SB;
10295       if (FlipSigns) {
10296         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10297       } else {
10298         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10299         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10300         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10301                          Sign, Zero, Sign, Zero);
10302       }
10303       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10304       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10305
10306       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10307       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10308       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10309
10310       // Create masks for only the low parts/high parts of the 64 bit integers.
10311       static const int MaskHi[] = { 1, 1, 3, 3 };
10312       static const int MaskLo[] = { 0, 0, 2, 2 };
10313       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10314       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10315       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10316
10317       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10318       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10319
10320       if (Invert)
10321         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10322
10323       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10324     }
10325
10326     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10327       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10328       // pcmpeqd + pshufd + pand.
10329       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10330
10331       // First cast everything to the right type.
10332       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10333       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10334
10335       // Do the compare.
10336       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10337
10338       // Make sure the lower and upper halves are both all-ones.
10339       static const int Mask[] = { 1, 0, 3, 2 };
10340       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10341       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10342
10343       if (Invert)
10344         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10345
10346       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10347     }
10348   }
10349
10350   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10351   // bits of the inputs before performing those operations.
10352   if (FlipSigns) {
10353     EVT EltVT = VT.getVectorElementType();
10354     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10355     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10356     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10357   }
10358
10359   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10360
10361   // If the logical-not of the result is required, perform that now.
10362   if (Invert)
10363     Result = DAG.getNOT(dl, Result, VT);
10364
10365   if (MinMax)
10366     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10367
10368   if (Subus)
10369     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10370                          getZeroVector(VT, Subtarget, DAG, dl));
10371
10372   return Result;
10373 }
10374
10375 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10376
10377   MVT VT = Op.getSimpleValueType();
10378
10379   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10380
10381   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10382          && "SetCC type must be 8-bit or 1-bit integer");
10383   SDValue Op0 = Op.getOperand(0);
10384   SDValue Op1 = Op.getOperand(1);
10385   SDLoc dl(Op);
10386   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10387
10388   // Optimize to BT if possible.
10389   // Lower (X & (1 << N)) == 0 to BT(X, N).
10390   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10391   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10392   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10393       Op1.getOpcode() == ISD::Constant &&
10394       cast<ConstantSDNode>(Op1)->isNullValue() &&
10395       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10396     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10397     if (NewSetCC.getNode())
10398       return NewSetCC;
10399   }
10400
10401   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10402   // these.
10403   if (Op1.getOpcode() == ISD::Constant &&
10404       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10405        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10406       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10407
10408     // If the input is a setcc, then reuse the input setcc or use a new one with
10409     // the inverted condition.
10410     if (Op0.getOpcode() == X86ISD::SETCC) {
10411       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10412       bool Invert = (CC == ISD::SETNE) ^
10413         cast<ConstantSDNode>(Op1)->isNullValue();
10414       if (!Invert)
10415         return Op0;
10416
10417       CCode = X86::GetOppositeBranchCondition(CCode);
10418       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10419                                   DAG.getConstant(CCode, MVT::i8),
10420                                   Op0.getOperand(1));
10421       if (VT == MVT::i1)
10422         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10423       return SetCC;
10424     }
10425   }
10426   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10427       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10428       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10429
10430     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10431     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10432   }
10433
10434   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10435   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10436   if (X86CC == X86::COND_INVALID)
10437     return SDValue();
10438
10439   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10440   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10441   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10442                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10443   if (VT == MVT::i1)
10444     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10445   return SetCC;
10446 }
10447
10448 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10449 static bool isX86LogicalCmp(SDValue Op) {
10450   unsigned Opc = Op.getNode()->getOpcode();
10451   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10452       Opc == X86ISD::SAHF)
10453     return true;
10454   if (Op.getResNo() == 1 &&
10455       (Opc == X86ISD::ADD ||
10456        Opc == X86ISD::SUB ||
10457        Opc == X86ISD::ADC ||
10458        Opc == X86ISD::SBB ||
10459        Opc == X86ISD::SMUL ||
10460        Opc == X86ISD::UMUL ||
10461        Opc == X86ISD::INC ||
10462        Opc == X86ISD::DEC ||
10463        Opc == X86ISD::OR ||
10464        Opc == X86ISD::XOR ||
10465        Opc == X86ISD::AND))
10466     return true;
10467
10468   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10469     return true;
10470
10471   return false;
10472 }
10473
10474 static bool isZero(SDValue V) {
10475   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10476   return C && C->isNullValue();
10477 }
10478
10479 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10480   if (V.getOpcode() != ISD::TRUNCATE)
10481     return false;
10482
10483   SDValue VOp0 = V.getOperand(0);
10484   unsigned InBits = VOp0.getValueSizeInBits();
10485   unsigned Bits = V.getValueSizeInBits();
10486   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10487 }
10488
10489 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10490   bool addTest = true;
10491   SDValue Cond  = Op.getOperand(0);
10492   SDValue Op1 = Op.getOperand(1);
10493   SDValue Op2 = Op.getOperand(2);
10494   SDLoc DL(Op);
10495   EVT VT = Op1.getValueType();
10496   SDValue CC;
10497
10498   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10499   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10500   // sequence later on.
10501   if (Cond.getOpcode() == ISD::SETCC &&
10502       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10503        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10504       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10505     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10506     int SSECC = translateX86FSETCC(
10507         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10508
10509     if (SSECC != 8) {
10510       if (Subtarget->hasAVX512()) {
10511         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10512                                   DAG.getConstant(SSECC, MVT::i8));
10513         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10514       }
10515       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10516                                 DAG.getConstant(SSECC, MVT::i8));
10517       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10518       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10519       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10520     }
10521   }
10522
10523   if (Cond.getOpcode() == ISD::SETCC) {
10524     SDValue NewCond = LowerSETCC(Cond, DAG);
10525     if (NewCond.getNode())
10526       Cond = NewCond;
10527   }
10528
10529   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10530   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10531   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10532   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10533   if (Cond.getOpcode() == X86ISD::SETCC &&
10534       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10535       isZero(Cond.getOperand(1).getOperand(1))) {
10536     SDValue Cmp = Cond.getOperand(1);
10537
10538     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10539
10540     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10541         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10542       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10543
10544       SDValue CmpOp0 = Cmp.getOperand(0);
10545       // Apply further optimizations for special cases
10546       // (select (x != 0), -1, 0) -> neg & sbb
10547       // (select (x == 0), 0, -1) -> neg & sbb
10548       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10549         if (YC->isNullValue() &&
10550             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10551           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10552           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10553                                     DAG.getConstant(0, CmpOp0.getValueType()),
10554                                     CmpOp0);
10555           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10556                                     DAG.getConstant(X86::COND_B, MVT::i8),
10557                                     SDValue(Neg.getNode(), 1));
10558           return Res;
10559         }
10560
10561       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10562                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10563       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10564
10565       SDValue Res =   // Res = 0 or -1.
10566         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10567                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10568
10569       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10570         Res = DAG.getNOT(DL, Res, Res.getValueType());
10571
10572       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10573       if (N2C == 0 || !N2C->isNullValue())
10574         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10575       return Res;
10576     }
10577   }
10578
10579   // Look past (and (setcc_carry (cmp ...)), 1).
10580   if (Cond.getOpcode() == ISD::AND &&
10581       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10582     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10583     if (C && C->getAPIntValue() == 1)
10584       Cond = Cond.getOperand(0);
10585   }
10586
10587   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10588   // setting operand in place of the X86ISD::SETCC.
10589   unsigned CondOpcode = Cond.getOpcode();
10590   if (CondOpcode == X86ISD::SETCC ||
10591       CondOpcode == X86ISD::SETCC_CARRY) {
10592     CC = Cond.getOperand(0);
10593
10594     SDValue Cmp = Cond.getOperand(1);
10595     unsigned Opc = Cmp.getOpcode();
10596     MVT VT = Op.getSimpleValueType();
10597
10598     bool IllegalFPCMov = false;
10599     if (VT.isFloatingPoint() && !VT.isVector() &&
10600         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10601       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10602
10603     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10604         Opc == X86ISD::BT) { // FIXME
10605       Cond = Cmp;
10606       addTest = false;
10607     }
10608   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10609              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10610              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10611               Cond.getOperand(0).getValueType() != MVT::i8)) {
10612     SDValue LHS = Cond.getOperand(0);
10613     SDValue RHS = Cond.getOperand(1);
10614     unsigned X86Opcode;
10615     unsigned X86Cond;
10616     SDVTList VTs;
10617     switch (CondOpcode) {
10618     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10619     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10620     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10621     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10622     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10623     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10624     default: llvm_unreachable("unexpected overflowing operator");
10625     }
10626     if (CondOpcode == ISD::UMULO)
10627       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10628                           MVT::i32);
10629     else
10630       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10631
10632     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10633
10634     if (CondOpcode == ISD::UMULO)
10635       Cond = X86Op.getValue(2);
10636     else
10637       Cond = X86Op.getValue(1);
10638
10639     CC = DAG.getConstant(X86Cond, MVT::i8);
10640     addTest = false;
10641   }
10642
10643   if (addTest) {
10644     // Look pass the truncate if the high bits are known zero.
10645     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10646         Cond = Cond.getOperand(0);
10647
10648     // We know the result of AND is compared against zero. Try to match
10649     // it to BT.
10650     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10651       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10652       if (NewSetCC.getNode()) {
10653         CC = NewSetCC.getOperand(0);
10654         Cond = NewSetCC.getOperand(1);
10655         addTest = false;
10656       }
10657     }
10658   }
10659
10660   if (addTest) {
10661     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10662     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10663   }
10664
10665   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10666   // a <  b ?  0 : -1 -> RES = setcc_carry
10667   // a >= b ? -1 :  0 -> RES = setcc_carry
10668   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10669   if (Cond.getOpcode() == X86ISD::SUB) {
10670     Cond = ConvertCmpIfNecessary(Cond, DAG);
10671     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10672
10673     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10674         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10675       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10676                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10677       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10678         return DAG.getNOT(DL, Res, Res.getValueType());
10679       return Res;
10680     }
10681   }
10682
10683   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10684   // widen the cmov and push the truncate through. This avoids introducing a new
10685   // branch during isel and doesn't add any extensions.
10686   if (Op.getValueType() == MVT::i8 &&
10687       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10688     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10689     if (T1.getValueType() == T2.getValueType() &&
10690         // Blacklist CopyFromReg to avoid partial register stalls.
10691         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10692       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10693       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10694       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10695     }
10696   }
10697
10698   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10699   // condition is true.
10700   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10701   SDValue Ops[] = { Op2, Op1, CC, Cond };
10702   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10703 }
10704
10705 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10706   MVT VT = Op->getSimpleValueType(0);
10707   SDValue In = Op->getOperand(0);
10708   MVT InVT = In.getSimpleValueType();
10709   SDLoc dl(Op);
10710
10711   unsigned int NumElts = VT.getVectorNumElements();
10712   if (NumElts != 8 && NumElts != 16)
10713     return SDValue();
10714
10715   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10716     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10717
10718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10719   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10720
10721   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10722   Constant *C = ConstantInt::get(*DAG.getContext(),
10723     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10724
10725   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10726   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10727   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10728                           MachinePointerInfo::getConstantPool(),
10729                           false, false, false, Alignment);
10730   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10731   if (VT.is512BitVector())
10732     return Brcst;
10733   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10734 }
10735
10736 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10737                                 SelectionDAG &DAG) {
10738   MVT VT = Op->getSimpleValueType(0);
10739   SDValue In = Op->getOperand(0);
10740   MVT InVT = In.getSimpleValueType();
10741   SDLoc dl(Op);
10742
10743   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10744     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10745
10746   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10747       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10748       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10749     return SDValue();
10750
10751   if (Subtarget->hasInt256())
10752     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10753
10754   // Optimize vectors in AVX mode
10755   // Sign extend  v8i16 to v8i32 and
10756   //              v4i32 to v4i64
10757   //
10758   // Divide input vector into two parts
10759   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10760   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10761   // concat the vectors to original VT
10762
10763   unsigned NumElems = InVT.getVectorNumElements();
10764   SDValue Undef = DAG.getUNDEF(InVT);
10765
10766   SmallVector<int,8> ShufMask1(NumElems, -1);
10767   for (unsigned i = 0; i != NumElems/2; ++i)
10768     ShufMask1[i] = i;
10769
10770   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10771
10772   SmallVector<int,8> ShufMask2(NumElems, -1);
10773   for (unsigned i = 0; i != NumElems/2; ++i)
10774     ShufMask2[i] = i + NumElems/2;
10775
10776   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10777
10778   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10779                                 VT.getVectorNumElements()/2);
10780
10781   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10782   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10783
10784   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10785 }
10786
10787 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10788 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10789 // from the AND / OR.
10790 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10791   Opc = Op.getOpcode();
10792   if (Opc != ISD::OR && Opc != ISD::AND)
10793     return false;
10794   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10795           Op.getOperand(0).hasOneUse() &&
10796           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10797           Op.getOperand(1).hasOneUse());
10798 }
10799
10800 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10801 // 1 and that the SETCC node has a single use.
10802 static bool isXor1OfSetCC(SDValue Op) {
10803   if (Op.getOpcode() != ISD::XOR)
10804     return false;
10805   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10806   if (N1C && N1C->getAPIntValue() == 1) {
10807     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10808       Op.getOperand(0).hasOneUse();
10809   }
10810   return false;
10811 }
10812
10813 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10814   bool addTest = true;
10815   SDValue Chain = Op.getOperand(0);
10816   SDValue Cond  = Op.getOperand(1);
10817   SDValue Dest  = Op.getOperand(2);
10818   SDLoc dl(Op);
10819   SDValue CC;
10820   bool Inverted = false;
10821
10822   if (Cond.getOpcode() == ISD::SETCC) {
10823     // Check for setcc([su]{add,sub,mul}o == 0).
10824     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10825         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10826         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10827         Cond.getOperand(0).getResNo() == 1 &&
10828         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10829          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10830          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10831          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10832          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10833          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10834       Inverted = true;
10835       Cond = Cond.getOperand(0);
10836     } else {
10837       SDValue NewCond = LowerSETCC(Cond, DAG);
10838       if (NewCond.getNode())
10839         Cond = NewCond;
10840     }
10841   }
10842 #if 0
10843   // FIXME: LowerXALUO doesn't handle these!!
10844   else if (Cond.getOpcode() == X86ISD::ADD  ||
10845            Cond.getOpcode() == X86ISD::SUB  ||
10846            Cond.getOpcode() == X86ISD::SMUL ||
10847            Cond.getOpcode() == X86ISD::UMUL)
10848     Cond = LowerXALUO(Cond, DAG);
10849 #endif
10850
10851   // Look pass (and (setcc_carry (cmp ...)), 1).
10852   if (Cond.getOpcode() == ISD::AND &&
10853       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10854     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10855     if (C && C->getAPIntValue() == 1)
10856       Cond = Cond.getOperand(0);
10857   }
10858
10859   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10860   // setting operand in place of the X86ISD::SETCC.
10861   unsigned CondOpcode = Cond.getOpcode();
10862   if (CondOpcode == X86ISD::SETCC ||
10863       CondOpcode == X86ISD::SETCC_CARRY) {
10864     CC = Cond.getOperand(0);
10865
10866     SDValue Cmp = Cond.getOperand(1);
10867     unsigned Opc = Cmp.getOpcode();
10868     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10869     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10870       Cond = Cmp;
10871       addTest = false;
10872     } else {
10873       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10874       default: break;
10875       case X86::COND_O:
10876       case X86::COND_B:
10877         // These can only come from an arithmetic instruction with overflow,
10878         // e.g. SADDO, UADDO.
10879         Cond = Cond.getNode()->getOperand(1);
10880         addTest = false;
10881         break;
10882       }
10883     }
10884   }
10885   CondOpcode = Cond.getOpcode();
10886   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10887       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10888       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10889        Cond.getOperand(0).getValueType() != MVT::i8)) {
10890     SDValue LHS = Cond.getOperand(0);
10891     SDValue RHS = Cond.getOperand(1);
10892     unsigned X86Opcode;
10893     unsigned X86Cond;
10894     SDVTList VTs;
10895     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10896     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10897     // X86ISD::INC).
10898     switch (CondOpcode) {
10899     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10900     case ISD::SADDO:
10901       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10902         if (C->isOne()) {
10903           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10904           break;
10905         }
10906       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10907     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10908     case ISD::SSUBO:
10909       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10910         if (C->isOne()) {
10911           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10912           break;
10913         }
10914       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10915     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10916     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10917     default: llvm_unreachable("unexpected overflowing operator");
10918     }
10919     if (Inverted)
10920       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10921     if (CondOpcode == ISD::UMULO)
10922       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10923                           MVT::i32);
10924     else
10925       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10926
10927     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10928
10929     if (CondOpcode == ISD::UMULO)
10930       Cond = X86Op.getValue(2);
10931     else
10932       Cond = X86Op.getValue(1);
10933
10934     CC = DAG.getConstant(X86Cond, MVT::i8);
10935     addTest = false;
10936   } else {
10937     unsigned CondOpc;
10938     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10939       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10940       if (CondOpc == ISD::OR) {
10941         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10942         // two branches instead of an explicit OR instruction with a
10943         // separate test.
10944         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10945             isX86LogicalCmp(Cmp)) {
10946           CC = Cond.getOperand(0).getOperand(0);
10947           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10948                               Chain, Dest, CC, Cmp);
10949           CC = Cond.getOperand(1).getOperand(0);
10950           Cond = Cmp;
10951           addTest = false;
10952         }
10953       } else { // ISD::AND
10954         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10955         // two branches instead of an explicit AND instruction with a
10956         // separate test. However, we only do this if this block doesn't
10957         // have a fall-through edge, because this requires an explicit
10958         // jmp when the condition is false.
10959         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10960             isX86LogicalCmp(Cmp) &&
10961             Op.getNode()->hasOneUse()) {
10962           X86::CondCode CCode =
10963             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10964           CCode = X86::GetOppositeBranchCondition(CCode);
10965           CC = DAG.getConstant(CCode, MVT::i8);
10966           SDNode *User = *Op.getNode()->use_begin();
10967           // Look for an unconditional branch following this conditional branch.
10968           // We need this because we need to reverse the successors in order
10969           // to implement FCMP_OEQ.
10970           if (User->getOpcode() == ISD::BR) {
10971             SDValue FalseBB = User->getOperand(1);
10972             SDNode *NewBR =
10973               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10974             assert(NewBR == User);
10975             (void)NewBR;
10976             Dest = FalseBB;
10977
10978             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10979                                 Chain, Dest, CC, Cmp);
10980             X86::CondCode CCode =
10981               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10982             CCode = X86::GetOppositeBranchCondition(CCode);
10983             CC = DAG.getConstant(CCode, MVT::i8);
10984             Cond = Cmp;
10985             addTest = false;
10986           }
10987         }
10988       }
10989     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10990       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10991       // It should be transformed during dag combiner except when the condition
10992       // is set by a arithmetics with overflow node.
10993       X86::CondCode CCode =
10994         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10995       CCode = X86::GetOppositeBranchCondition(CCode);
10996       CC = DAG.getConstant(CCode, MVT::i8);
10997       Cond = Cond.getOperand(0).getOperand(1);
10998       addTest = false;
10999     } else if (Cond.getOpcode() == ISD::SETCC &&
11000                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11001       // For FCMP_OEQ, we can emit
11002       // two branches instead of an explicit AND instruction with a
11003       // separate test. However, we only do this if this block doesn't
11004       // have a fall-through edge, because this requires an explicit
11005       // jmp when the condition is false.
11006       if (Op.getNode()->hasOneUse()) {
11007         SDNode *User = *Op.getNode()->use_begin();
11008         // Look for an unconditional branch following this conditional branch.
11009         // We need this because we need to reverse the successors in order
11010         // to implement FCMP_OEQ.
11011         if (User->getOpcode() == ISD::BR) {
11012           SDValue FalseBB = User->getOperand(1);
11013           SDNode *NewBR =
11014             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11015           assert(NewBR == User);
11016           (void)NewBR;
11017           Dest = FalseBB;
11018
11019           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11020                                     Cond.getOperand(0), Cond.getOperand(1));
11021           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11022           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11023           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11024                               Chain, Dest, CC, Cmp);
11025           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11026           Cond = Cmp;
11027           addTest = false;
11028         }
11029       }
11030     } else if (Cond.getOpcode() == ISD::SETCC &&
11031                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11032       // For FCMP_UNE, we can emit
11033       // two branches instead of an explicit AND instruction with a
11034       // separate test. However, we only do this if this block doesn't
11035       // have a fall-through edge, because this requires an explicit
11036       // jmp when the condition is false.
11037       if (Op.getNode()->hasOneUse()) {
11038         SDNode *User = *Op.getNode()->use_begin();
11039         // Look for an unconditional branch following this conditional branch.
11040         // We need this because we need to reverse the successors in order
11041         // to implement FCMP_UNE.
11042         if (User->getOpcode() == ISD::BR) {
11043           SDValue FalseBB = User->getOperand(1);
11044           SDNode *NewBR =
11045             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11046           assert(NewBR == User);
11047           (void)NewBR;
11048
11049           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11050                                     Cond.getOperand(0), Cond.getOperand(1));
11051           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11052           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11053           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11054                               Chain, Dest, CC, Cmp);
11055           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11056           Cond = Cmp;
11057           addTest = false;
11058           Dest = FalseBB;
11059         }
11060       }
11061     }
11062   }
11063
11064   if (addTest) {
11065     // Look pass the truncate if the high bits are known zero.
11066     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11067         Cond = Cond.getOperand(0);
11068
11069     // We know the result of AND is compared against zero. Try to match
11070     // it to BT.
11071     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11072       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11073       if (NewSetCC.getNode()) {
11074         CC = NewSetCC.getOperand(0);
11075         Cond = NewSetCC.getOperand(1);
11076         addTest = false;
11077       }
11078     }
11079   }
11080
11081   if (addTest) {
11082     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11083     Cond = EmitTest(Cond, X86::COND_NE, DAG);
11084   }
11085   Cond = ConvertCmpIfNecessary(Cond, DAG);
11086   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11087                      Chain, Dest, CC, Cond);
11088 }
11089
11090 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11091 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11092 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11093 // that the guard pages used by the OS virtual memory manager are allocated in
11094 // correct sequence.
11095 SDValue
11096 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11097                                            SelectionDAG &DAG) const {
11098   MachineFunction &MF = DAG.getMachineFunction();
11099   bool SplitStack = MF.shouldSplitStack();
11100   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11101                SplitStack;
11102   SDLoc dl(Op);
11103
11104   if (!Lower) {
11105     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11106     SDNode* Node = Op.getNode();
11107
11108     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11109     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11110         " not tell us which reg is the stack pointer!");
11111     EVT VT = Node->getValueType(0);
11112     SDValue Tmp1 = SDValue(Node, 0);
11113     SDValue Tmp2 = SDValue(Node, 1);
11114     SDValue Tmp3 = Node->getOperand(2);
11115     SDValue Chain = Tmp1.getOperand(0);
11116
11117     // Chain the dynamic stack allocation so that it doesn't modify the stack
11118     // pointer when other instructions are using the stack.
11119     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11120         SDLoc(Node));
11121
11122     SDValue Size = Tmp2.getOperand(1);
11123     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11124     Chain = SP.getValue(1);
11125     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11126     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11127     unsigned StackAlign = TFI.getStackAlignment();
11128     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11129     if (Align > StackAlign)
11130       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11131           DAG.getConstant(-(uint64_t)Align, VT));
11132     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11133
11134     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11135         DAG.getIntPtrConstant(0, true), SDValue(),
11136         SDLoc(Node));
11137
11138     SDValue Ops[2] = { Tmp1, Tmp2 };
11139     return DAG.getMergeValues(Ops, 2, dl);
11140   }
11141
11142   // Get the inputs.
11143   SDValue Chain = Op.getOperand(0);
11144   SDValue Size  = Op.getOperand(1);
11145   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11146   EVT VT = Op.getNode()->getValueType(0);
11147
11148   bool Is64Bit = Subtarget->is64Bit();
11149   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11150
11151   if (SplitStack) {
11152     MachineRegisterInfo &MRI = MF.getRegInfo();
11153
11154     if (Is64Bit) {
11155       // The 64 bit implementation of segmented stacks needs to clobber both r10
11156       // r11. This makes it impossible to use it along with nested parameters.
11157       const Function *F = MF.getFunction();
11158
11159       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11160            I != E; ++I)
11161         if (I->hasNestAttr())
11162           report_fatal_error("Cannot use segmented stacks with functions that "
11163                              "have nested arguments.");
11164     }
11165
11166     const TargetRegisterClass *AddrRegClass =
11167       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11168     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11169     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11170     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11171                                 DAG.getRegister(Vreg, SPTy));
11172     SDValue Ops1[2] = { Value, Chain };
11173     return DAG.getMergeValues(Ops1, 2, dl);
11174   } else {
11175     SDValue Flag;
11176     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11177
11178     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11179     Flag = Chain.getValue(1);
11180     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11181
11182     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11183
11184     const X86RegisterInfo *RegInfo =
11185       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11186     unsigned SPReg = RegInfo->getStackRegister();
11187     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11188     Chain = SP.getValue(1);
11189
11190     if (Align) {
11191       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11192                        DAG.getConstant(-(uint64_t)Align, VT));
11193       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11194     }
11195
11196     SDValue Ops1[2] = { SP, Chain };
11197     return DAG.getMergeValues(Ops1, 2, dl);
11198   }
11199 }
11200
11201 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11202   MachineFunction &MF = DAG.getMachineFunction();
11203   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11204
11205   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11206   SDLoc DL(Op);
11207
11208   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11209     // vastart just stores the address of the VarArgsFrameIndex slot into the
11210     // memory location argument.
11211     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11212                                    getPointerTy());
11213     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11214                         MachinePointerInfo(SV), false, false, 0);
11215   }
11216
11217   // __va_list_tag:
11218   //   gp_offset         (0 - 6 * 8)
11219   //   fp_offset         (48 - 48 + 8 * 16)
11220   //   overflow_arg_area (point to parameters coming in memory).
11221   //   reg_save_area
11222   SmallVector<SDValue, 8> MemOps;
11223   SDValue FIN = Op.getOperand(1);
11224   // Store gp_offset
11225   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11226                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11227                                                MVT::i32),
11228                                FIN, MachinePointerInfo(SV), false, false, 0);
11229   MemOps.push_back(Store);
11230
11231   // Store fp_offset
11232   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11233                     FIN, DAG.getIntPtrConstant(4));
11234   Store = DAG.getStore(Op.getOperand(0), DL,
11235                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11236                                        MVT::i32),
11237                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11238   MemOps.push_back(Store);
11239
11240   // Store ptr to overflow_arg_area
11241   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11242                     FIN, DAG.getIntPtrConstant(4));
11243   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11244                                     getPointerTy());
11245   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11246                        MachinePointerInfo(SV, 8),
11247                        false, false, 0);
11248   MemOps.push_back(Store);
11249
11250   // Store ptr to reg_save_area.
11251   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11252                     FIN, DAG.getIntPtrConstant(8));
11253   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11254                                     getPointerTy());
11255   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11256                        MachinePointerInfo(SV, 16), false, false, 0);
11257   MemOps.push_back(Store);
11258   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11259                      &MemOps[0], MemOps.size());
11260 }
11261
11262 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11263   assert(Subtarget->is64Bit() &&
11264          "LowerVAARG only handles 64-bit va_arg!");
11265   assert((Subtarget->isTargetLinux() ||
11266           Subtarget->isTargetDarwin()) &&
11267           "Unhandled target in LowerVAARG");
11268   assert(Op.getNode()->getNumOperands() == 4);
11269   SDValue Chain = Op.getOperand(0);
11270   SDValue SrcPtr = Op.getOperand(1);
11271   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11272   unsigned Align = Op.getConstantOperandVal(3);
11273   SDLoc dl(Op);
11274
11275   EVT ArgVT = Op.getNode()->getValueType(0);
11276   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11277   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11278   uint8_t ArgMode;
11279
11280   // Decide which area this value should be read from.
11281   // TODO: Implement the AMD64 ABI in its entirety. This simple
11282   // selection mechanism works only for the basic types.
11283   if (ArgVT == MVT::f80) {
11284     llvm_unreachable("va_arg for f80 not yet implemented");
11285   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11286     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11287   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11288     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11289   } else {
11290     llvm_unreachable("Unhandled argument type in LowerVAARG");
11291   }
11292
11293   if (ArgMode == 2) {
11294     // Sanity Check: Make sure using fp_offset makes sense.
11295     assert(!getTargetMachine().Options.UseSoftFloat &&
11296            !(DAG.getMachineFunction()
11297                 .getFunction()->getAttributes()
11298                 .hasAttribute(AttributeSet::FunctionIndex,
11299                               Attribute::NoImplicitFloat)) &&
11300            Subtarget->hasSSE1());
11301   }
11302
11303   // Insert VAARG_64 node into the DAG
11304   // VAARG_64 returns two values: Variable Argument Address, Chain
11305   SmallVector<SDValue, 11> InstOps;
11306   InstOps.push_back(Chain);
11307   InstOps.push_back(SrcPtr);
11308   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11309   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11310   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11311   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11312   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11313                                           VTs, &InstOps[0], InstOps.size(),
11314                                           MVT::i64,
11315                                           MachinePointerInfo(SV),
11316                                           /*Align=*/0,
11317                                           /*Volatile=*/false,
11318                                           /*ReadMem=*/true,
11319                                           /*WriteMem=*/true);
11320   Chain = VAARG.getValue(1);
11321
11322   // Load the next argument and return it
11323   return DAG.getLoad(ArgVT, dl,
11324                      Chain,
11325                      VAARG,
11326                      MachinePointerInfo(),
11327                      false, false, false, 0);
11328 }
11329
11330 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11331                            SelectionDAG &DAG) {
11332   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11333   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11334   SDValue Chain = Op.getOperand(0);
11335   SDValue DstPtr = Op.getOperand(1);
11336   SDValue SrcPtr = Op.getOperand(2);
11337   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11338   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11339   SDLoc DL(Op);
11340
11341   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11342                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11343                        false,
11344                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11345 }
11346
11347 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11348 // amount is a constant. Takes immediate version of shift as input.
11349 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11350                                           SDValue SrcOp, uint64_t ShiftAmt,
11351                                           SelectionDAG &DAG) {
11352   MVT ElementType = VT.getVectorElementType();
11353
11354   // Check for ShiftAmt >= element width
11355   if (ShiftAmt >= ElementType.getSizeInBits()) {
11356     if (Opc == X86ISD::VSRAI)
11357       ShiftAmt = ElementType.getSizeInBits() - 1;
11358     else
11359       return DAG.getConstant(0, VT);
11360   }
11361
11362   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11363          && "Unknown target vector shift-by-constant node");
11364
11365   // Fold this packed vector shift into a build vector if SrcOp is a
11366   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11367   if (VT == SrcOp.getSimpleValueType() &&
11368       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11369     SmallVector<SDValue, 8> Elts;
11370     unsigned NumElts = SrcOp->getNumOperands();
11371     ConstantSDNode *ND;
11372
11373     switch(Opc) {
11374     default: llvm_unreachable(0);
11375     case X86ISD::VSHLI:
11376       for (unsigned i=0; i!=NumElts; ++i) {
11377         SDValue CurrentOp = SrcOp->getOperand(i);
11378         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11379           Elts.push_back(CurrentOp);
11380           continue;
11381         }
11382         ND = cast<ConstantSDNode>(CurrentOp);
11383         const APInt &C = ND->getAPIntValue();
11384         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11385       }
11386       break;
11387     case X86ISD::VSRLI:
11388       for (unsigned i=0; i!=NumElts; ++i) {
11389         SDValue CurrentOp = SrcOp->getOperand(i);
11390         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11391           Elts.push_back(CurrentOp);
11392           continue;
11393         }
11394         ND = cast<ConstantSDNode>(CurrentOp);
11395         const APInt &C = ND->getAPIntValue();
11396         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11397       }
11398       break;
11399     case X86ISD::VSRAI:
11400       for (unsigned i=0; i!=NumElts; ++i) {
11401         SDValue CurrentOp = SrcOp->getOperand(i);
11402         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11403           Elts.push_back(CurrentOp);
11404           continue;
11405         }
11406         ND = cast<ConstantSDNode>(CurrentOp);
11407         const APInt &C = ND->getAPIntValue();
11408         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11409       }
11410       break;
11411     }
11412
11413     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11414   }
11415
11416   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11417 }
11418
11419 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11420 // may or may not be a constant. Takes immediate version of shift as input.
11421 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11422                                    SDValue SrcOp, SDValue ShAmt,
11423                                    SelectionDAG &DAG) {
11424   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11425
11426   // Catch shift-by-constant.
11427   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11428     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11429                                       CShAmt->getZExtValue(), DAG);
11430
11431   // Change opcode to non-immediate version
11432   switch (Opc) {
11433     default: llvm_unreachable("Unknown target vector shift node");
11434     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11435     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11436     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11437   }
11438
11439   // Need to build a vector containing shift amount
11440   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11441   SDValue ShOps[4];
11442   ShOps[0] = ShAmt;
11443   ShOps[1] = DAG.getConstant(0, MVT::i32);
11444   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11445   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11446
11447   // The return type has to be a 128-bit type with the same element
11448   // type as the input type.
11449   MVT EltVT = VT.getVectorElementType();
11450   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11451
11452   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11453   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11454 }
11455
11456 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11457   SDLoc dl(Op);
11458   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11459   switch (IntNo) {
11460   default: return SDValue();    // Don't custom lower most intrinsics.
11461   // Comparison intrinsics.
11462   case Intrinsic::x86_sse_comieq_ss:
11463   case Intrinsic::x86_sse_comilt_ss:
11464   case Intrinsic::x86_sse_comile_ss:
11465   case Intrinsic::x86_sse_comigt_ss:
11466   case Intrinsic::x86_sse_comige_ss:
11467   case Intrinsic::x86_sse_comineq_ss:
11468   case Intrinsic::x86_sse_ucomieq_ss:
11469   case Intrinsic::x86_sse_ucomilt_ss:
11470   case Intrinsic::x86_sse_ucomile_ss:
11471   case Intrinsic::x86_sse_ucomigt_ss:
11472   case Intrinsic::x86_sse_ucomige_ss:
11473   case Intrinsic::x86_sse_ucomineq_ss:
11474   case Intrinsic::x86_sse2_comieq_sd:
11475   case Intrinsic::x86_sse2_comilt_sd:
11476   case Intrinsic::x86_sse2_comile_sd:
11477   case Intrinsic::x86_sse2_comigt_sd:
11478   case Intrinsic::x86_sse2_comige_sd:
11479   case Intrinsic::x86_sse2_comineq_sd:
11480   case Intrinsic::x86_sse2_ucomieq_sd:
11481   case Intrinsic::x86_sse2_ucomilt_sd:
11482   case Intrinsic::x86_sse2_ucomile_sd:
11483   case Intrinsic::x86_sse2_ucomigt_sd:
11484   case Intrinsic::x86_sse2_ucomige_sd:
11485   case Intrinsic::x86_sse2_ucomineq_sd: {
11486     unsigned Opc;
11487     ISD::CondCode CC;
11488     switch (IntNo) {
11489     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11490     case Intrinsic::x86_sse_comieq_ss:
11491     case Intrinsic::x86_sse2_comieq_sd:
11492       Opc = X86ISD::COMI;
11493       CC = ISD::SETEQ;
11494       break;
11495     case Intrinsic::x86_sse_comilt_ss:
11496     case Intrinsic::x86_sse2_comilt_sd:
11497       Opc = X86ISD::COMI;
11498       CC = ISD::SETLT;
11499       break;
11500     case Intrinsic::x86_sse_comile_ss:
11501     case Intrinsic::x86_sse2_comile_sd:
11502       Opc = X86ISD::COMI;
11503       CC = ISD::SETLE;
11504       break;
11505     case Intrinsic::x86_sse_comigt_ss:
11506     case Intrinsic::x86_sse2_comigt_sd:
11507       Opc = X86ISD::COMI;
11508       CC = ISD::SETGT;
11509       break;
11510     case Intrinsic::x86_sse_comige_ss:
11511     case Intrinsic::x86_sse2_comige_sd:
11512       Opc = X86ISD::COMI;
11513       CC = ISD::SETGE;
11514       break;
11515     case Intrinsic::x86_sse_comineq_ss:
11516     case Intrinsic::x86_sse2_comineq_sd:
11517       Opc = X86ISD::COMI;
11518       CC = ISD::SETNE;
11519       break;
11520     case Intrinsic::x86_sse_ucomieq_ss:
11521     case Intrinsic::x86_sse2_ucomieq_sd:
11522       Opc = X86ISD::UCOMI;
11523       CC = ISD::SETEQ;
11524       break;
11525     case Intrinsic::x86_sse_ucomilt_ss:
11526     case Intrinsic::x86_sse2_ucomilt_sd:
11527       Opc = X86ISD::UCOMI;
11528       CC = ISD::SETLT;
11529       break;
11530     case Intrinsic::x86_sse_ucomile_ss:
11531     case Intrinsic::x86_sse2_ucomile_sd:
11532       Opc = X86ISD::UCOMI;
11533       CC = ISD::SETLE;
11534       break;
11535     case Intrinsic::x86_sse_ucomigt_ss:
11536     case Intrinsic::x86_sse2_ucomigt_sd:
11537       Opc = X86ISD::UCOMI;
11538       CC = ISD::SETGT;
11539       break;
11540     case Intrinsic::x86_sse_ucomige_ss:
11541     case Intrinsic::x86_sse2_ucomige_sd:
11542       Opc = X86ISD::UCOMI;
11543       CC = ISD::SETGE;
11544       break;
11545     case Intrinsic::x86_sse_ucomineq_ss:
11546     case Intrinsic::x86_sse2_ucomineq_sd:
11547       Opc = X86ISD::UCOMI;
11548       CC = ISD::SETNE;
11549       break;
11550     }
11551
11552     SDValue LHS = Op.getOperand(1);
11553     SDValue RHS = Op.getOperand(2);
11554     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11555     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11556     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11557     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11558                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11559     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11560   }
11561
11562   // Arithmetic intrinsics.
11563   case Intrinsic::x86_sse2_pmulu_dq:
11564   case Intrinsic::x86_avx2_pmulu_dq:
11565     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11566                        Op.getOperand(1), Op.getOperand(2));
11567
11568   // SSE2/AVX2 sub with unsigned saturation intrinsics
11569   case Intrinsic::x86_sse2_psubus_b:
11570   case Intrinsic::x86_sse2_psubus_w:
11571   case Intrinsic::x86_avx2_psubus_b:
11572   case Intrinsic::x86_avx2_psubus_w:
11573     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11574                        Op.getOperand(1), Op.getOperand(2));
11575
11576   // SSE3/AVX horizontal add/sub intrinsics
11577   case Intrinsic::x86_sse3_hadd_ps:
11578   case Intrinsic::x86_sse3_hadd_pd:
11579   case Intrinsic::x86_avx_hadd_ps_256:
11580   case Intrinsic::x86_avx_hadd_pd_256:
11581   case Intrinsic::x86_sse3_hsub_ps:
11582   case Intrinsic::x86_sse3_hsub_pd:
11583   case Intrinsic::x86_avx_hsub_ps_256:
11584   case Intrinsic::x86_avx_hsub_pd_256:
11585   case Intrinsic::x86_ssse3_phadd_w_128:
11586   case Intrinsic::x86_ssse3_phadd_d_128:
11587   case Intrinsic::x86_avx2_phadd_w:
11588   case Intrinsic::x86_avx2_phadd_d:
11589   case Intrinsic::x86_ssse3_phsub_w_128:
11590   case Intrinsic::x86_ssse3_phsub_d_128:
11591   case Intrinsic::x86_avx2_phsub_w:
11592   case Intrinsic::x86_avx2_phsub_d: {
11593     unsigned Opcode;
11594     switch (IntNo) {
11595     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11596     case Intrinsic::x86_sse3_hadd_ps:
11597     case Intrinsic::x86_sse3_hadd_pd:
11598     case Intrinsic::x86_avx_hadd_ps_256:
11599     case Intrinsic::x86_avx_hadd_pd_256:
11600       Opcode = X86ISD::FHADD;
11601       break;
11602     case Intrinsic::x86_sse3_hsub_ps:
11603     case Intrinsic::x86_sse3_hsub_pd:
11604     case Intrinsic::x86_avx_hsub_ps_256:
11605     case Intrinsic::x86_avx_hsub_pd_256:
11606       Opcode = X86ISD::FHSUB;
11607       break;
11608     case Intrinsic::x86_ssse3_phadd_w_128:
11609     case Intrinsic::x86_ssse3_phadd_d_128:
11610     case Intrinsic::x86_avx2_phadd_w:
11611     case Intrinsic::x86_avx2_phadd_d:
11612       Opcode = X86ISD::HADD;
11613       break;
11614     case Intrinsic::x86_ssse3_phsub_w_128:
11615     case Intrinsic::x86_ssse3_phsub_d_128:
11616     case Intrinsic::x86_avx2_phsub_w:
11617     case Intrinsic::x86_avx2_phsub_d:
11618       Opcode = X86ISD::HSUB;
11619       break;
11620     }
11621     return DAG.getNode(Opcode, dl, Op.getValueType(),
11622                        Op.getOperand(1), Op.getOperand(2));
11623   }
11624
11625   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11626   case Intrinsic::x86_sse2_pmaxu_b:
11627   case Intrinsic::x86_sse41_pmaxuw:
11628   case Intrinsic::x86_sse41_pmaxud:
11629   case Intrinsic::x86_avx2_pmaxu_b:
11630   case Intrinsic::x86_avx2_pmaxu_w:
11631   case Intrinsic::x86_avx2_pmaxu_d:
11632   case Intrinsic::x86_sse2_pminu_b:
11633   case Intrinsic::x86_sse41_pminuw:
11634   case Intrinsic::x86_sse41_pminud:
11635   case Intrinsic::x86_avx2_pminu_b:
11636   case Intrinsic::x86_avx2_pminu_w:
11637   case Intrinsic::x86_avx2_pminu_d:
11638   case Intrinsic::x86_sse41_pmaxsb:
11639   case Intrinsic::x86_sse2_pmaxs_w:
11640   case Intrinsic::x86_sse41_pmaxsd:
11641   case Intrinsic::x86_avx2_pmaxs_b:
11642   case Intrinsic::x86_avx2_pmaxs_w:
11643   case Intrinsic::x86_avx2_pmaxs_d:
11644   case Intrinsic::x86_sse41_pminsb:
11645   case Intrinsic::x86_sse2_pmins_w:
11646   case Intrinsic::x86_sse41_pminsd:
11647   case Intrinsic::x86_avx2_pmins_b:
11648   case Intrinsic::x86_avx2_pmins_w:
11649   case Intrinsic::x86_avx2_pmins_d: {
11650     unsigned Opcode;
11651     switch (IntNo) {
11652     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11653     case Intrinsic::x86_sse2_pmaxu_b:
11654     case Intrinsic::x86_sse41_pmaxuw:
11655     case Intrinsic::x86_sse41_pmaxud:
11656     case Intrinsic::x86_avx2_pmaxu_b:
11657     case Intrinsic::x86_avx2_pmaxu_w:
11658     case Intrinsic::x86_avx2_pmaxu_d:
11659       Opcode = X86ISD::UMAX;
11660       break;
11661     case Intrinsic::x86_sse2_pminu_b:
11662     case Intrinsic::x86_sse41_pminuw:
11663     case Intrinsic::x86_sse41_pminud:
11664     case Intrinsic::x86_avx2_pminu_b:
11665     case Intrinsic::x86_avx2_pminu_w:
11666     case Intrinsic::x86_avx2_pminu_d:
11667       Opcode = X86ISD::UMIN;
11668       break;
11669     case Intrinsic::x86_sse41_pmaxsb:
11670     case Intrinsic::x86_sse2_pmaxs_w:
11671     case Intrinsic::x86_sse41_pmaxsd:
11672     case Intrinsic::x86_avx2_pmaxs_b:
11673     case Intrinsic::x86_avx2_pmaxs_w:
11674     case Intrinsic::x86_avx2_pmaxs_d:
11675       Opcode = X86ISD::SMAX;
11676       break;
11677     case Intrinsic::x86_sse41_pminsb:
11678     case Intrinsic::x86_sse2_pmins_w:
11679     case Intrinsic::x86_sse41_pminsd:
11680     case Intrinsic::x86_avx2_pmins_b:
11681     case Intrinsic::x86_avx2_pmins_w:
11682     case Intrinsic::x86_avx2_pmins_d:
11683       Opcode = X86ISD::SMIN;
11684       break;
11685     }
11686     return DAG.getNode(Opcode, dl, Op.getValueType(),
11687                        Op.getOperand(1), Op.getOperand(2));
11688   }
11689
11690   // SSE/SSE2/AVX floating point max/min intrinsics.
11691   case Intrinsic::x86_sse_max_ps:
11692   case Intrinsic::x86_sse2_max_pd:
11693   case Intrinsic::x86_avx_max_ps_256:
11694   case Intrinsic::x86_avx_max_pd_256:
11695   case Intrinsic::x86_sse_min_ps:
11696   case Intrinsic::x86_sse2_min_pd:
11697   case Intrinsic::x86_avx_min_ps_256:
11698   case Intrinsic::x86_avx_min_pd_256: {
11699     unsigned Opcode;
11700     switch (IntNo) {
11701     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11702     case Intrinsic::x86_sse_max_ps:
11703     case Intrinsic::x86_sse2_max_pd:
11704     case Intrinsic::x86_avx_max_ps_256:
11705     case Intrinsic::x86_avx_max_pd_256:
11706       Opcode = X86ISD::FMAX;
11707       break;
11708     case Intrinsic::x86_sse_min_ps:
11709     case Intrinsic::x86_sse2_min_pd:
11710     case Intrinsic::x86_avx_min_ps_256:
11711     case Intrinsic::x86_avx_min_pd_256:
11712       Opcode = X86ISD::FMIN;
11713       break;
11714     }
11715     return DAG.getNode(Opcode, dl, Op.getValueType(),
11716                        Op.getOperand(1), Op.getOperand(2));
11717   }
11718
11719   // AVX2 variable shift intrinsics
11720   case Intrinsic::x86_avx2_psllv_d:
11721   case Intrinsic::x86_avx2_psllv_q:
11722   case Intrinsic::x86_avx2_psllv_d_256:
11723   case Intrinsic::x86_avx2_psllv_q_256:
11724   case Intrinsic::x86_avx2_psrlv_d:
11725   case Intrinsic::x86_avx2_psrlv_q:
11726   case Intrinsic::x86_avx2_psrlv_d_256:
11727   case Intrinsic::x86_avx2_psrlv_q_256:
11728   case Intrinsic::x86_avx2_psrav_d:
11729   case Intrinsic::x86_avx2_psrav_d_256: {
11730     unsigned Opcode;
11731     switch (IntNo) {
11732     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11733     case Intrinsic::x86_avx2_psllv_d:
11734     case Intrinsic::x86_avx2_psllv_q:
11735     case Intrinsic::x86_avx2_psllv_d_256:
11736     case Intrinsic::x86_avx2_psllv_q_256:
11737       Opcode = ISD::SHL;
11738       break;
11739     case Intrinsic::x86_avx2_psrlv_d:
11740     case Intrinsic::x86_avx2_psrlv_q:
11741     case Intrinsic::x86_avx2_psrlv_d_256:
11742     case Intrinsic::x86_avx2_psrlv_q_256:
11743       Opcode = ISD::SRL;
11744       break;
11745     case Intrinsic::x86_avx2_psrav_d:
11746     case Intrinsic::x86_avx2_psrav_d_256:
11747       Opcode = ISD::SRA;
11748       break;
11749     }
11750     return DAG.getNode(Opcode, dl, Op.getValueType(),
11751                        Op.getOperand(1), Op.getOperand(2));
11752   }
11753
11754   case Intrinsic::x86_ssse3_pshuf_b_128:
11755   case Intrinsic::x86_avx2_pshuf_b:
11756     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11757                        Op.getOperand(1), Op.getOperand(2));
11758
11759   case Intrinsic::x86_ssse3_psign_b_128:
11760   case Intrinsic::x86_ssse3_psign_w_128:
11761   case Intrinsic::x86_ssse3_psign_d_128:
11762   case Intrinsic::x86_avx2_psign_b:
11763   case Intrinsic::x86_avx2_psign_w:
11764   case Intrinsic::x86_avx2_psign_d:
11765     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11766                        Op.getOperand(1), Op.getOperand(2));
11767
11768   case Intrinsic::x86_sse41_insertps:
11769     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11770                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11771
11772   case Intrinsic::x86_avx_vperm2f128_ps_256:
11773   case Intrinsic::x86_avx_vperm2f128_pd_256:
11774   case Intrinsic::x86_avx_vperm2f128_si_256:
11775   case Intrinsic::x86_avx2_vperm2i128:
11776     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11777                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11778
11779   case Intrinsic::x86_avx2_permd:
11780   case Intrinsic::x86_avx2_permps:
11781     // Operands intentionally swapped. Mask is last operand to intrinsic,
11782     // but second operand for node/instruction.
11783     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11784                        Op.getOperand(2), Op.getOperand(1));
11785
11786   case Intrinsic::x86_sse_sqrt_ps:
11787   case Intrinsic::x86_sse2_sqrt_pd:
11788   case Intrinsic::x86_avx_sqrt_ps_256:
11789   case Intrinsic::x86_avx_sqrt_pd_256:
11790     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11791
11792   // ptest and testp intrinsics. The intrinsic these come from are designed to
11793   // return an integer value, not just an instruction so lower it to the ptest
11794   // or testp pattern and a setcc for the result.
11795   case Intrinsic::x86_sse41_ptestz:
11796   case Intrinsic::x86_sse41_ptestc:
11797   case Intrinsic::x86_sse41_ptestnzc:
11798   case Intrinsic::x86_avx_ptestz_256:
11799   case Intrinsic::x86_avx_ptestc_256:
11800   case Intrinsic::x86_avx_ptestnzc_256:
11801   case Intrinsic::x86_avx_vtestz_ps:
11802   case Intrinsic::x86_avx_vtestc_ps:
11803   case Intrinsic::x86_avx_vtestnzc_ps:
11804   case Intrinsic::x86_avx_vtestz_pd:
11805   case Intrinsic::x86_avx_vtestc_pd:
11806   case Intrinsic::x86_avx_vtestnzc_pd:
11807   case Intrinsic::x86_avx_vtestz_ps_256:
11808   case Intrinsic::x86_avx_vtestc_ps_256:
11809   case Intrinsic::x86_avx_vtestnzc_ps_256:
11810   case Intrinsic::x86_avx_vtestz_pd_256:
11811   case Intrinsic::x86_avx_vtestc_pd_256:
11812   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11813     bool IsTestPacked = false;
11814     unsigned X86CC;
11815     switch (IntNo) {
11816     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11817     case Intrinsic::x86_avx_vtestz_ps:
11818     case Intrinsic::x86_avx_vtestz_pd:
11819     case Intrinsic::x86_avx_vtestz_ps_256:
11820     case Intrinsic::x86_avx_vtestz_pd_256:
11821       IsTestPacked = true; // Fallthrough
11822     case Intrinsic::x86_sse41_ptestz:
11823     case Intrinsic::x86_avx_ptestz_256:
11824       // ZF = 1
11825       X86CC = X86::COND_E;
11826       break;
11827     case Intrinsic::x86_avx_vtestc_ps:
11828     case Intrinsic::x86_avx_vtestc_pd:
11829     case Intrinsic::x86_avx_vtestc_ps_256:
11830     case Intrinsic::x86_avx_vtestc_pd_256:
11831       IsTestPacked = true; // Fallthrough
11832     case Intrinsic::x86_sse41_ptestc:
11833     case Intrinsic::x86_avx_ptestc_256:
11834       // CF = 1
11835       X86CC = X86::COND_B;
11836       break;
11837     case Intrinsic::x86_avx_vtestnzc_ps:
11838     case Intrinsic::x86_avx_vtestnzc_pd:
11839     case Intrinsic::x86_avx_vtestnzc_ps_256:
11840     case Intrinsic::x86_avx_vtestnzc_pd_256:
11841       IsTestPacked = true; // Fallthrough
11842     case Intrinsic::x86_sse41_ptestnzc:
11843     case Intrinsic::x86_avx_ptestnzc_256:
11844       // ZF and CF = 0
11845       X86CC = X86::COND_A;
11846       break;
11847     }
11848
11849     SDValue LHS = Op.getOperand(1);
11850     SDValue RHS = Op.getOperand(2);
11851     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11852     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11853     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11854     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11855     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11856   }
11857   case Intrinsic::x86_avx512_kortestz_w:
11858   case Intrinsic::x86_avx512_kortestc_w: {
11859     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11860     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11861     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11862     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11863     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11864     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11865     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11866   }
11867
11868   // SSE/AVX shift intrinsics
11869   case Intrinsic::x86_sse2_psll_w:
11870   case Intrinsic::x86_sse2_psll_d:
11871   case Intrinsic::x86_sse2_psll_q:
11872   case Intrinsic::x86_avx2_psll_w:
11873   case Intrinsic::x86_avx2_psll_d:
11874   case Intrinsic::x86_avx2_psll_q:
11875   case Intrinsic::x86_sse2_psrl_w:
11876   case Intrinsic::x86_sse2_psrl_d:
11877   case Intrinsic::x86_sse2_psrl_q:
11878   case Intrinsic::x86_avx2_psrl_w:
11879   case Intrinsic::x86_avx2_psrl_d:
11880   case Intrinsic::x86_avx2_psrl_q:
11881   case Intrinsic::x86_sse2_psra_w:
11882   case Intrinsic::x86_sse2_psra_d:
11883   case Intrinsic::x86_avx2_psra_w:
11884   case Intrinsic::x86_avx2_psra_d: {
11885     unsigned Opcode;
11886     switch (IntNo) {
11887     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11888     case Intrinsic::x86_sse2_psll_w:
11889     case Intrinsic::x86_sse2_psll_d:
11890     case Intrinsic::x86_sse2_psll_q:
11891     case Intrinsic::x86_avx2_psll_w:
11892     case Intrinsic::x86_avx2_psll_d:
11893     case Intrinsic::x86_avx2_psll_q:
11894       Opcode = X86ISD::VSHL;
11895       break;
11896     case Intrinsic::x86_sse2_psrl_w:
11897     case Intrinsic::x86_sse2_psrl_d:
11898     case Intrinsic::x86_sse2_psrl_q:
11899     case Intrinsic::x86_avx2_psrl_w:
11900     case Intrinsic::x86_avx2_psrl_d:
11901     case Intrinsic::x86_avx2_psrl_q:
11902       Opcode = X86ISD::VSRL;
11903       break;
11904     case Intrinsic::x86_sse2_psra_w:
11905     case Intrinsic::x86_sse2_psra_d:
11906     case Intrinsic::x86_avx2_psra_w:
11907     case Intrinsic::x86_avx2_psra_d:
11908       Opcode = X86ISD::VSRA;
11909       break;
11910     }
11911     return DAG.getNode(Opcode, dl, Op.getValueType(),
11912                        Op.getOperand(1), Op.getOperand(2));
11913   }
11914
11915   // SSE/AVX immediate shift intrinsics
11916   case Intrinsic::x86_sse2_pslli_w:
11917   case Intrinsic::x86_sse2_pslli_d:
11918   case Intrinsic::x86_sse2_pslli_q:
11919   case Intrinsic::x86_avx2_pslli_w:
11920   case Intrinsic::x86_avx2_pslli_d:
11921   case Intrinsic::x86_avx2_pslli_q:
11922   case Intrinsic::x86_sse2_psrli_w:
11923   case Intrinsic::x86_sse2_psrli_d:
11924   case Intrinsic::x86_sse2_psrli_q:
11925   case Intrinsic::x86_avx2_psrli_w:
11926   case Intrinsic::x86_avx2_psrli_d:
11927   case Intrinsic::x86_avx2_psrli_q:
11928   case Intrinsic::x86_sse2_psrai_w:
11929   case Intrinsic::x86_sse2_psrai_d:
11930   case Intrinsic::x86_avx2_psrai_w:
11931   case Intrinsic::x86_avx2_psrai_d: {
11932     unsigned Opcode;
11933     switch (IntNo) {
11934     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11935     case Intrinsic::x86_sse2_pslli_w:
11936     case Intrinsic::x86_sse2_pslli_d:
11937     case Intrinsic::x86_sse2_pslli_q:
11938     case Intrinsic::x86_avx2_pslli_w:
11939     case Intrinsic::x86_avx2_pslli_d:
11940     case Intrinsic::x86_avx2_pslli_q:
11941       Opcode = X86ISD::VSHLI;
11942       break;
11943     case Intrinsic::x86_sse2_psrli_w:
11944     case Intrinsic::x86_sse2_psrli_d:
11945     case Intrinsic::x86_sse2_psrli_q:
11946     case Intrinsic::x86_avx2_psrli_w:
11947     case Intrinsic::x86_avx2_psrli_d:
11948     case Intrinsic::x86_avx2_psrli_q:
11949       Opcode = X86ISD::VSRLI;
11950       break;
11951     case Intrinsic::x86_sse2_psrai_w:
11952     case Intrinsic::x86_sse2_psrai_d:
11953     case Intrinsic::x86_avx2_psrai_w:
11954     case Intrinsic::x86_avx2_psrai_d:
11955       Opcode = X86ISD::VSRAI;
11956       break;
11957     }
11958     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11959                                Op.getOperand(1), Op.getOperand(2), DAG);
11960   }
11961
11962   case Intrinsic::x86_sse42_pcmpistria128:
11963   case Intrinsic::x86_sse42_pcmpestria128:
11964   case Intrinsic::x86_sse42_pcmpistric128:
11965   case Intrinsic::x86_sse42_pcmpestric128:
11966   case Intrinsic::x86_sse42_pcmpistrio128:
11967   case Intrinsic::x86_sse42_pcmpestrio128:
11968   case Intrinsic::x86_sse42_pcmpistris128:
11969   case Intrinsic::x86_sse42_pcmpestris128:
11970   case Intrinsic::x86_sse42_pcmpistriz128:
11971   case Intrinsic::x86_sse42_pcmpestriz128: {
11972     unsigned Opcode;
11973     unsigned X86CC;
11974     switch (IntNo) {
11975     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11976     case Intrinsic::x86_sse42_pcmpistria128:
11977       Opcode = X86ISD::PCMPISTRI;
11978       X86CC = X86::COND_A;
11979       break;
11980     case Intrinsic::x86_sse42_pcmpestria128:
11981       Opcode = X86ISD::PCMPESTRI;
11982       X86CC = X86::COND_A;
11983       break;
11984     case Intrinsic::x86_sse42_pcmpistric128:
11985       Opcode = X86ISD::PCMPISTRI;
11986       X86CC = X86::COND_B;
11987       break;
11988     case Intrinsic::x86_sse42_pcmpestric128:
11989       Opcode = X86ISD::PCMPESTRI;
11990       X86CC = X86::COND_B;
11991       break;
11992     case Intrinsic::x86_sse42_pcmpistrio128:
11993       Opcode = X86ISD::PCMPISTRI;
11994       X86CC = X86::COND_O;
11995       break;
11996     case Intrinsic::x86_sse42_pcmpestrio128:
11997       Opcode = X86ISD::PCMPESTRI;
11998       X86CC = X86::COND_O;
11999       break;
12000     case Intrinsic::x86_sse42_pcmpistris128:
12001       Opcode = X86ISD::PCMPISTRI;
12002       X86CC = X86::COND_S;
12003       break;
12004     case Intrinsic::x86_sse42_pcmpestris128:
12005       Opcode = X86ISD::PCMPESTRI;
12006       X86CC = X86::COND_S;
12007       break;
12008     case Intrinsic::x86_sse42_pcmpistriz128:
12009       Opcode = X86ISD::PCMPISTRI;
12010       X86CC = X86::COND_E;
12011       break;
12012     case Intrinsic::x86_sse42_pcmpestriz128:
12013       Opcode = X86ISD::PCMPESTRI;
12014       X86CC = X86::COND_E;
12015       break;
12016     }
12017     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12018     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12019     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12020     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12021                                 DAG.getConstant(X86CC, MVT::i8),
12022                                 SDValue(PCMP.getNode(), 1));
12023     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12024   }
12025
12026   case Intrinsic::x86_sse42_pcmpistri128:
12027   case Intrinsic::x86_sse42_pcmpestri128: {
12028     unsigned Opcode;
12029     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12030       Opcode = X86ISD::PCMPISTRI;
12031     else
12032       Opcode = X86ISD::PCMPESTRI;
12033
12034     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12035     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12036     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12037   }
12038   case Intrinsic::x86_fma_vfmadd_ps:
12039   case Intrinsic::x86_fma_vfmadd_pd:
12040   case Intrinsic::x86_fma_vfmsub_ps:
12041   case Intrinsic::x86_fma_vfmsub_pd:
12042   case Intrinsic::x86_fma_vfnmadd_ps:
12043   case Intrinsic::x86_fma_vfnmadd_pd:
12044   case Intrinsic::x86_fma_vfnmsub_ps:
12045   case Intrinsic::x86_fma_vfnmsub_pd:
12046   case Intrinsic::x86_fma_vfmaddsub_ps:
12047   case Intrinsic::x86_fma_vfmaddsub_pd:
12048   case Intrinsic::x86_fma_vfmsubadd_ps:
12049   case Intrinsic::x86_fma_vfmsubadd_pd:
12050   case Intrinsic::x86_fma_vfmadd_ps_256:
12051   case Intrinsic::x86_fma_vfmadd_pd_256:
12052   case Intrinsic::x86_fma_vfmsub_ps_256:
12053   case Intrinsic::x86_fma_vfmsub_pd_256:
12054   case Intrinsic::x86_fma_vfnmadd_ps_256:
12055   case Intrinsic::x86_fma_vfnmadd_pd_256:
12056   case Intrinsic::x86_fma_vfnmsub_ps_256:
12057   case Intrinsic::x86_fma_vfnmsub_pd_256:
12058   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12059   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12060   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12061   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12062   case Intrinsic::x86_fma_vfmadd_ps_512:
12063   case Intrinsic::x86_fma_vfmadd_pd_512:
12064   case Intrinsic::x86_fma_vfmsub_ps_512:
12065   case Intrinsic::x86_fma_vfmsub_pd_512:
12066   case Intrinsic::x86_fma_vfnmadd_ps_512:
12067   case Intrinsic::x86_fma_vfnmadd_pd_512:
12068   case Intrinsic::x86_fma_vfnmsub_ps_512:
12069   case Intrinsic::x86_fma_vfnmsub_pd_512:
12070   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12071   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12072   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12073   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12074     unsigned Opc;
12075     switch (IntNo) {
12076     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12077     case Intrinsic::x86_fma_vfmadd_ps:
12078     case Intrinsic::x86_fma_vfmadd_pd:
12079     case Intrinsic::x86_fma_vfmadd_ps_256:
12080     case Intrinsic::x86_fma_vfmadd_pd_256:
12081     case Intrinsic::x86_fma_vfmadd_ps_512:
12082     case Intrinsic::x86_fma_vfmadd_pd_512:
12083       Opc = X86ISD::FMADD;
12084       break;
12085     case Intrinsic::x86_fma_vfmsub_ps:
12086     case Intrinsic::x86_fma_vfmsub_pd:
12087     case Intrinsic::x86_fma_vfmsub_ps_256:
12088     case Intrinsic::x86_fma_vfmsub_pd_256:
12089     case Intrinsic::x86_fma_vfmsub_ps_512:
12090     case Intrinsic::x86_fma_vfmsub_pd_512:
12091       Opc = X86ISD::FMSUB;
12092       break;
12093     case Intrinsic::x86_fma_vfnmadd_ps:
12094     case Intrinsic::x86_fma_vfnmadd_pd:
12095     case Intrinsic::x86_fma_vfnmadd_ps_256:
12096     case Intrinsic::x86_fma_vfnmadd_pd_256:
12097     case Intrinsic::x86_fma_vfnmadd_ps_512:
12098     case Intrinsic::x86_fma_vfnmadd_pd_512:
12099       Opc = X86ISD::FNMADD;
12100       break;
12101     case Intrinsic::x86_fma_vfnmsub_ps:
12102     case Intrinsic::x86_fma_vfnmsub_pd:
12103     case Intrinsic::x86_fma_vfnmsub_ps_256:
12104     case Intrinsic::x86_fma_vfnmsub_pd_256:
12105     case Intrinsic::x86_fma_vfnmsub_ps_512:
12106     case Intrinsic::x86_fma_vfnmsub_pd_512:
12107       Opc = X86ISD::FNMSUB;
12108       break;
12109     case Intrinsic::x86_fma_vfmaddsub_ps:
12110     case Intrinsic::x86_fma_vfmaddsub_pd:
12111     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12112     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12113     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12114     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12115       Opc = X86ISD::FMADDSUB;
12116       break;
12117     case Intrinsic::x86_fma_vfmsubadd_ps:
12118     case Intrinsic::x86_fma_vfmsubadd_pd:
12119     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12120     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12121     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12122     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12123       Opc = X86ISD::FMSUBADD;
12124       break;
12125     }
12126
12127     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12128                        Op.getOperand(2), Op.getOperand(3));
12129   }
12130   }
12131 }
12132
12133 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12134                              SDValue Base, SDValue Index,
12135                              SDValue ScaleOp, SDValue Chain,
12136                              const X86Subtarget * Subtarget) {
12137   SDLoc dl(Op);
12138   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12139   assert(C && "Invalid scale type");
12140   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12141   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12142   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12143                              Index.getSimpleValueType().getVectorNumElements());
12144   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12145   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12146   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12147   SDValue Segment = DAG.getRegister(0, MVT::i32);
12148   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12149   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12150   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12151   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12152 }
12153
12154 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12155                               SDValue Src, SDValue Mask, SDValue Base,
12156                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12157                               const X86Subtarget * Subtarget) {
12158   SDLoc dl(Op);
12159   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12160   assert(C && "Invalid scale type");
12161   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12162   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12163                              Index.getSimpleValueType().getVectorNumElements());
12164   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12165   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12166   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12167   SDValue Segment = DAG.getRegister(0, MVT::i32);
12168   if (Src.getOpcode() == ISD::UNDEF)
12169     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12170   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12171   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12172   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12173   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12174 }
12175
12176 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12177                               SDValue Src, SDValue Base, SDValue Index,
12178                               SDValue ScaleOp, SDValue Chain) {
12179   SDLoc dl(Op);
12180   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12181   assert(C && "Invalid scale type");
12182   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12183   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12184   SDValue Segment = DAG.getRegister(0, MVT::i32);
12185   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12186                              Index.getSimpleValueType().getVectorNumElements());
12187   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12188   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12189   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12190   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12191   return SDValue(Res, 1);
12192 }
12193
12194 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12195                                SDValue Src, SDValue Mask, SDValue Base,
12196                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12197   SDLoc dl(Op);
12198   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12199   assert(C && "Invalid scale type");
12200   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12201   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12202   SDValue Segment = DAG.getRegister(0, MVT::i32);
12203   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12204                              Index.getSimpleValueType().getVectorNumElements());
12205   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12206   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12207   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12208   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12209   return SDValue(Res, 1);
12210 }
12211
12212 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12213                                       SelectionDAG &DAG) {
12214   SDLoc dl(Op);
12215   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12216   switch (IntNo) {
12217   default: return SDValue();    // Don't custom lower most intrinsics.
12218
12219   // RDRAND/RDSEED intrinsics.
12220   case Intrinsic::x86_rdrand_16:
12221   case Intrinsic::x86_rdrand_32:
12222   case Intrinsic::x86_rdrand_64:
12223   case Intrinsic::x86_rdseed_16:
12224   case Intrinsic::x86_rdseed_32:
12225   case Intrinsic::x86_rdseed_64: {
12226     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12227                        IntNo == Intrinsic::x86_rdseed_32 ||
12228                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12229                                                             X86ISD::RDRAND;
12230     // Emit the node with the right value type.
12231     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12232     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12233
12234     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12235     // Otherwise return the value from Rand, which is always 0, casted to i32.
12236     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12237                       DAG.getConstant(1, Op->getValueType(1)),
12238                       DAG.getConstant(X86::COND_B, MVT::i32),
12239                       SDValue(Result.getNode(), 1) };
12240     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12241                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12242                                   Ops, array_lengthof(Ops));
12243
12244     // Return { result, isValid, chain }.
12245     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12246                        SDValue(Result.getNode(), 2));
12247   }
12248   //int_gather(index, base, scale);
12249   case Intrinsic::x86_avx512_gather_qpd_512:
12250   case Intrinsic::x86_avx512_gather_qps_512:
12251   case Intrinsic::x86_avx512_gather_dpd_512:
12252   case Intrinsic::x86_avx512_gather_qpi_512:
12253   case Intrinsic::x86_avx512_gather_qpq_512:
12254   case Intrinsic::x86_avx512_gather_dpq_512:
12255   case Intrinsic::x86_avx512_gather_dps_512:
12256   case Intrinsic::x86_avx512_gather_dpi_512: {
12257     unsigned Opc;
12258     switch (IntNo) {
12259     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12260     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12261     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12262     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12263     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12264     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12265     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12266     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12267     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12268     }
12269     SDValue Chain = Op.getOperand(0);
12270     SDValue Index = Op.getOperand(2);
12271     SDValue Base  = Op.getOperand(3);
12272     SDValue Scale = Op.getOperand(4);
12273     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12274   }
12275   //int_gather_mask(v1, mask, index, base, scale);
12276   case Intrinsic::x86_avx512_gather_qps_mask_512:
12277   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12278   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12279   case Intrinsic::x86_avx512_gather_dps_mask_512:
12280   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12281   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12282   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12283   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12284     unsigned Opc;
12285     switch (IntNo) {
12286     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12287     case Intrinsic::x86_avx512_gather_qps_mask_512:
12288       Opc = X86::VGATHERQPSZrm; break;
12289     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12290       Opc = X86::VGATHERQPDZrm; break;
12291     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12292       Opc = X86::VGATHERDPDZrm; break;
12293     case Intrinsic::x86_avx512_gather_dps_mask_512:
12294       Opc = X86::VGATHERDPSZrm; break;
12295     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12296       Opc = X86::VPGATHERQDZrm; break;
12297     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12298       Opc = X86::VPGATHERQQZrm; break;
12299     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12300       Opc = X86::VPGATHERDDZrm; break;
12301     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12302       Opc = X86::VPGATHERDQZrm; break;
12303     }
12304     SDValue Chain = Op.getOperand(0);
12305     SDValue Src   = Op.getOperand(2);
12306     SDValue Mask  = Op.getOperand(3);
12307     SDValue Index = Op.getOperand(4);
12308     SDValue Base  = Op.getOperand(5);
12309     SDValue Scale = Op.getOperand(6);
12310     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12311                           Subtarget);
12312   }
12313   //int_scatter(base, index, v1, scale);
12314   case Intrinsic::x86_avx512_scatter_qpd_512:
12315   case Intrinsic::x86_avx512_scatter_qps_512:
12316   case Intrinsic::x86_avx512_scatter_dpd_512:
12317   case Intrinsic::x86_avx512_scatter_qpi_512:
12318   case Intrinsic::x86_avx512_scatter_qpq_512:
12319   case Intrinsic::x86_avx512_scatter_dpq_512:
12320   case Intrinsic::x86_avx512_scatter_dps_512:
12321   case Intrinsic::x86_avx512_scatter_dpi_512: {
12322     unsigned Opc;
12323     switch (IntNo) {
12324     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12325     case Intrinsic::x86_avx512_scatter_qpd_512:
12326       Opc = X86::VSCATTERQPDZmr; break;
12327     case Intrinsic::x86_avx512_scatter_qps_512:
12328       Opc = X86::VSCATTERQPSZmr; break;
12329     case Intrinsic::x86_avx512_scatter_dpd_512:
12330       Opc = X86::VSCATTERDPDZmr; break;
12331     case Intrinsic::x86_avx512_scatter_dps_512:
12332       Opc = X86::VSCATTERDPSZmr; break;
12333     case Intrinsic::x86_avx512_scatter_qpi_512:
12334       Opc = X86::VPSCATTERQDZmr; break;
12335     case Intrinsic::x86_avx512_scatter_qpq_512:
12336       Opc = X86::VPSCATTERQQZmr; break;
12337     case Intrinsic::x86_avx512_scatter_dpq_512:
12338       Opc = X86::VPSCATTERDQZmr; break;
12339     case Intrinsic::x86_avx512_scatter_dpi_512:
12340       Opc = X86::VPSCATTERDDZmr; break;
12341     }
12342     SDValue Chain = Op.getOperand(0);
12343     SDValue Base  = Op.getOperand(2);
12344     SDValue Index = Op.getOperand(3);
12345     SDValue Src   = Op.getOperand(4);
12346     SDValue Scale = Op.getOperand(5);
12347     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12348   }
12349   //int_scatter_mask(base, mask, index, v1, scale);
12350   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12351   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12352   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12353   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12354   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12355   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12356   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12357   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12358     unsigned Opc;
12359     switch (IntNo) {
12360     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12361     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12362       Opc = X86::VSCATTERQPDZmr; break;
12363     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12364       Opc = X86::VSCATTERQPSZmr; break;
12365     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12366       Opc = X86::VSCATTERDPDZmr; break;
12367     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12368       Opc = X86::VSCATTERDPSZmr; break;
12369     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12370       Opc = X86::VPSCATTERQDZmr; break;
12371     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12372       Opc = X86::VPSCATTERQQZmr; break;
12373     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12374       Opc = X86::VPSCATTERDQZmr; break;
12375     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12376       Opc = X86::VPSCATTERDDZmr; break;
12377     }
12378     SDValue Chain = Op.getOperand(0);
12379     SDValue Base  = Op.getOperand(2);
12380     SDValue Mask  = Op.getOperand(3);
12381     SDValue Index = Op.getOperand(4);
12382     SDValue Src   = Op.getOperand(5);
12383     SDValue Scale = Op.getOperand(6);
12384     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12385   }
12386   // XTEST intrinsics.
12387   case Intrinsic::x86_xtest: {
12388     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12389     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12390     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12391                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12392                                 InTrans);
12393     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12394     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12395                        Ret, SDValue(InTrans.getNode(), 1));
12396   }
12397   }
12398 }
12399
12400 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12401                                            SelectionDAG &DAG) const {
12402   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12403   MFI->setReturnAddressIsTaken(true);
12404
12405   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12406     return SDValue();
12407
12408   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12409   SDLoc dl(Op);
12410   EVT PtrVT = getPointerTy();
12411
12412   if (Depth > 0) {
12413     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12414     const X86RegisterInfo *RegInfo =
12415       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12416     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12417     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12418                        DAG.getNode(ISD::ADD, dl, PtrVT,
12419                                    FrameAddr, Offset),
12420                        MachinePointerInfo(), false, false, false, 0);
12421   }
12422
12423   // Just load the return address.
12424   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12425   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12426                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12427 }
12428
12429 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12430   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12431   MFI->setFrameAddressIsTaken(true);
12432
12433   EVT VT = Op.getValueType();
12434   SDLoc dl(Op);  // FIXME probably not meaningful
12435   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12436   const X86RegisterInfo *RegInfo =
12437     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12438   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12439   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12440           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12441          "Invalid Frame Register!");
12442   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12443   while (Depth--)
12444     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12445                             MachinePointerInfo(),
12446                             false, false, false, 0);
12447   return FrameAddr;
12448 }
12449
12450 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12451                                                      SelectionDAG &DAG) const {
12452   const X86RegisterInfo *RegInfo =
12453     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12454   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12455 }
12456
12457 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12458   SDValue Chain     = Op.getOperand(0);
12459   SDValue Offset    = Op.getOperand(1);
12460   SDValue Handler   = Op.getOperand(2);
12461   SDLoc dl      (Op);
12462
12463   EVT PtrVT = getPointerTy();
12464   const X86RegisterInfo *RegInfo =
12465     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12466   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12467   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12468           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12469          "Invalid Frame Register!");
12470   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12471   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12472
12473   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12474                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12475   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12476   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12477                        false, false, 0);
12478   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12479
12480   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12481                      DAG.getRegister(StoreAddrReg, PtrVT));
12482 }
12483
12484 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12485                                                SelectionDAG &DAG) const {
12486   SDLoc DL(Op);
12487   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12488                      DAG.getVTList(MVT::i32, MVT::Other),
12489                      Op.getOperand(0), Op.getOperand(1));
12490 }
12491
12492 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12493                                                 SelectionDAG &DAG) const {
12494   SDLoc DL(Op);
12495   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12496                      Op.getOperand(0), Op.getOperand(1));
12497 }
12498
12499 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12500   return Op.getOperand(0);
12501 }
12502
12503 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12504                                                 SelectionDAG &DAG) const {
12505   SDValue Root = Op.getOperand(0);
12506   SDValue Trmp = Op.getOperand(1); // trampoline
12507   SDValue FPtr = Op.getOperand(2); // nested function
12508   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12509   SDLoc dl (Op);
12510
12511   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12512   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12513
12514   if (Subtarget->is64Bit()) {
12515     SDValue OutChains[6];
12516
12517     // Large code-model.
12518     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12519     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12520
12521     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12522     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12523
12524     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12525
12526     // Load the pointer to the nested function into R11.
12527     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12528     SDValue Addr = Trmp;
12529     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12530                                 Addr, MachinePointerInfo(TrmpAddr),
12531                                 false, false, 0);
12532
12533     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12534                        DAG.getConstant(2, MVT::i64));
12535     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12536                                 MachinePointerInfo(TrmpAddr, 2),
12537                                 false, false, 2);
12538
12539     // Load the 'nest' parameter value into R10.
12540     // R10 is specified in X86CallingConv.td
12541     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12542     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12543                        DAG.getConstant(10, MVT::i64));
12544     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12545                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12546                                 false, false, 0);
12547
12548     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12549                        DAG.getConstant(12, MVT::i64));
12550     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12551                                 MachinePointerInfo(TrmpAddr, 12),
12552                                 false, false, 2);
12553
12554     // Jump to the nested function.
12555     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12556     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12557                        DAG.getConstant(20, MVT::i64));
12558     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12559                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12560                                 false, false, 0);
12561
12562     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12563     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12564                        DAG.getConstant(22, MVT::i64));
12565     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12566                                 MachinePointerInfo(TrmpAddr, 22),
12567                                 false, false, 0);
12568
12569     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12570   } else {
12571     const Function *Func =
12572       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12573     CallingConv::ID CC = Func->getCallingConv();
12574     unsigned NestReg;
12575
12576     switch (CC) {
12577     default:
12578       llvm_unreachable("Unsupported calling convention");
12579     case CallingConv::C:
12580     case CallingConv::X86_StdCall: {
12581       // Pass 'nest' parameter in ECX.
12582       // Must be kept in sync with X86CallingConv.td
12583       NestReg = X86::ECX;
12584
12585       // Check that ECX wasn't needed by an 'inreg' parameter.
12586       FunctionType *FTy = Func->getFunctionType();
12587       const AttributeSet &Attrs = Func->getAttributes();
12588
12589       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12590         unsigned InRegCount = 0;
12591         unsigned Idx = 1;
12592
12593         for (FunctionType::param_iterator I = FTy->param_begin(),
12594              E = FTy->param_end(); I != E; ++I, ++Idx)
12595           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12596             // FIXME: should only count parameters that are lowered to integers.
12597             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12598
12599         if (InRegCount > 2) {
12600           report_fatal_error("Nest register in use - reduce number of inreg"
12601                              " parameters!");
12602         }
12603       }
12604       break;
12605     }
12606     case CallingConv::X86_FastCall:
12607     case CallingConv::X86_ThisCall:
12608     case CallingConv::Fast:
12609       // Pass 'nest' parameter in EAX.
12610       // Must be kept in sync with X86CallingConv.td
12611       NestReg = X86::EAX;
12612       break;
12613     }
12614
12615     SDValue OutChains[4];
12616     SDValue Addr, Disp;
12617
12618     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12619                        DAG.getConstant(10, MVT::i32));
12620     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12621
12622     // This is storing the opcode for MOV32ri.
12623     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12624     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12625     OutChains[0] = DAG.getStore(Root, dl,
12626                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12627                                 Trmp, MachinePointerInfo(TrmpAddr),
12628                                 false, false, 0);
12629
12630     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12631                        DAG.getConstant(1, MVT::i32));
12632     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12633                                 MachinePointerInfo(TrmpAddr, 1),
12634                                 false, false, 1);
12635
12636     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12637     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12638                        DAG.getConstant(5, MVT::i32));
12639     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12640                                 MachinePointerInfo(TrmpAddr, 5),
12641                                 false, false, 1);
12642
12643     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12644                        DAG.getConstant(6, MVT::i32));
12645     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12646                                 MachinePointerInfo(TrmpAddr, 6),
12647                                 false, false, 1);
12648
12649     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12650   }
12651 }
12652
12653 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12654                                             SelectionDAG &DAG) const {
12655   /*
12656    The rounding mode is in bits 11:10 of FPSR, and has the following
12657    settings:
12658      00 Round to nearest
12659      01 Round to -inf
12660      10 Round to +inf
12661      11 Round to 0
12662
12663   FLT_ROUNDS, on the other hand, expects the following:
12664     -1 Undefined
12665      0 Round to 0
12666      1 Round to nearest
12667      2 Round to +inf
12668      3 Round to -inf
12669
12670   To perform the conversion, we do:
12671     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12672   */
12673
12674   MachineFunction &MF = DAG.getMachineFunction();
12675   const TargetMachine &TM = MF.getTarget();
12676   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12677   unsigned StackAlignment = TFI.getStackAlignment();
12678   MVT VT = Op.getSimpleValueType();
12679   SDLoc DL(Op);
12680
12681   // Save FP Control Word to stack slot
12682   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12683   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12684
12685   MachineMemOperand *MMO =
12686    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12687                            MachineMemOperand::MOStore, 2, 2);
12688
12689   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12690   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12691                                           DAG.getVTList(MVT::Other),
12692                                           Ops, array_lengthof(Ops), MVT::i16,
12693                                           MMO);
12694
12695   // Load FP Control Word from stack slot
12696   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12697                             MachinePointerInfo(), false, false, false, 0);
12698
12699   // Transform as necessary
12700   SDValue CWD1 =
12701     DAG.getNode(ISD::SRL, DL, MVT::i16,
12702                 DAG.getNode(ISD::AND, DL, MVT::i16,
12703                             CWD, DAG.getConstant(0x800, MVT::i16)),
12704                 DAG.getConstant(11, MVT::i8));
12705   SDValue CWD2 =
12706     DAG.getNode(ISD::SRL, DL, MVT::i16,
12707                 DAG.getNode(ISD::AND, DL, MVT::i16,
12708                             CWD, DAG.getConstant(0x400, MVT::i16)),
12709                 DAG.getConstant(9, MVT::i8));
12710
12711   SDValue RetVal =
12712     DAG.getNode(ISD::AND, DL, MVT::i16,
12713                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12714                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12715                             DAG.getConstant(1, MVT::i16)),
12716                 DAG.getConstant(3, MVT::i16));
12717
12718   return DAG.getNode((VT.getSizeInBits() < 16 ?
12719                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12720 }
12721
12722 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12723   MVT VT = Op.getSimpleValueType();
12724   EVT OpVT = VT;
12725   unsigned NumBits = VT.getSizeInBits();
12726   SDLoc dl(Op);
12727
12728   Op = Op.getOperand(0);
12729   if (VT == MVT::i8) {
12730     // Zero extend to i32 since there is not an i8 bsr.
12731     OpVT = MVT::i32;
12732     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12733   }
12734
12735   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12736   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12737   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12738
12739   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12740   SDValue Ops[] = {
12741     Op,
12742     DAG.getConstant(NumBits+NumBits-1, OpVT),
12743     DAG.getConstant(X86::COND_E, MVT::i8),
12744     Op.getValue(1)
12745   };
12746   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12747
12748   // Finally xor with NumBits-1.
12749   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12750
12751   if (VT == MVT::i8)
12752     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12753   return Op;
12754 }
12755
12756 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12757   MVT VT = Op.getSimpleValueType();
12758   EVT OpVT = VT;
12759   unsigned NumBits = VT.getSizeInBits();
12760   SDLoc dl(Op);
12761
12762   Op = Op.getOperand(0);
12763   if (VT == MVT::i8) {
12764     // Zero extend to i32 since there is not an i8 bsr.
12765     OpVT = MVT::i32;
12766     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12767   }
12768
12769   // Issue a bsr (scan bits in reverse).
12770   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12771   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12772
12773   // And xor with NumBits-1.
12774   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12775
12776   if (VT == MVT::i8)
12777     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12778   return Op;
12779 }
12780
12781 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12782   MVT VT = Op.getSimpleValueType();
12783   unsigned NumBits = VT.getSizeInBits();
12784   SDLoc dl(Op);
12785   Op = Op.getOperand(0);
12786
12787   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12788   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12789   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12790
12791   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12792   SDValue Ops[] = {
12793     Op,
12794     DAG.getConstant(NumBits, VT),
12795     DAG.getConstant(X86::COND_E, MVT::i8),
12796     Op.getValue(1)
12797   };
12798   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12799 }
12800
12801 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12802 // ones, and then concatenate the result back.
12803 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12804   MVT VT = Op.getSimpleValueType();
12805
12806   assert(VT.is256BitVector() && VT.isInteger() &&
12807          "Unsupported value type for operation");
12808
12809   unsigned NumElems = VT.getVectorNumElements();
12810   SDLoc dl(Op);
12811
12812   // Extract the LHS vectors
12813   SDValue LHS = Op.getOperand(0);
12814   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12815   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12816
12817   // Extract the RHS vectors
12818   SDValue RHS = Op.getOperand(1);
12819   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12820   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12821
12822   MVT EltVT = VT.getVectorElementType();
12823   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12824
12825   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12826                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12827                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12828 }
12829
12830 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12831   assert(Op.getSimpleValueType().is256BitVector() &&
12832          Op.getSimpleValueType().isInteger() &&
12833          "Only handle AVX 256-bit vector integer operation");
12834   return Lower256IntArith(Op, DAG);
12835 }
12836
12837 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12838   assert(Op.getSimpleValueType().is256BitVector() &&
12839          Op.getSimpleValueType().isInteger() &&
12840          "Only handle AVX 256-bit vector integer operation");
12841   return Lower256IntArith(Op, DAG);
12842 }
12843
12844 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12845                         SelectionDAG &DAG) {
12846   SDLoc dl(Op);
12847   MVT VT = Op.getSimpleValueType();
12848
12849   // Decompose 256-bit ops into smaller 128-bit ops.
12850   if (VT.is256BitVector() && !Subtarget->hasInt256())
12851     return Lower256IntArith(Op, DAG);
12852
12853   SDValue A = Op.getOperand(0);
12854   SDValue B = Op.getOperand(1);
12855
12856   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12857   if (VT == MVT::v4i32) {
12858     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12859            "Should not custom lower when pmuldq is available!");
12860
12861     // Extract the odd parts.
12862     static const int UnpackMask[] = { 1, -1, 3, -1 };
12863     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12864     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12865
12866     // Multiply the even parts.
12867     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12868     // Now multiply odd parts.
12869     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12870
12871     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12872     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12873
12874     // Merge the two vectors back together with a shuffle. This expands into 2
12875     // shuffles.
12876     static const int ShufMask[] = { 0, 4, 2, 6 };
12877     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12878   }
12879
12880   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12881          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12882
12883   //  Ahi = psrlqi(a, 32);
12884   //  Bhi = psrlqi(b, 32);
12885   //
12886   //  AloBlo = pmuludq(a, b);
12887   //  AloBhi = pmuludq(a, Bhi);
12888   //  AhiBlo = pmuludq(Ahi, b);
12889
12890   //  AloBhi = psllqi(AloBhi, 32);
12891   //  AhiBlo = psllqi(AhiBlo, 32);
12892   //  return AloBlo + AloBhi + AhiBlo;
12893
12894   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12895   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12896
12897   // Bit cast to 32-bit vectors for MULUDQ
12898   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12899                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12900   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12901   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12902   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12903   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12904
12905   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12906   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12907   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12908
12909   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12910   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12911
12912   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12913   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12914 }
12915
12916 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12917   MVT VT = Op.getSimpleValueType();
12918   MVT EltTy = VT.getVectorElementType();
12919   unsigned NumElts = VT.getVectorNumElements();
12920   SDValue N0 = Op.getOperand(0);
12921   SDLoc dl(Op);
12922
12923   // Lower sdiv X, pow2-const.
12924   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12925   if (!C)
12926     return SDValue();
12927
12928   APInt SplatValue, SplatUndef;
12929   unsigned SplatBitSize;
12930   bool HasAnyUndefs;
12931   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12932                           HasAnyUndefs) ||
12933       EltTy.getSizeInBits() < SplatBitSize)
12934     return SDValue();
12935
12936   if ((SplatValue != 0) &&
12937       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12938     unsigned Lg2 = SplatValue.countTrailingZeros();
12939     // Splat the sign bit.
12940     SmallVector<SDValue, 16> Sz(NumElts,
12941                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12942                                                 EltTy));
12943     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12944                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12945                                           NumElts));
12946     // Add (N0 < 0) ? abs2 - 1 : 0;
12947     SmallVector<SDValue, 16> Amt(NumElts,
12948                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12949                                                  EltTy));
12950     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12951                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12952                                           NumElts));
12953     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12954     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12955     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12956                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12957                                           NumElts));
12958
12959     // If we're dividing by a positive value, we're done.  Otherwise, we must
12960     // negate the result.
12961     if (SplatValue.isNonNegative())
12962       return SRA;
12963
12964     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12965     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12966     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12967   }
12968   return SDValue();
12969 }
12970
12971 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12972                                          const X86Subtarget *Subtarget) {
12973   MVT VT = Op.getSimpleValueType();
12974   SDLoc dl(Op);
12975   SDValue R = Op.getOperand(0);
12976   SDValue Amt = Op.getOperand(1);
12977
12978   // Optimize shl/srl/sra with constant shift amount.
12979   if (isSplatVector(Amt.getNode())) {
12980     SDValue SclrAmt = Amt->getOperand(0);
12981     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12982       uint64_t ShiftAmt = C->getZExtValue();
12983
12984       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12985           (Subtarget->hasInt256() &&
12986            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12987           (Subtarget->hasAVX512() &&
12988            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12989         if (Op.getOpcode() == ISD::SHL)
12990           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12991                                             DAG);
12992         if (Op.getOpcode() == ISD::SRL)
12993           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12994                                             DAG);
12995         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12996           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12997                                             DAG);
12998       }
12999
13000       if (VT == MVT::v16i8) {
13001         if (Op.getOpcode() == ISD::SHL) {
13002           // Make a large shift.
13003           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13004                                                    MVT::v8i16, R, ShiftAmt,
13005                                                    DAG);
13006           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13007           // Zero out the rightmost bits.
13008           SmallVector<SDValue, 16> V(16,
13009                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13010                                                      MVT::i8));
13011           return DAG.getNode(ISD::AND, dl, VT, SHL,
13012                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13013         }
13014         if (Op.getOpcode() == ISD::SRL) {
13015           // Make a large shift.
13016           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13017                                                    MVT::v8i16, R, ShiftAmt,
13018                                                    DAG);
13019           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13020           // Zero out the leftmost bits.
13021           SmallVector<SDValue, 16> V(16,
13022                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13023                                                      MVT::i8));
13024           return DAG.getNode(ISD::AND, dl, VT, SRL,
13025                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13026         }
13027         if (Op.getOpcode() == ISD::SRA) {
13028           if (ShiftAmt == 7) {
13029             // R s>> 7  ===  R s< 0
13030             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13031             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13032           }
13033
13034           // R s>> a === ((R u>> a) ^ m) - m
13035           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13036           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13037                                                          MVT::i8));
13038           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13039           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13040           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13041           return Res;
13042         }
13043         llvm_unreachable("Unknown shift opcode.");
13044       }
13045
13046       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13047         if (Op.getOpcode() == ISD::SHL) {
13048           // Make a large shift.
13049           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13050                                                    MVT::v16i16, R, ShiftAmt,
13051                                                    DAG);
13052           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13053           // Zero out the rightmost bits.
13054           SmallVector<SDValue, 32> V(32,
13055                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13056                                                      MVT::i8));
13057           return DAG.getNode(ISD::AND, dl, VT, SHL,
13058                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13059         }
13060         if (Op.getOpcode() == ISD::SRL) {
13061           // Make a large shift.
13062           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13063                                                    MVT::v16i16, R, ShiftAmt,
13064                                                    DAG);
13065           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13066           // Zero out the leftmost bits.
13067           SmallVector<SDValue, 32> V(32,
13068                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13069                                                      MVT::i8));
13070           return DAG.getNode(ISD::AND, dl, VT, SRL,
13071                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13072         }
13073         if (Op.getOpcode() == ISD::SRA) {
13074           if (ShiftAmt == 7) {
13075             // R s>> 7  ===  R s< 0
13076             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13077             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13078           }
13079
13080           // R s>> a === ((R u>> a) ^ m) - m
13081           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13082           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13083                                                          MVT::i8));
13084           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13085           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13086           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13087           return Res;
13088         }
13089         llvm_unreachable("Unknown shift opcode.");
13090       }
13091     }
13092   }
13093
13094   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13095   if (!Subtarget->is64Bit() &&
13096       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13097       Amt.getOpcode() == ISD::BITCAST &&
13098       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13099     Amt = Amt.getOperand(0);
13100     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13101                      VT.getVectorNumElements();
13102     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13103     uint64_t ShiftAmt = 0;
13104     for (unsigned i = 0; i != Ratio; ++i) {
13105       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13106       if (C == 0)
13107         return SDValue();
13108       // 6 == Log2(64)
13109       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13110     }
13111     // Check remaining shift amounts.
13112     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13113       uint64_t ShAmt = 0;
13114       for (unsigned j = 0; j != Ratio; ++j) {
13115         ConstantSDNode *C =
13116           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13117         if (C == 0)
13118           return SDValue();
13119         // 6 == Log2(64)
13120         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13121       }
13122       if (ShAmt != ShiftAmt)
13123         return SDValue();
13124     }
13125     switch (Op.getOpcode()) {
13126     default:
13127       llvm_unreachable("Unknown shift opcode!");
13128     case ISD::SHL:
13129       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13130                                         DAG);
13131     case ISD::SRL:
13132       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13133                                         DAG);
13134     case ISD::SRA:
13135       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13136                                         DAG);
13137     }
13138   }
13139
13140   return SDValue();
13141 }
13142
13143 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13144                                         const X86Subtarget* Subtarget) {
13145   MVT VT = Op.getSimpleValueType();
13146   SDLoc dl(Op);
13147   SDValue R = Op.getOperand(0);
13148   SDValue Amt = Op.getOperand(1);
13149
13150   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13151       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13152       (Subtarget->hasInt256() &&
13153        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13154         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13155        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13156     SDValue BaseShAmt;
13157     EVT EltVT = VT.getVectorElementType();
13158
13159     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13160       unsigned NumElts = VT.getVectorNumElements();
13161       unsigned i, j;
13162       for (i = 0; i != NumElts; ++i) {
13163         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13164           continue;
13165         break;
13166       }
13167       for (j = i; j != NumElts; ++j) {
13168         SDValue Arg = Amt.getOperand(j);
13169         if (Arg.getOpcode() == ISD::UNDEF) continue;
13170         if (Arg != Amt.getOperand(i))
13171           break;
13172       }
13173       if (i != NumElts && j == NumElts)
13174         BaseShAmt = Amt.getOperand(i);
13175     } else {
13176       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13177         Amt = Amt.getOperand(0);
13178       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13179                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13180         SDValue InVec = Amt.getOperand(0);
13181         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13182           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13183           unsigned i = 0;
13184           for (; i != NumElts; ++i) {
13185             SDValue Arg = InVec.getOperand(i);
13186             if (Arg.getOpcode() == ISD::UNDEF) continue;
13187             BaseShAmt = Arg;
13188             break;
13189           }
13190         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13191            if (ConstantSDNode *C =
13192                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13193              unsigned SplatIdx =
13194                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13195              if (C->getZExtValue() == SplatIdx)
13196                BaseShAmt = InVec.getOperand(1);
13197            }
13198         }
13199         if (BaseShAmt.getNode() == 0)
13200           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13201                                   DAG.getIntPtrConstant(0));
13202       }
13203     }
13204
13205     if (BaseShAmt.getNode()) {
13206       if (EltVT.bitsGT(MVT::i32))
13207         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13208       else if (EltVT.bitsLT(MVT::i32))
13209         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13210
13211       switch (Op.getOpcode()) {
13212       default:
13213         llvm_unreachable("Unknown shift opcode!");
13214       case ISD::SHL:
13215         switch (VT.SimpleTy) {
13216         default: return SDValue();
13217         case MVT::v2i64:
13218         case MVT::v4i32:
13219         case MVT::v8i16:
13220         case MVT::v4i64:
13221         case MVT::v8i32:
13222         case MVT::v16i16:
13223         case MVT::v16i32:
13224         case MVT::v8i64:
13225           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13226         }
13227       case ISD::SRA:
13228         switch (VT.SimpleTy) {
13229         default: return SDValue();
13230         case MVT::v4i32:
13231         case MVT::v8i16:
13232         case MVT::v8i32:
13233         case MVT::v16i16:
13234         case MVT::v16i32:
13235         case MVT::v8i64:
13236           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13237         }
13238       case ISD::SRL:
13239         switch (VT.SimpleTy) {
13240         default: return SDValue();
13241         case MVT::v2i64:
13242         case MVT::v4i32:
13243         case MVT::v8i16:
13244         case MVT::v4i64:
13245         case MVT::v8i32:
13246         case MVT::v16i16:
13247         case MVT::v16i32:
13248         case MVT::v8i64:
13249           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13250         }
13251       }
13252     }
13253   }
13254
13255   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13256   if (!Subtarget->is64Bit() &&
13257       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13258       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13259       Amt.getOpcode() == ISD::BITCAST &&
13260       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13261     Amt = Amt.getOperand(0);
13262     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13263                      VT.getVectorNumElements();
13264     std::vector<SDValue> Vals(Ratio);
13265     for (unsigned i = 0; i != Ratio; ++i)
13266       Vals[i] = Amt.getOperand(i);
13267     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13268       for (unsigned j = 0; j != Ratio; ++j)
13269         if (Vals[j] != Amt.getOperand(i + j))
13270           return SDValue();
13271     }
13272     switch (Op.getOpcode()) {
13273     default:
13274       llvm_unreachable("Unknown shift opcode!");
13275     case ISD::SHL:
13276       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13277     case ISD::SRL:
13278       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13279     case ISD::SRA:
13280       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13281     }
13282   }
13283
13284   return SDValue();
13285 }
13286
13287 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13288                           SelectionDAG &DAG) {
13289
13290   MVT VT = Op.getSimpleValueType();
13291   SDLoc dl(Op);
13292   SDValue R = Op.getOperand(0);
13293   SDValue Amt = Op.getOperand(1);
13294   SDValue V;
13295
13296   if (!Subtarget->hasSSE2())
13297     return SDValue();
13298
13299   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13300   if (V.getNode())
13301     return V;
13302
13303   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13304   if (V.getNode())
13305       return V;
13306
13307   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13308     return Op;
13309   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13310   if (Subtarget->hasInt256()) {
13311     if (Op.getOpcode() == ISD::SRL &&
13312         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13313          VT == MVT::v4i64 || VT == MVT::v8i32))
13314       return Op;
13315     if (Op.getOpcode() == ISD::SHL &&
13316         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13317          VT == MVT::v4i64 || VT == MVT::v8i32))
13318       return Op;
13319     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13320       return Op;
13321   }
13322
13323   // If possible, lower this packed shift into a vector multiply instead of
13324   // expanding it into a sequence of scalar shifts.
13325   // Do this only if the vector shift count is a constant build_vector.
13326   if (Op.getOpcode() == ISD::SHL && 
13327       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13328        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13329       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13330     SmallVector<SDValue, 8> Elts;
13331     EVT SVT = VT.getScalarType();
13332     unsigned SVTBits = SVT.getSizeInBits();
13333     const APInt &One = APInt(SVTBits, 1);
13334     unsigned NumElems = VT.getVectorNumElements();
13335
13336     for (unsigned i=0; i !=NumElems; ++i) {
13337       SDValue Op = Amt->getOperand(i);
13338       if (Op->getOpcode() == ISD::UNDEF) {
13339         Elts.push_back(Op);
13340         continue;
13341       }
13342
13343       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13344       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13345       uint64_t ShAmt = C.getZExtValue();
13346       if (ShAmt >= SVTBits) {
13347         Elts.push_back(DAG.getUNDEF(SVT));
13348         continue;
13349       }
13350       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13351     }
13352     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13353     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13354   }
13355
13356   // Lower SHL with variable shift amount.
13357   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13358     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13359
13360     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13361     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13362     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13363     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13364   }
13365
13366   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13367     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13368
13369     // a = a << 5;
13370     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13371     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13372
13373     // Turn 'a' into a mask suitable for VSELECT
13374     SDValue VSelM = DAG.getConstant(0x80, VT);
13375     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13376     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13377
13378     SDValue CM1 = DAG.getConstant(0x0f, VT);
13379     SDValue CM2 = DAG.getConstant(0x3f, VT);
13380
13381     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13382     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13383     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13384     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13385     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13386
13387     // a += a
13388     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13389     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13390     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13391
13392     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13393     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13394     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13395     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13396     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13397
13398     // a += a
13399     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13400     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13401     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13402
13403     // return VSELECT(r, r+r, a);
13404     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13405                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13406     return R;
13407   }
13408
13409   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13410   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13411   // solution better.
13412   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13413     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13414     unsigned ExtOpc =
13415         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13416     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13417     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13418     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13419                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13420     }
13421
13422   // Decompose 256-bit shifts into smaller 128-bit shifts.
13423   if (VT.is256BitVector()) {
13424     unsigned NumElems = VT.getVectorNumElements();
13425     MVT EltVT = VT.getVectorElementType();
13426     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13427
13428     // Extract the two vectors
13429     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13430     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13431
13432     // Recreate the shift amount vectors
13433     SDValue Amt1, Amt2;
13434     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13435       // Constant shift amount
13436       SmallVector<SDValue, 4> Amt1Csts;
13437       SmallVector<SDValue, 4> Amt2Csts;
13438       for (unsigned i = 0; i != NumElems/2; ++i)
13439         Amt1Csts.push_back(Amt->getOperand(i));
13440       for (unsigned i = NumElems/2; i != NumElems; ++i)
13441         Amt2Csts.push_back(Amt->getOperand(i));
13442
13443       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13444                                  &Amt1Csts[0], NumElems/2);
13445       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13446                                  &Amt2Csts[0], NumElems/2);
13447     } else {
13448       // Variable shift amount
13449       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13450       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13451     }
13452
13453     // Issue new vector shifts for the smaller types
13454     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13455     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13456
13457     // Concatenate the result back
13458     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13459   }
13460
13461   return SDValue();
13462 }
13463
13464 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13465   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13466   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13467   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13468   // has only one use.
13469   SDNode *N = Op.getNode();
13470   SDValue LHS = N->getOperand(0);
13471   SDValue RHS = N->getOperand(1);
13472   unsigned BaseOp = 0;
13473   unsigned Cond = 0;
13474   SDLoc DL(Op);
13475   switch (Op.getOpcode()) {
13476   default: llvm_unreachable("Unknown ovf instruction!");
13477   case ISD::SADDO:
13478     // A subtract of one will be selected as a INC. Note that INC doesn't
13479     // set CF, so we can't do this for UADDO.
13480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13481       if (C->isOne()) {
13482         BaseOp = X86ISD::INC;
13483         Cond = X86::COND_O;
13484         break;
13485       }
13486     BaseOp = X86ISD::ADD;
13487     Cond = X86::COND_O;
13488     break;
13489   case ISD::UADDO:
13490     BaseOp = X86ISD::ADD;
13491     Cond = X86::COND_B;
13492     break;
13493   case ISD::SSUBO:
13494     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13495     // set CF, so we can't do this for USUBO.
13496     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13497       if (C->isOne()) {
13498         BaseOp = X86ISD::DEC;
13499         Cond = X86::COND_O;
13500         break;
13501       }
13502     BaseOp = X86ISD::SUB;
13503     Cond = X86::COND_O;
13504     break;
13505   case ISD::USUBO:
13506     BaseOp = X86ISD::SUB;
13507     Cond = X86::COND_B;
13508     break;
13509   case ISD::SMULO:
13510     BaseOp = X86ISD::SMUL;
13511     Cond = X86::COND_O;
13512     break;
13513   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13514     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13515                                  MVT::i32);
13516     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13517
13518     SDValue SetCC =
13519       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13520                   DAG.getConstant(X86::COND_O, MVT::i32),
13521                   SDValue(Sum.getNode(), 2));
13522
13523     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13524   }
13525   }
13526
13527   // Also sets EFLAGS.
13528   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13529   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13530
13531   SDValue SetCC =
13532     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13533                 DAG.getConstant(Cond, MVT::i32),
13534                 SDValue(Sum.getNode(), 1));
13535
13536   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13537 }
13538
13539 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13540                                                   SelectionDAG &DAG) const {
13541   SDLoc dl(Op);
13542   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13543   MVT VT = Op.getSimpleValueType();
13544
13545   if (!Subtarget->hasSSE2() || !VT.isVector())
13546     return SDValue();
13547
13548   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13549                       ExtraVT.getScalarType().getSizeInBits();
13550
13551   switch (VT.SimpleTy) {
13552     default: return SDValue();
13553     case MVT::v8i32:
13554     case MVT::v16i16:
13555       if (!Subtarget->hasFp256())
13556         return SDValue();
13557       if (!Subtarget->hasInt256()) {
13558         // needs to be split
13559         unsigned NumElems = VT.getVectorNumElements();
13560
13561         // Extract the LHS vectors
13562         SDValue LHS = Op.getOperand(0);
13563         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13564         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13565
13566         MVT EltVT = VT.getVectorElementType();
13567         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13568
13569         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13570         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13571         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13572                                    ExtraNumElems/2);
13573         SDValue Extra = DAG.getValueType(ExtraVT);
13574
13575         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13576         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13577
13578         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13579       }
13580       // fall through
13581     case MVT::v4i32:
13582     case MVT::v8i16: {
13583       SDValue Op0 = Op.getOperand(0);
13584       SDValue Op00 = Op0.getOperand(0);
13585       SDValue Tmp1;
13586       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13587       if (Op0.getOpcode() == ISD::BITCAST &&
13588           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13589         // (sext (vzext x)) -> (vsext x)
13590         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13591         if (Tmp1.getNode()) {
13592           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13593           // This folding is only valid when the in-reg type is a vector of i8,
13594           // i16, or i32.
13595           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13596               ExtraEltVT == MVT::i32) {
13597             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13598             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13599                    "This optimization is invalid without a VZEXT.");
13600             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13601           }
13602           Op0 = Tmp1;
13603         }
13604       }
13605
13606       // If the above didn't work, then just use Shift-Left + Shift-Right.
13607       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13608                                         DAG);
13609       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13610                                         DAG);
13611     }
13612   }
13613 }
13614
13615 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13616                                  SelectionDAG &DAG) {
13617   SDLoc dl(Op);
13618   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13619     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13620   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13621     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13622
13623   // The only fence that needs an instruction is a sequentially-consistent
13624   // cross-thread fence.
13625   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13626     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13627     // no-sse2). There isn't any reason to disable it if the target processor
13628     // supports it.
13629     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13630       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13631
13632     SDValue Chain = Op.getOperand(0);
13633     SDValue Zero = DAG.getConstant(0, MVT::i32);
13634     SDValue Ops[] = {
13635       DAG.getRegister(X86::ESP, MVT::i32), // Base
13636       DAG.getTargetConstant(1, MVT::i8),   // Scale
13637       DAG.getRegister(0, MVT::i32),        // Index
13638       DAG.getTargetConstant(0, MVT::i32),  // Disp
13639       DAG.getRegister(0, MVT::i32),        // Segment.
13640       Zero,
13641       Chain
13642     };
13643     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13644     return SDValue(Res, 0);
13645   }
13646
13647   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13648   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13649 }
13650
13651 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13652                              SelectionDAG &DAG) {
13653   MVT T = Op.getSimpleValueType();
13654   SDLoc DL(Op);
13655   unsigned Reg = 0;
13656   unsigned size = 0;
13657   switch(T.SimpleTy) {
13658   default: llvm_unreachable("Invalid value type!");
13659   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13660   case MVT::i16: Reg = X86::AX;  size = 2; break;
13661   case MVT::i32: Reg = X86::EAX; size = 4; break;
13662   case MVT::i64:
13663     assert(Subtarget->is64Bit() && "Node not type legal!");
13664     Reg = X86::RAX; size = 8;
13665     break;
13666   }
13667   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13668                                     Op.getOperand(2), SDValue());
13669   SDValue Ops[] = { cpIn.getValue(0),
13670                     Op.getOperand(1),
13671                     Op.getOperand(3),
13672                     DAG.getTargetConstant(size, MVT::i8),
13673                     cpIn.getValue(1) };
13674   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13675   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13676   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13677                                            Ops, array_lengthof(Ops), T, MMO);
13678   SDValue cpOut =
13679     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13680   return cpOut;
13681 }
13682
13683 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13684                                      SelectionDAG &DAG) {
13685   assert(Subtarget->is64Bit() && "Result not type legalized?");
13686   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13687   SDValue TheChain = Op.getOperand(0);
13688   SDLoc dl(Op);
13689   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13690   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13691   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13692                                    rax.getValue(2));
13693   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13694                             DAG.getConstant(32, MVT::i8));
13695   SDValue Ops[] = {
13696     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13697     rdx.getValue(1)
13698   };
13699   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13700 }
13701
13702 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13703                             SelectionDAG &DAG) {
13704   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13705   MVT DstVT = Op.getSimpleValueType();
13706   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13707          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13708   assert((DstVT == MVT::i64 ||
13709           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13710          "Unexpected custom BITCAST");
13711   // i64 <=> MMX conversions are Legal.
13712   if (SrcVT==MVT::i64 && DstVT.isVector())
13713     return Op;
13714   if (DstVT==MVT::i64 && SrcVT.isVector())
13715     return Op;
13716   // MMX <=> MMX conversions are Legal.
13717   if (SrcVT.isVector() && DstVT.isVector())
13718     return Op;
13719   // All other conversions need to be expanded.
13720   return SDValue();
13721 }
13722
13723 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13724   SDNode *Node = Op.getNode();
13725   SDLoc dl(Node);
13726   EVT T = Node->getValueType(0);
13727   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13728                               DAG.getConstant(0, T), Node->getOperand(2));
13729   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13730                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13731                        Node->getOperand(0),
13732                        Node->getOperand(1), negOp,
13733                        cast<AtomicSDNode>(Node)->getSrcValue(),
13734                        cast<AtomicSDNode>(Node)->getAlignment(),
13735                        cast<AtomicSDNode>(Node)->getOrdering(),
13736                        cast<AtomicSDNode>(Node)->getSynchScope());
13737 }
13738
13739 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13740   SDNode *Node = Op.getNode();
13741   SDLoc dl(Node);
13742   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13743
13744   // Convert seq_cst store -> xchg
13745   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13746   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13747   //        (The only way to get a 16-byte store is cmpxchg16b)
13748   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13749   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13750       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13751     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13752                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13753                                  Node->getOperand(0),
13754                                  Node->getOperand(1), Node->getOperand(2),
13755                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13756                                  cast<AtomicSDNode>(Node)->getOrdering(),
13757                                  cast<AtomicSDNode>(Node)->getSynchScope());
13758     return Swap.getValue(1);
13759   }
13760   // Other atomic stores have a simple pattern.
13761   return Op;
13762 }
13763
13764 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13765   EVT VT = Op.getNode()->getSimpleValueType(0);
13766
13767   // Let legalize expand this if it isn't a legal type yet.
13768   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13769     return SDValue();
13770
13771   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13772
13773   unsigned Opc;
13774   bool ExtraOp = false;
13775   switch (Op.getOpcode()) {
13776   default: llvm_unreachable("Invalid code");
13777   case ISD::ADDC: Opc = X86ISD::ADD; break;
13778   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13779   case ISD::SUBC: Opc = X86ISD::SUB; break;
13780   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13781   }
13782
13783   if (!ExtraOp)
13784     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13785                        Op.getOperand(1));
13786   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13787                      Op.getOperand(1), Op.getOperand(2));
13788 }
13789
13790 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13791                             SelectionDAG &DAG) {
13792   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13793
13794   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13795   // which returns the values as { float, float } (in XMM0) or
13796   // { double, double } (which is returned in XMM0, XMM1).
13797   SDLoc dl(Op);
13798   SDValue Arg = Op.getOperand(0);
13799   EVT ArgVT = Arg.getValueType();
13800   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13801
13802   TargetLowering::ArgListTy Args;
13803   TargetLowering::ArgListEntry Entry;
13804
13805   Entry.Node = Arg;
13806   Entry.Ty = ArgTy;
13807   Entry.isSExt = false;
13808   Entry.isZExt = false;
13809   Args.push_back(Entry);
13810
13811   bool isF64 = ArgVT == MVT::f64;
13812   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13813   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13814   // the results are returned via SRet in memory.
13815   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13816   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13817   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13818
13819   Type *RetTy = isF64
13820     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13821     : (Type*)VectorType::get(ArgTy, 4);
13822   TargetLowering::
13823     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13824                          false, false, false, false, 0,
13825                          CallingConv::C, /*isTaillCall=*/false,
13826                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13827                          Callee, Args, DAG, dl);
13828   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13829
13830   if (isF64)
13831     // Returned in xmm0 and xmm1.
13832     return CallResult.first;
13833
13834   // Returned in bits 0:31 and 32:64 xmm0.
13835   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13836                                CallResult.first, DAG.getIntPtrConstant(0));
13837   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13838                                CallResult.first, DAG.getIntPtrConstant(1));
13839   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13840   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13841 }
13842
13843 /// LowerOperation - Provide custom lowering hooks for some operations.
13844 ///
13845 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13846   switch (Op.getOpcode()) {
13847   default: llvm_unreachable("Should not custom lower this!");
13848   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13849   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13850   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13851   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13852   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13853   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13854   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13855   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13856   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13857   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13858   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13859   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13860   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13861   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13862   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13863   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13864   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13865   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13866   case ISD::SHL_PARTS:
13867   case ISD::SRA_PARTS:
13868   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13869   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13870   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13871   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13872   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13873   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13874   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13875   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13876   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13877   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13878   case ISD::FABS:               return LowerFABS(Op, DAG);
13879   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13880   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13881   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13882   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13883   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13884   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13885   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13886   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13887   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13888   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13889   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13890   case ISD::INTRINSIC_VOID:
13891   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13892   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13893   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13894   case ISD::FRAME_TO_ARGS_OFFSET:
13895                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13896   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13897   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13898   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13899   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13900   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13901   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13902   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13903   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13904   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13905   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13906   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13907   case ISD::SRA:
13908   case ISD::SRL:
13909   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13910   case ISD::SADDO:
13911   case ISD::UADDO:
13912   case ISD::SSUBO:
13913   case ISD::USUBO:
13914   case ISD::SMULO:
13915   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13916   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13917   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13918   case ISD::ADDC:
13919   case ISD::ADDE:
13920   case ISD::SUBC:
13921   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13922   case ISD::ADD:                return LowerADD(Op, DAG);
13923   case ISD::SUB:                return LowerSUB(Op, DAG);
13924   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13925   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13926   }
13927 }
13928
13929 static void ReplaceATOMIC_LOAD(SDNode *Node,
13930                                   SmallVectorImpl<SDValue> &Results,
13931                                   SelectionDAG &DAG) {
13932   SDLoc dl(Node);
13933   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13934
13935   // Convert wide load -> cmpxchg8b/cmpxchg16b
13936   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13937   //        (The only way to get a 16-byte load is cmpxchg16b)
13938   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13939   SDValue Zero = DAG.getConstant(0, VT);
13940   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13941                                Node->getOperand(0),
13942                                Node->getOperand(1), Zero, Zero,
13943                                cast<AtomicSDNode>(Node)->getMemOperand(),
13944                                cast<AtomicSDNode>(Node)->getOrdering(),
13945                                cast<AtomicSDNode>(Node)->getOrdering(),
13946                                cast<AtomicSDNode>(Node)->getSynchScope());
13947   Results.push_back(Swap.getValue(0));
13948   Results.push_back(Swap.getValue(1));
13949 }
13950
13951 static void
13952 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13953                         SelectionDAG &DAG, unsigned NewOp) {
13954   SDLoc dl(Node);
13955   assert (Node->getValueType(0) == MVT::i64 &&
13956           "Only know how to expand i64 atomics");
13957
13958   SDValue Chain = Node->getOperand(0);
13959   SDValue In1 = Node->getOperand(1);
13960   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13961                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13962   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13963                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13964   SDValue Ops[] = { Chain, In1, In2L, In2H };
13965   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13966   SDValue Result =
13967     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13968                             cast<MemSDNode>(Node)->getMemOperand());
13969   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13970   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13971   Results.push_back(Result.getValue(2));
13972 }
13973
13974 /// ReplaceNodeResults - Replace a node with an illegal result type
13975 /// with a new node built out of custom code.
13976 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13977                                            SmallVectorImpl<SDValue>&Results,
13978                                            SelectionDAG &DAG) const {
13979   SDLoc dl(N);
13980   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13981   switch (N->getOpcode()) {
13982   default:
13983     llvm_unreachable("Do not know how to custom type legalize this operation!");
13984   case ISD::SIGN_EXTEND_INREG:
13985   case ISD::ADDC:
13986   case ISD::ADDE:
13987   case ISD::SUBC:
13988   case ISD::SUBE:
13989     // We don't want to expand or promote these.
13990     return;
13991   case ISD::FP_TO_SINT:
13992   case ISD::FP_TO_UINT: {
13993     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13994
13995     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13996       return;
13997
13998     std::pair<SDValue,SDValue> Vals =
13999         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14000     SDValue FIST = Vals.first, StackSlot = Vals.second;
14001     if (FIST.getNode() != 0) {
14002       EVT VT = N->getValueType(0);
14003       // Return a load from the stack slot.
14004       if (StackSlot.getNode() != 0)
14005         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14006                                       MachinePointerInfo(),
14007                                       false, false, false, 0));
14008       else
14009         Results.push_back(FIST);
14010     }
14011     return;
14012   }
14013   case ISD::UINT_TO_FP: {
14014     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14015     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14016         N->getValueType(0) != MVT::v2f32)
14017       return;
14018     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14019                                  N->getOperand(0));
14020     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14021                                      MVT::f64);
14022     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14023     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14024                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14025     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14026     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14027     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14028     return;
14029   }
14030   case ISD::FP_ROUND: {
14031     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14032         return;
14033     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14034     Results.push_back(V);
14035     return;
14036   }
14037   case ISD::READCYCLECOUNTER: {
14038     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14039     SDValue TheChain = N->getOperand(0);
14040     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
14041     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
14042                                      rd.getValue(1));
14043     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
14044                                      eax.getValue(2));
14045     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14046     SDValue Ops[] = { eax, edx };
14047     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
14048                                   array_lengthof(Ops)));
14049     Results.push_back(edx.getValue(1));
14050     return;
14051   }
14052   case ISD::ATOMIC_CMP_SWAP: {
14053     EVT T = N->getValueType(0);
14054     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14055     bool Regs64bit = T == MVT::i128;
14056     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14057     SDValue cpInL, cpInH;
14058     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14059                         DAG.getConstant(0, HalfT));
14060     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14061                         DAG.getConstant(1, HalfT));
14062     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14063                              Regs64bit ? X86::RAX : X86::EAX,
14064                              cpInL, SDValue());
14065     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14066                              Regs64bit ? X86::RDX : X86::EDX,
14067                              cpInH, cpInL.getValue(1));
14068     SDValue swapInL, swapInH;
14069     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14070                           DAG.getConstant(0, HalfT));
14071     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14072                           DAG.getConstant(1, HalfT));
14073     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14074                                Regs64bit ? X86::RBX : X86::EBX,
14075                                swapInL, cpInH.getValue(1));
14076     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14077                                Regs64bit ? X86::RCX : X86::ECX,
14078                                swapInH, swapInL.getValue(1));
14079     SDValue Ops[] = { swapInH.getValue(0),
14080                       N->getOperand(1),
14081                       swapInH.getValue(1) };
14082     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14083     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14084     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14085                                   X86ISD::LCMPXCHG8_DAG;
14086     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14087                                              Ops, array_lengthof(Ops), T, MMO);
14088     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14089                                         Regs64bit ? X86::RAX : X86::EAX,
14090                                         HalfT, Result.getValue(1));
14091     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14092                                         Regs64bit ? X86::RDX : X86::EDX,
14093                                         HalfT, cpOutL.getValue(2));
14094     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14095     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14096     Results.push_back(cpOutH.getValue(1));
14097     return;
14098   }
14099   case ISD::ATOMIC_LOAD_ADD:
14100   case ISD::ATOMIC_LOAD_AND:
14101   case ISD::ATOMIC_LOAD_NAND:
14102   case ISD::ATOMIC_LOAD_OR:
14103   case ISD::ATOMIC_LOAD_SUB:
14104   case ISD::ATOMIC_LOAD_XOR:
14105   case ISD::ATOMIC_LOAD_MAX:
14106   case ISD::ATOMIC_LOAD_MIN:
14107   case ISD::ATOMIC_LOAD_UMAX:
14108   case ISD::ATOMIC_LOAD_UMIN:
14109   case ISD::ATOMIC_SWAP: {
14110     unsigned Opc;
14111     switch (N->getOpcode()) {
14112     default: llvm_unreachable("Unexpected opcode");
14113     case ISD::ATOMIC_LOAD_ADD:
14114       Opc = X86ISD::ATOMADD64_DAG;
14115       break;
14116     case ISD::ATOMIC_LOAD_AND:
14117       Opc = X86ISD::ATOMAND64_DAG;
14118       break;
14119     case ISD::ATOMIC_LOAD_NAND:
14120       Opc = X86ISD::ATOMNAND64_DAG;
14121       break;
14122     case ISD::ATOMIC_LOAD_OR:
14123       Opc = X86ISD::ATOMOR64_DAG;
14124       break;
14125     case ISD::ATOMIC_LOAD_SUB:
14126       Opc = X86ISD::ATOMSUB64_DAG;
14127       break;
14128     case ISD::ATOMIC_LOAD_XOR:
14129       Opc = X86ISD::ATOMXOR64_DAG;
14130       break;
14131     case ISD::ATOMIC_LOAD_MAX:
14132       Opc = X86ISD::ATOMMAX64_DAG;
14133       break;
14134     case ISD::ATOMIC_LOAD_MIN:
14135       Opc = X86ISD::ATOMMIN64_DAG;
14136       break;
14137     case ISD::ATOMIC_LOAD_UMAX:
14138       Opc = X86ISD::ATOMUMAX64_DAG;
14139       break;
14140     case ISD::ATOMIC_LOAD_UMIN:
14141       Opc = X86ISD::ATOMUMIN64_DAG;
14142       break;
14143     case ISD::ATOMIC_SWAP:
14144       Opc = X86ISD::ATOMSWAP64_DAG;
14145       break;
14146     }
14147     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14148     return;
14149   }
14150   case ISD::ATOMIC_LOAD:
14151     ReplaceATOMIC_LOAD(N, Results, DAG);
14152   }
14153 }
14154
14155 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14156   switch (Opcode) {
14157   default: return NULL;
14158   case X86ISD::BSF:                return "X86ISD::BSF";
14159   case X86ISD::BSR:                return "X86ISD::BSR";
14160   case X86ISD::SHLD:               return "X86ISD::SHLD";
14161   case X86ISD::SHRD:               return "X86ISD::SHRD";
14162   case X86ISD::FAND:               return "X86ISD::FAND";
14163   case X86ISD::FANDN:              return "X86ISD::FANDN";
14164   case X86ISD::FOR:                return "X86ISD::FOR";
14165   case X86ISD::FXOR:               return "X86ISD::FXOR";
14166   case X86ISD::FSRL:               return "X86ISD::FSRL";
14167   case X86ISD::FILD:               return "X86ISD::FILD";
14168   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14169   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14170   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14171   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14172   case X86ISD::FLD:                return "X86ISD::FLD";
14173   case X86ISD::FST:                return "X86ISD::FST";
14174   case X86ISD::CALL:               return "X86ISD::CALL";
14175   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14176   case X86ISD::BT:                 return "X86ISD::BT";
14177   case X86ISD::CMP:                return "X86ISD::CMP";
14178   case X86ISD::COMI:               return "X86ISD::COMI";
14179   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14180   case X86ISD::CMPM:               return "X86ISD::CMPM";
14181   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14182   case X86ISD::SETCC:              return "X86ISD::SETCC";
14183   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14184   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14185   case X86ISD::CMOV:               return "X86ISD::CMOV";
14186   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14187   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14188   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14189   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14190   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14191   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14192   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14193   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14194   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14195   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14196   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14197   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14198   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14199   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14200   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14201   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14202   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14203   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14204   case X86ISD::HADD:               return "X86ISD::HADD";
14205   case X86ISD::HSUB:               return "X86ISD::HSUB";
14206   case X86ISD::FHADD:              return "X86ISD::FHADD";
14207   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14208   case X86ISD::UMAX:               return "X86ISD::UMAX";
14209   case X86ISD::UMIN:               return "X86ISD::UMIN";
14210   case X86ISD::SMAX:               return "X86ISD::SMAX";
14211   case X86ISD::SMIN:               return "X86ISD::SMIN";
14212   case X86ISD::FMAX:               return "X86ISD::FMAX";
14213   case X86ISD::FMIN:               return "X86ISD::FMIN";
14214   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14215   case X86ISD::FMINC:              return "X86ISD::FMINC";
14216   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14217   case X86ISD::FRCP:               return "X86ISD::FRCP";
14218   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14219   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14220   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14221   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14222   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14223   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14224   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14225   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14226   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14227   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14228   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14229   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14230   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14231   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14232   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14233   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14234   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14235   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14236   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14237   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14238   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14239   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14240   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14241   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14242   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14243   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14244   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14245   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14246   case X86ISD::VSHL:               return "X86ISD::VSHL";
14247   case X86ISD::VSRL:               return "X86ISD::VSRL";
14248   case X86ISD::VSRA:               return "X86ISD::VSRA";
14249   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14250   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14251   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14252   case X86ISD::CMPP:               return "X86ISD::CMPP";
14253   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14254   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14255   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14256   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14257   case X86ISD::ADD:                return "X86ISD::ADD";
14258   case X86ISD::SUB:                return "X86ISD::SUB";
14259   case X86ISD::ADC:                return "X86ISD::ADC";
14260   case X86ISD::SBB:                return "X86ISD::SBB";
14261   case X86ISD::SMUL:               return "X86ISD::SMUL";
14262   case X86ISD::UMUL:               return "X86ISD::UMUL";
14263   case X86ISD::INC:                return "X86ISD::INC";
14264   case X86ISD::DEC:                return "X86ISD::DEC";
14265   case X86ISD::OR:                 return "X86ISD::OR";
14266   case X86ISD::XOR:                return "X86ISD::XOR";
14267   case X86ISD::AND:                return "X86ISD::AND";
14268   case X86ISD::BZHI:               return "X86ISD::BZHI";
14269   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14270   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14271   case X86ISD::PTEST:              return "X86ISD::PTEST";
14272   case X86ISD::TESTP:              return "X86ISD::TESTP";
14273   case X86ISD::TESTM:              return "X86ISD::TESTM";
14274   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14275   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14276   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14277   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14278   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14279   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14280   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14281   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14282   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14283   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14284   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14285   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14286   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14287   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14288   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14289   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14290   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14291   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14292   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14293   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14294   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14295   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14296   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14297   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14298   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14299   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14300   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14301   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14302   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14303   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14304   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14305   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14306   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14307   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14308   case X86ISD::SAHF:               return "X86ISD::SAHF";
14309   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14310   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14311   case X86ISD::FMADD:              return "X86ISD::FMADD";
14312   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14313   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14314   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14315   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14316   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14317   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14318   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14319   case X86ISD::XTEST:              return "X86ISD::XTEST";
14320   }
14321 }
14322
14323 // isLegalAddressingMode - Return true if the addressing mode represented
14324 // by AM is legal for this target, for a load/store of the specified type.
14325 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14326                                               Type *Ty) const {
14327   // X86 supports extremely general addressing modes.
14328   CodeModel::Model M = getTargetMachine().getCodeModel();
14329   Reloc::Model R = getTargetMachine().getRelocationModel();
14330
14331   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14332   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14333     return false;
14334
14335   if (AM.BaseGV) {
14336     unsigned GVFlags =
14337       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14338
14339     // If a reference to this global requires an extra load, we can't fold it.
14340     if (isGlobalStubReference(GVFlags))
14341       return false;
14342
14343     // If BaseGV requires a register for the PIC base, we cannot also have a
14344     // BaseReg specified.
14345     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14346       return false;
14347
14348     // If lower 4G is not available, then we must use rip-relative addressing.
14349     if ((M != CodeModel::Small || R != Reloc::Static) &&
14350         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14351       return false;
14352   }
14353
14354   switch (AM.Scale) {
14355   case 0:
14356   case 1:
14357   case 2:
14358   case 4:
14359   case 8:
14360     // These scales always work.
14361     break;
14362   case 3:
14363   case 5:
14364   case 9:
14365     // These scales are formed with basereg+scalereg.  Only accept if there is
14366     // no basereg yet.
14367     if (AM.HasBaseReg)
14368       return false;
14369     break;
14370   default:  // Other stuff never works.
14371     return false;
14372   }
14373
14374   return true;
14375 }
14376
14377 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14378   unsigned Bits = Ty->getScalarSizeInBits();
14379
14380   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14381   // particularly cheaper than those without.
14382   if (Bits == 8)
14383     return false;
14384
14385   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14386   // variable shifts just as cheap as scalar ones.
14387   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14388     return false;
14389
14390   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14391   // fully general vector.
14392   return true;
14393 }
14394
14395 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14396   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14397     return false;
14398   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14399   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14400   return NumBits1 > NumBits2;
14401 }
14402
14403 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14404   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14405     return false;
14406
14407   if (!isTypeLegal(EVT::getEVT(Ty1)))
14408     return false;
14409
14410   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14411
14412   // Assuming the caller doesn't have a zeroext or signext return parameter,
14413   // truncation all the way down to i1 is valid.
14414   return true;
14415 }
14416
14417 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14418   return isInt<32>(Imm);
14419 }
14420
14421 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14422   // Can also use sub to handle negated immediates.
14423   return isInt<32>(Imm);
14424 }
14425
14426 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14427   if (!VT1.isInteger() || !VT2.isInteger())
14428     return false;
14429   unsigned NumBits1 = VT1.getSizeInBits();
14430   unsigned NumBits2 = VT2.getSizeInBits();
14431   return NumBits1 > NumBits2;
14432 }
14433
14434 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14435   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14436   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14437 }
14438
14439 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14440   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14441   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14442 }
14443
14444 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14445   EVT VT1 = Val.getValueType();
14446   if (isZExtFree(VT1, VT2))
14447     return true;
14448
14449   if (Val.getOpcode() != ISD::LOAD)
14450     return false;
14451
14452   if (!VT1.isSimple() || !VT1.isInteger() ||
14453       !VT2.isSimple() || !VT2.isInteger())
14454     return false;
14455
14456   switch (VT1.getSimpleVT().SimpleTy) {
14457   default: break;
14458   case MVT::i8:
14459   case MVT::i16:
14460   case MVT::i32:
14461     // X86 has 8, 16, and 32-bit zero-extending loads.
14462     return true;
14463   }
14464
14465   return false;
14466 }
14467
14468 bool
14469 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14470   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14471     return false;
14472
14473   VT = VT.getScalarType();
14474
14475   if (!VT.isSimple())
14476     return false;
14477
14478   switch (VT.getSimpleVT().SimpleTy) {
14479   case MVT::f32:
14480   case MVT::f64:
14481     return true;
14482   default:
14483     break;
14484   }
14485
14486   return false;
14487 }
14488
14489 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14490   // i16 instructions are longer (0x66 prefix) and potentially slower.
14491   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14492 }
14493
14494 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14495 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14496 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14497 /// are assumed to be legal.
14498 bool
14499 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14500                                       EVT VT) const {
14501   if (!VT.isSimple())
14502     return false;
14503
14504   MVT SVT = VT.getSimpleVT();
14505
14506   // Very little shuffling can be done for 64-bit vectors right now.
14507   if (VT.getSizeInBits() == 64)
14508     return false;
14509
14510   // FIXME: pshufb, blends, shifts.
14511   return (SVT.getVectorNumElements() == 2 ||
14512           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14513           isMOVLMask(M, SVT) ||
14514           isSHUFPMask(M, SVT) ||
14515           isPSHUFDMask(M, SVT) ||
14516           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14517           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14518           isPALIGNRMask(M, SVT, Subtarget) ||
14519           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14520           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14521           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14522           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14523 }
14524
14525 bool
14526 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14527                                           EVT VT) const {
14528   if (!VT.isSimple())
14529     return false;
14530
14531   MVT SVT = VT.getSimpleVT();
14532   unsigned NumElts = SVT.getVectorNumElements();
14533   // FIXME: This collection of masks seems suspect.
14534   if (NumElts == 2)
14535     return true;
14536   if (NumElts == 4 && SVT.is128BitVector()) {
14537     return (isMOVLMask(Mask, SVT)  ||
14538             isCommutedMOVLMask(Mask, SVT, true) ||
14539             isSHUFPMask(Mask, SVT) ||
14540             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14541   }
14542   return false;
14543 }
14544
14545 //===----------------------------------------------------------------------===//
14546 //                           X86 Scheduler Hooks
14547 //===----------------------------------------------------------------------===//
14548
14549 /// Utility function to emit xbegin specifying the start of an RTM region.
14550 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14551                                      const TargetInstrInfo *TII) {
14552   DebugLoc DL = MI->getDebugLoc();
14553
14554   const BasicBlock *BB = MBB->getBasicBlock();
14555   MachineFunction::iterator I = MBB;
14556   ++I;
14557
14558   // For the v = xbegin(), we generate
14559   //
14560   // thisMBB:
14561   //  xbegin sinkMBB
14562   //
14563   // mainMBB:
14564   //  eax = -1
14565   //
14566   // sinkMBB:
14567   //  v = eax
14568
14569   MachineBasicBlock *thisMBB = MBB;
14570   MachineFunction *MF = MBB->getParent();
14571   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14572   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14573   MF->insert(I, mainMBB);
14574   MF->insert(I, sinkMBB);
14575
14576   // Transfer the remainder of BB and its successor edges to sinkMBB.
14577   sinkMBB->splice(sinkMBB->begin(), MBB,
14578                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14579   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14580
14581   // thisMBB:
14582   //  xbegin sinkMBB
14583   //  # fallthrough to mainMBB
14584   //  # abortion to sinkMBB
14585   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14586   thisMBB->addSuccessor(mainMBB);
14587   thisMBB->addSuccessor(sinkMBB);
14588
14589   // mainMBB:
14590   //  EAX = -1
14591   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14592   mainMBB->addSuccessor(sinkMBB);
14593
14594   // sinkMBB:
14595   // EAX is live into the sinkMBB
14596   sinkMBB->addLiveIn(X86::EAX);
14597   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14598           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14599     .addReg(X86::EAX);
14600
14601   MI->eraseFromParent();
14602   return sinkMBB;
14603 }
14604
14605 // Get CMPXCHG opcode for the specified data type.
14606 static unsigned getCmpXChgOpcode(EVT VT) {
14607   switch (VT.getSimpleVT().SimpleTy) {
14608   case MVT::i8:  return X86::LCMPXCHG8;
14609   case MVT::i16: return X86::LCMPXCHG16;
14610   case MVT::i32: return X86::LCMPXCHG32;
14611   case MVT::i64: return X86::LCMPXCHG64;
14612   default:
14613     break;
14614   }
14615   llvm_unreachable("Invalid operand size!");
14616 }
14617
14618 // Get LOAD opcode for the specified data type.
14619 static unsigned getLoadOpcode(EVT VT) {
14620   switch (VT.getSimpleVT().SimpleTy) {
14621   case MVT::i8:  return X86::MOV8rm;
14622   case MVT::i16: return X86::MOV16rm;
14623   case MVT::i32: return X86::MOV32rm;
14624   case MVT::i64: return X86::MOV64rm;
14625   default:
14626     break;
14627   }
14628   llvm_unreachable("Invalid operand size!");
14629 }
14630
14631 // Get opcode of the non-atomic one from the specified atomic instruction.
14632 static unsigned getNonAtomicOpcode(unsigned Opc) {
14633   switch (Opc) {
14634   case X86::ATOMAND8:  return X86::AND8rr;
14635   case X86::ATOMAND16: return X86::AND16rr;
14636   case X86::ATOMAND32: return X86::AND32rr;
14637   case X86::ATOMAND64: return X86::AND64rr;
14638   case X86::ATOMOR8:   return X86::OR8rr;
14639   case X86::ATOMOR16:  return X86::OR16rr;
14640   case X86::ATOMOR32:  return X86::OR32rr;
14641   case X86::ATOMOR64:  return X86::OR64rr;
14642   case X86::ATOMXOR8:  return X86::XOR8rr;
14643   case X86::ATOMXOR16: return X86::XOR16rr;
14644   case X86::ATOMXOR32: return X86::XOR32rr;
14645   case X86::ATOMXOR64: return X86::XOR64rr;
14646   }
14647   llvm_unreachable("Unhandled atomic-load-op opcode!");
14648 }
14649
14650 // Get opcode of the non-atomic one from the specified atomic instruction with
14651 // extra opcode.
14652 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14653                                                unsigned &ExtraOpc) {
14654   switch (Opc) {
14655   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14656   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14657   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14658   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14659   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14660   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14661   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14662   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14663   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14664   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14665   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14666   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14667   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14668   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14669   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14670   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14671   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14672   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14673   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14674   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14675   }
14676   llvm_unreachable("Unhandled atomic-load-op opcode!");
14677 }
14678
14679 // Get opcode of the non-atomic one from the specified atomic instruction for
14680 // 64-bit data type on 32-bit target.
14681 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14682   switch (Opc) {
14683   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14684   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14685   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14686   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14687   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14688   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14689   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14690   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14691   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14692   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14693   }
14694   llvm_unreachable("Unhandled atomic-load-op opcode!");
14695 }
14696
14697 // Get opcode of the non-atomic one from the specified atomic instruction for
14698 // 64-bit data type on 32-bit target with extra opcode.
14699 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14700                                                    unsigned &HiOpc,
14701                                                    unsigned &ExtraOpc) {
14702   switch (Opc) {
14703   case X86::ATOMNAND6432:
14704     ExtraOpc = X86::NOT32r;
14705     HiOpc = X86::AND32rr;
14706     return X86::AND32rr;
14707   }
14708   llvm_unreachable("Unhandled atomic-load-op opcode!");
14709 }
14710
14711 // Get pseudo CMOV opcode from the specified data type.
14712 static unsigned getPseudoCMOVOpc(EVT VT) {
14713   switch (VT.getSimpleVT().SimpleTy) {
14714   case MVT::i8:  return X86::CMOV_GR8;
14715   case MVT::i16: return X86::CMOV_GR16;
14716   case MVT::i32: return X86::CMOV_GR32;
14717   default:
14718     break;
14719   }
14720   llvm_unreachable("Unknown CMOV opcode!");
14721 }
14722
14723 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14724 // They will be translated into a spin-loop or compare-exchange loop from
14725 //
14726 //    ...
14727 //    dst = atomic-fetch-op MI.addr, MI.val
14728 //    ...
14729 //
14730 // to
14731 //
14732 //    ...
14733 //    t1 = LOAD MI.addr
14734 // loop:
14735 //    t4 = phi(t1, t3 / loop)
14736 //    t2 = OP MI.val, t4
14737 //    EAX = t4
14738 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14739 //    t3 = EAX
14740 //    JNE loop
14741 // sink:
14742 //    dst = t3
14743 //    ...
14744 MachineBasicBlock *
14745 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14746                                        MachineBasicBlock *MBB) const {
14747   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14748   DebugLoc DL = MI->getDebugLoc();
14749
14750   MachineFunction *MF = MBB->getParent();
14751   MachineRegisterInfo &MRI = MF->getRegInfo();
14752
14753   const BasicBlock *BB = MBB->getBasicBlock();
14754   MachineFunction::iterator I = MBB;
14755   ++I;
14756
14757   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14758          "Unexpected number of operands");
14759
14760   assert(MI->hasOneMemOperand() &&
14761          "Expected atomic-load-op to have one memoperand");
14762
14763   // Memory Reference
14764   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14765   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14766
14767   unsigned DstReg, SrcReg;
14768   unsigned MemOpndSlot;
14769
14770   unsigned CurOp = 0;
14771
14772   DstReg = MI->getOperand(CurOp++).getReg();
14773   MemOpndSlot = CurOp;
14774   CurOp += X86::AddrNumOperands;
14775   SrcReg = MI->getOperand(CurOp++).getReg();
14776
14777   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14778   MVT::SimpleValueType VT = *RC->vt_begin();
14779   unsigned t1 = MRI.createVirtualRegister(RC);
14780   unsigned t2 = MRI.createVirtualRegister(RC);
14781   unsigned t3 = MRI.createVirtualRegister(RC);
14782   unsigned t4 = MRI.createVirtualRegister(RC);
14783   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14784
14785   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14786   unsigned LOADOpc = getLoadOpcode(VT);
14787
14788   // For the atomic load-arith operator, we generate
14789   //
14790   //  thisMBB:
14791   //    t1 = LOAD [MI.addr]
14792   //  mainMBB:
14793   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14794   //    t1 = OP MI.val, EAX
14795   //    EAX = t4
14796   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14797   //    t3 = EAX
14798   //    JNE mainMBB
14799   //  sinkMBB:
14800   //    dst = t3
14801
14802   MachineBasicBlock *thisMBB = MBB;
14803   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14804   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14805   MF->insert(I, mainMBB);
14806   MF->insert(I, sinkMBB);
14807
14808   MachineInstrBuilder MIB;
14809
14810   // Transfer the remainder of BB and its successor edges to sinkMBB.
14811   sinkMBB->splice(sinkMBB->begin(), MBB,
14812                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14813   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14814
14815   // thisMBB:
14816   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14817   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14818     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14819     if (NewMO.isReg())
14820       NewMO.setIsKill(false);
14821     MIB.addOperand(NewMO);
14822   }
14823   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14824     unsigned flags = (*MMOI)->getFlags();
14825     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14826     MachineMemOperand *MMO =
14827       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14828                                (*MMOI)->getSize(),
14829                                (*MMOI)->getBaseAlignment(),
14830                                (*MMOI)->getTBAAInfo(),
14831                                (*MMOI)->getRanges());
14832     MIB.addMemOperand(MMO);
14833   }
14834
14835   thisMBB->addSuccessor(mainMBB);
14836
14837   // mainMBB:
14838   MachineBasicBlock *origMainMBB = mainMBB;
14839
14840   // Add a PHI.
14841   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14842                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14843
14844   unsigned Opc = MI->getOpcode();
14845   switch (Opc) {
14846   default:
14847     llvm_unreachable("Unhandled atomic-load-op opcode!");
14848   case X86::ATOMAND8:
14849   case X86::ATOMAND16:
14850   case X86::ATOMAND32:
14851   case X86::ATOMAND64:
14852   case X86::ATOMOR8:
14853   case X86::ATOMOR16:
14854   case X86::ATOMOR32:
14855   case X86::ATOMOR64:
14856   case X86::ATOMXOR8:
14857   case X86::ATOMXOR16:
14858   case X86::ATOMXOR32:
14859   case X86::ATOMXOR64: {
14860     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14861     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14862       .addReg(t4);
14863     break;
14864   }
14865   case X86::ATOMNAND8:
14866   case X86::ATOMNAND16:
14867   case X86::ATOMNAND32:
14868   case X86::ATOMNAND64: {
14869     unsigned Tmp = MRI.createVirtualRegister(RC);
14870     unsigned NOTOpc;
14871     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14872     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14873       .addReg(t4);
14874     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14875     break;
14876   }
14877   case X86::ATOMMAX8:
14878   case X86::ATOMMAX16:
14879   case X86::ATOMMAX32:
14880   case X86::ATOMMAX64:
14881   case X86::ATOMMIN8:
14882   case X86::ATOMMIN16:
14883   case X86::ATOMMIN32:
14884   case X86::ATOMMIN64:
14885   case X86::ATOMUMAX8:
14886   case X86::ATOMUMAX16:
14887   case X86::ATOMUMAX32:
14888   case X86::ATOMUMAX64:
14889   case X86::ATOMUMIN8:
14890   case X86::ATOMUMIN16:
14891   case X86::ATOMUMIN32:
14892   case X86::ATOMUMIN64: {
14893     unsigned CMPOpc;
14894     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14895
14896     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14897       .addReg(SrcReg)
14898       .addReg(t4);
14899
14900     if (Subtarget->hasCMov()) {
14901       if (VT != MVT::i8) {
14902         // Native support
14903         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14904           .addReg(SrcReg)
14905           .addReg(t4);
14906       } else {
14907         // Promote i8 to i32 to use CMOV32
14908         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14909         const TargetRegisterClass *RC32 =
14910           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14911         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14912         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14913         unsigned Tmp = MRI.createVirtualRegister(RC32);
14914
14915         unsigned Undef = MRI.createVirtualRegister(RC32);
14916         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14917
14918         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14919           .addReg(Undef)
14920           .addReg(SrcReg)
14921           .addImm(X86::sub_8bit);
14922         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14923           .addReg(Undef)
14924           .addReg(t4)
14925           .addImm(X86::sub_8bit);
14926
14927         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14928           .addReg(SrcReg32)
14929           .addReg(AccReg32);
14930
14931         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14932           .addReg(Tmp, 0, X86::sub_8bit);
14933       }
14934     } else {
14935       // Use pseudo select and lower them.
14936       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14937              "Invalid atomic-load-op transformation!");
14938       unsigned SelOpc = getPseudoCMOVOpc(VT);
14939       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14940       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14941       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14942               .addReg(SrcReg).addReg(t4)
14943               .addImm(CC);
14944       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14945       // Replace the original PHI node as mainMBB is changed after CMOV
14946       // lowering.
14947       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14948         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14949       Phi->eraseFromParent();
14950     }
14951     break;
14952   }
14953   }
14954
14955   // Copy PhyReg back from virtual register.
14956   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14957     .addReg(t4);
14958
14959   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14960   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14961     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14962     if (NewMO.isReg())
14963       NewMO.setIsKill(false);
14964     MIB.addOperand(NewMO);
14965   }
14966   MIB.addReg(t2);
14967   MIB.setMemRefs(MMOBegin, MMOEnd);
14968
14969   // Copy PhyReg back to virtual register.
14970   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14971     .addReg(PhyReg);
14972
14973   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14974
14975   mainMBB->addSuccessor(origMainMBB);
14976   mainMBB->addSuccessor(sinkMBB);
14977
14978   // sinkMBB:
14979   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14980           TII->get(TargetOpcode::COPY), DstReg)
14981     .addReg(t3);
14982
14983   MI->eraseFromParent();
14984   return sinkMBB;
14985 }
14986
14987 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14988 // instructions. They will be translated into a spin-loop or compare-exchange
14989 // loop from
14990 //
14991 //    ...
14992 //    dst = atomic-fetch-op MI.addr, MI.val
14993 //    ...
14994 //
14995 // to
14996 //
14997 //    ...
14998 //    t1L = LOAD [MI.addr + 0]
14999 //    t1H = LOAD [MI.addr + 4]
15000 // loop:
15001 //    t4L = phi(t1L, t3L / loop)
15002 //    t4H = phi(t1H, t3H / loop)
15003 //    t2L = OP MI.val.lo, t4L
15004 //    t2H = OP MI.val.hi, t4H
15005 //    EAX = t4L
15006 //    EDX = t4H
15007 //    EBX = t2L
15008 //    ECX = t2H
15009 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15010 //    t3L = EAX
15011 //    t3H = EDX
15012 //    JNE loop
15013 // sink:
15014 //    dstL = t3L
15015 //    dstH = t3H
15016 //    ...
15017 MachineBasicBlock *
15018 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15019                                            MachineBasicBlock *MBB) const {
15020   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15021   DebugLoc DL = MI->getDebugLoc();
15022
15023   MachineFunction *MF = MBB->getParent();
15024   MachineRegisterInfo &MRI = MF->getRegInfo();
15025
15026   const BasicBlock *BB = MBB->getBasicBlock();
15027   MachineFunction::iterator I = MBB;
15028   ++I;
15029
15030   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15031          "Unexpected number of operands");
15032
15033   assert(MI->hasOneMemOperand() &&
15034          "Expected atomic-load-op32 to have one memoperand");
15035
15036   // Memory Reference
15037   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15038   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15039
15040   unsigned DstLoReg, DstHiReg;
15041   unsigned SrcLoReg, SrcHiReg;
15042   unsigned MemOpndSlot;
15043
15044   unsigned CurOp = 0;
15045
15046   DstLoReg = MI->getOperand(CurOp++).getReg();
15047   DstHiReg = MI->getOperand(CurOp++).getReg();
15048   MemOpndSlot = CurOp;
15049   CurOp += X86::AddrNumOperands;
15050   SrcLoReg = MI->getOperand(CurOp++).getReg();
15051   SrcHiReg = MI->getOperand(CurOp++).getReg();
15052
15053   const TargetRegisterClass *RC = &X86::GR32RegClass;
15054   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15055
15056   unsigned t1L = MRI.createVirtualRegister(RC);
15057   unsigned t1H = MRI.createVirtualRegister(RC);
15058   unsigned t2L = MRI.createVirtualRegister(RC);
15059   unsigned t2H = MRI.createVirtualRegister(RC);
15060   unsigned t3L = MRI.createVirtualRegister(RC);
15061   unsigned t3H = MRI.createVirtualRegister(RC);
15062   unsigned t4L = MRI.createVirtualRegister(RC);
15063   unsigned t4H = MRI.createVirtualRegister(RC);
15064
15065   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15066   unsigned LOADOpc = X86::MOV32rm;
15067
15068   // For the atomic load-arith operator, we generate
15069   //
15070   //  thisMBB:
15071   //    t1L = LOAD [MI.addr + 0]
15072   //    t1H = LOAD [MI.addr + 4]
15073   //  mainMBB:
15074   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15075   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15076   //    t2L = OP MI.val.lo, t4L
15077   //    t2H = OP MI.val.hi, t4H
15078   //    EBX = t2L
15079   //    ECX = t2H
15080   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15081   //    t3L = EAX
15082   //    t3H = EDX
15083   //    JNE loop
15084   //  sinkMBB:
15085   //    dstL = t3L
15086   //    dstH = t3H
15087
15088   MachineBasicBlock *thisMBB = MBB;
15089   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15090   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15091   MF->insert(I, mainMBB);
15092   MF->insert(I, sinkMBB);
15093
15094   MachineInstrBuilder MIB;
15095
15096   // Transfer the remainder of BB and its successor edges to sinkMBB.
15097   sinkMBB->splice(sinkMBB->begin(), MBB,
15098                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15099   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15100
15101   // thisMBB:
15102   // Lo
15103   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15104   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15105     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15106     if (NewMO.isReg())
15107       NewMO.setIsKill(false);
15108     MIB.addOperand(NewMO);
15109   }
15110   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15111     unsigned flags = (*MMOI)->getFlags();
15112     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15113     MachineMemOperand *MMO =
15114       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15115                                (*MMOI)->getSize(),
15116                                (*MMOI)->getBaseAlignment(),
15117                                (*MMOI)->getTBAAInfo(),
15118                                (*MMOI)->getRanges());
15119     MIB.addMemOperand(MMO);
15120   };
15121   MachineInstr *LowMI = MIB;
15122
15123   // Hi
15124   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15125   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15126     if (i == X86::AddrDisp) {
15127       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15128     } else {
15129       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15130       if (NewMO.isReg())
15131         NewMO.setIsKill(false);
15132       MIB.addOperand(NewMO);
15133     }
15134   }
15135   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15136
15137   thisMBB->addSuccessor(mainMBB);
15138
15139   // mainMBB:
15140   MachineBasicBlock *origMainMBB = mainMBB;
15141
15142   // Add PHIs.
15143   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15144                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15145   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15146                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15147
15148   unsigned Opc = MI->getOpcode();
15149   switch (Opc) {
15150   default:
15151     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15152   case X86::ATOMAND6432:
15153   case X86::ATOMOR6432:
15154   case X86::ATOMXOR6432:
15155   case X86::ATOMADD6432:
15156   case X86::ATOMSUB6432: {
15157     unsigned HiOpc;
15158     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15159     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15160       .addReg(SrcLoReg);
15161     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15162       .addReg(SrcHiReg);
15163     break;
15164   }
15165   case X86::ATOMNAND6432: {
15166     unsigned HiOpc, NOTOpc;
15167     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15168     unsigned TmpL = MRI.createVirtualRegister(RC);
15169     unsigned TmpH = MRI.createVirtualRegister(RC);
15170     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15171       .addReg(t4L);
15172     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15173       .addReg(t4H);
15174     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15175     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15176     break;
15177   }
15178   case X86::ATOMMAX6432:
15179   case X86::ATOMMIN6432:
15180   case X86::ATOMUMAX6432:
15181   case X86::ATOMUMIN6432: {
15182     unsigned HiOpc;
15183     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15184     unsigned cL = MRI.createVirtualRegister(RC8);
15185     unsigned cH = MRI.createVirtualRegister(RC8);
15186     unsigned cL32 = MRI.createVirtualRegister(RC);
15187     unsigned cH32 = MRI.createVirtualRegister(RC);
15188     unsigned cc = MRI.createVirtualRegister(RC);
15189     // cl := cmp src_lo, lo
15190     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15191       .addReg(SrcLoReg).addReg(t4L);
15192     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15193     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15194     // ch := cmp src_hi, hi
15195     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15196       .addReg(SrcHiReg).addReg(t4H);
15197     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15198     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15199     // cc := if (src_hi == hi) ? cl : ch;
15200     if (Subtarget->hasCMov()) {
15201       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15202         .addReg(cH32).addReg(cL32);
15203     } else {
15204       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15205               .addReg(cH32).addReg(cL32)
15206               .addImm(X86::COND_E);
15207       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15208     }
15209     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15210     if (Subtarget->hasCMov()) {
15211       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15212         .addReg(SrcLoReg).addReg(t4L);
15213       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15214         .addReg(SrcHiReg).addReg(t4H);
15215     } else {
15216       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15217               .addReg(SrcLoReg).addReg(t4L)
15218               .addImm(X86::COND_NE);
15219       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15220       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15221       // 2nd CMOV lowering.
15222       mainMBB->addLiveIn(X86::EFLAGS);
15223       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15224               .addReg(SrcHiReg).addReg(t4H)
15225               .addImm(X86::COND_NE);
15226       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15227       // Replace the original PHI node as mainMBB is changed after CMOV
15228       // lowering.
15229       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15230         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15231       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15232         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15233       PhiL->eraseFromParent();
15234       PhiH->eraseFromParent();
15235     }
15236     break;
15237   }
15238   case X86::ATOMSWAP6432: {
15239     unsigned HiOpc;
15240     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15241     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15242     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15243     break;
15244   }
15245   }
15246
15247   // Copy EDX:EAX back from HiReg:LoReg
15248   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15249   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15250   // Copy ECX:EBX from t1H:t1L
15251   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15252   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15253
15254   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15255   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15256     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15257     if (NewMO.isReg())
15258       NewMO.setIsKill(false);
15259     MIB.addOperand(NewMO);
15260   }
15261   MIB.setMemRefs(MMOBegin, MMOEnd);
15262
15263   // Copy EDX:EAX back to t3H:t3L
15264   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15265   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15266
15267   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15268
15269   mainMBB->addSuccessor(origMainMBB);
15270   mainMBB->addSuccessor(sinkMBB);
15271
15272   // sinkMBB:
15273   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15274           TII->get(TargetOpcode::COPY), DstLoReg)
15275     .addReg(t3L);
15276   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15277           TII->get(TargetOpcode::COPY), DstHiReg)
15278     .addReg(t3H);
15279
15280   MI->eraseFromParent();
15281   return sinkMBB;
15282 }
15283
15284 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15285 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15286 // in the .td file.
15287 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15288                                        const TargetInstrInfo *TII) {
15289   unsigned Opc;
15290   switch (MI->getOpcode()) {
15291   default: llvm_unreachable("illegal opcode!");
15292   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15293   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15294   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15295   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15296   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15297   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15298   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15299   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15300   }
15301
15302   DebugLoc dl = MI->getDebugLoc();
15303   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15304
15305   unsigned NumArgs = MI->getNumOperands();
15306   for (unsigned i = 1; i < NumArgs; ++i) {
15307     MachineOperand &Op = MI->getOperand(i);
15308     if (!(Op.isReg() && Op.isImplicit()))
15309       MIB.addOperand(Op);
15310   }
15311   if (MI->hasOneMemOperand())
15312     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15313
15314   BuildMI(*BB, MI, dl,
15315     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15316     .addReg(X86::XMM0);
15317
15318   MI->eraseFromParent();
15319   return BB;
15320 }
15321
15322 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15323 // defs in an instruction pattern
15324 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15325                                        const TargetInstrInfo *TII) {
15326   unsigned Opc;
15327   switch (MI->getOpcode()) {
15328   default: llvm_unreachable("illegal opcode!");
15329   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15330   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15331   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15332   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15333   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15334   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15335   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15336   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15337   }
15338
15339   DebugLoc dl = MI->getDebugLoc();
15340   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15341
15342   unsigned NumArgs = MI->getNumOperands(); // remove the results
15343   for (unsigned i = 1; i < NumArgs; ++i) {
15344     MachineOperand &Op = MI->getOperand(i);
15345     if (!(Op.isReg() && Op.isImplicit()))
15346       MIB.addOperand(Op);
15347   }
15348   if (MI->hasOneMemOperand())
15349     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15350
15351   BuildMI(*BB, MI, dl,
15352     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15353     .addReg(X86::ECX);
15354
15355   MI->eraseFromParent();
15356   return BB;
15357 }
15358
15359 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15360                                        const TargetInstrInfo *TII,
15361                                        const X86Subtarget* Subtarget) {
15362   DebugLoc dl = MI->getDebugLoc();
15363
15364   // Address into RAX/EAX, other two args into ECX, EDX.
15365   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15366   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15367   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15368   for (int i = 0; i < X86::AddrNumOperands; ++i)
15369     MIB.addOperand(MI->getOperand(i));
15370
15371   unsigned ValOps = X86::AddrNumOperands;
15372   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15373     .addReg(MI->getOperand(ValOps).getReg());
15374   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15375     .addReg(MI->getOperand(ValOps+1).getReg());
15376
15377   // The instruction doesn't actually take any operands though.
15378   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15379
15380   MI->eraseFromParent(); // The pseudo is gone now.
15381   return BB;
15382 }
15383
15384 MachineBasicBlock *
15385 X86TargetLowering::EmitVAARG64WithCustomInserter(
15386                    MachineInstr *MI,
15387                    MachineBasicBlock *MBB) const {
15388   // Emit va_arg instruction on X86-64.
15389
15390   // Operands to this pseudo-instruction:
15391   // 0  ) Output        : destination address (reg)
15392   // 1-5) Input         : va_list address (addr, i64mem)
15393   // 6  ) ArgSize       : Size (in bytes) of vararg type
15394   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15395   // 8  ) Align         : Alignment of type
15396   // 9  ) EFLAGS (implicit-def)
15397
15398   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15399   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15400
15401   unsigned DestReg = MI->getOperand(0).getReg();
15402   MachineOperand &Base = MI->getOperand(1);
15403   MachineOperand &Scale = MI->getOperand(2);
15404   MachineOperand &Index = MI->getOperand(3);
15405   MachineOperand &Disp = MI->getOperand(4);
15406   MachineOperand &Segment = MI->getOperand(5);
15407   unsigned ArgSize = MI->getOperand(6).getImm();
15408   unsigned ArgMode = MI->getOperand(7).getImm();
15409   unsigned Align = MI->getOperand(8).getImm();
15410
15411   // Memory Reference
15412   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15413   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15414   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15415
15416   // Machine Information
15417   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15418   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15419   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15420   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15421   DebugLoc DL = MI->getDebugLoc();
15422
15423   // struct va_list {
15424   //   i32   gp_offset
15425   //   i32   fp_offset
15426   //   i64   overflow_area (address)
15427   //   i64   reg_save_area (address)
15428   // }
15429   // sizeof(va_list) = 24
15430   // alignment(va_list) = 8
15431
15432   unsigned TotalNumIntRegs = 6;
15433   unsigned TotalNumXMMRegs = 8;
15434   bool UseGPOffset = (ArgMode == 1);
15435   bool UseFPOffset = (ArgMode == 2);
15436   unsigned MaxOffset = TotalNumIntRegs * 8 +
15437                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15438
15439   /* Align ArgSize to a multiple of 8 */
15440   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15441   bool NeedsAlign = (Align > 8);
15442
15443   MachineBasicBlock *thisMBB = MBB;
15444   MachineBasicBlock *overflowMBB;
15445   MachineBasicBlock *offsetMBB;
15446   MachineBasicBlock *endMBB;
15447
15448   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15449   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15450   unsigned OffsetReg = 0;
15451
15452   if (!UseGPOffset && !UseFPOffset) {
15453     // If we only pull from the overflow region, we don't create a branch.
15454     // We don't need to alter control flow.
15455     OffsetDestReg = 0; // unused
15456     OverflowDestReg = DestReg;
15457
15458     offsetMBB = NULL;
15459     overflowMBB = thisMBB;
15460     endMBB = thisMBB;
15461   } else {
15462     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15463     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15464     // If not, pull from overflow_area. (branch to overflowMBB)
15465     //
15466     //       thisMBB
15467     //         |     .
15468     //         |        .
15469     //     offsetMBB   overflowMBB
15470     //         |        .
15471     //         |     .
15472     //        endMBB
15473
15474     // Registers for the PHI in endMBB
15475     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15476     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15477
15478     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15479     MachineFunction *MF = MBB->getParent();
15480     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15481     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15482     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15483
15484     MachineFunction::iterator MBBIter = MBB;
15485     ++MBBIter;
15486
15487     // Insert the new basic blocks
15488     MF->insert(MBBIter, offsetMBB);
15489     MF->insert(MBBIter, overflowMBB);
15490     MF->insert(MBBIter, endMBB);
15491
15492     // Transfer the remainder of MBB and its successor edges to endMBB.
15493     endMBB->splice(endMBB->begin(), thisMBB,
15494                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15495     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15496
15497     // Make offsetMBB and overflowMBB successors of thisMBB
15498     thisMBB->addSuccessor(offsetMBB);
15499     thisMBB->addSuccessor(overflowMBB);
15500
15501     // endMBB is a successor of both offsetMBB and overflowMBB
15502     offsetMBB->addSuccessor(endMBB);
15503     overflowMBB->addSuccessor(endMBB);
15504
15505     // Load the offset value into a register
15506     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15507     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15508       .addOperand(Base)
15509       .addOperand(Scale)
15510       .addOperand(Index)
15511       .addDisp(Disp, UseFPOffset ? 4 : 0)
15512       .addOperand(Segment)
15513       .setMemRefs(MMOBegin, MMOEnd);
15514
15515     // Check if there is enough room left to pull this argument.
15516     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15517       .addReg(OffsetReg)
15518       .addImm(MaxOffset + 8 - ArgSizeA8);
15519
15520     // Branch to "overflowMBB" if offset >= max
15521     // Fall through to "offsetMBB" otherwise
15522     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15523       .addMBB(overflowMBB);
15524   }
15525
15526   // In offsetMBB, emit code to use the reg_save_area.
15527   if (offsetMBB) {
15528     assert(OffsetReg != 0);
15529
15530     // Read the reg_save_area address.
15531     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15532     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15533       .addOperand(Base)
15534       .addOperand(Scale)
15535       .addOperand(Index)
15536       .addDisp(Disp, 16)
15537       .addOperand(Segment)
15538       .setMemRefs(MMOBegin, MMOEnd);
15539
15540     // Zero-extend the offset
15541     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15542       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15543         .addImm(0)
15544         .addReg(OffsetReg)
15545         .addImm(X86::sub_32bit);
15546
15547     // Add the offset to the reg_save_area to get the final address.
15548     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15549       .addReg(OffsetReg64)
15550       .addReg(RegSaveReg);
15551
15552     // Compute the offset for the next argument
15553     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15554     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15555       .addReg(OffsetReg)
15556       .addImm(UseFPOffset ? 16 : 8);
15557
15558     // Store it back into the va_list.
15559     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15560       .addOperand(Base)
15561       .addOperand(Scale)
15562       .addOperand(Index)
15563       .addDisp(Disp, UseFPOffset ? 4 : 0)
15564       .addOperand(Segment)
15565       .addReg(NextOffsetReg)
15566       .setMemRefs(MMOBegin, MMOEnd);
15567
15568     // Jump to endMBB
15569     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15570       .addMBB(endMBB);
15571   }
15572
15573   //
15574   // Emit code to use overflow area
15575   //
15576
15577   // Load the overflow_area address into a register.
15578   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15579   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15580     .addOperand(Base)
15581     .addOperand(Scale)
15582     .addOperand(Index)
15583     .addDisp(Disp, 8)
15584     .addOperand(Segment)
15585     .setMemRefs(MMOBegin, MMOEnd);
15586
15587   // If we need to align it, do so. Otherwise, just copy the address
15588   // to OverflowDestReg.
15589   if (NeedsAlign) {
15590     // Align the overflow address
15591     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15592     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15593
15594     // aligned_addr = (addr + (align-1)) & ~(align-1)
15595     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15596       .addReg(OverflowAddrReg)
15597       .addImm(Align-1);
15598
15599     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15600       .addReg(TmpReg)
15601       .addImm(~(uint64_t)(Align-1));
15602   } else {
15603     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15604       .addReg(OverflowAddrReg);
15605   }
15606
15607   // Compute the next overflow address after this argument.
15608   // (the overflow address should be kept 8-byte aligned)
15609   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15610   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15611     .addReg(OverflowDestReg)
15612     .addImm(ArgSizeA8);
15613
15614   // Store the new overflow address.
15615   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15616     .addOperand(Base)
15617     .addOperand(Scale)
15618     .addOperand(Index)
15619     .addDisp(Disp, 8)
15620     .addOperand(Segment)
15621     .addReg(NextAddrReg)
15622     .setMemRefs(MMOBegin, MMOEnd);
15623
15624   // If we branched, emit the PHI to the front of endMBB.
15625   if (offsetMBB) {
15626     BuildMI(*endMBB, endMBB->begin(), DL,
15627             TII->get(X86::PHI), DestReg)
15628       .addReg(OffsetDestReg).addMBB(offsetMBB)
15629       .addReg(OverflowDestReg).addMBB(overflowMBB);
15630   }
15631
15632   // Erase the pseudo instruction
15633   MI->eraseFromParent();
15634
15635   return endMBB;
15636 }
15637
15638 MachineBasicBlock *
15639 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15640                                                  MachineInstr *MI,
15641                                                  MachineBasicBlock *MBB) const {
15642   // Emit code to save XMM registers to the stack. The ABI says that the
15643   // number of registers to save is given in %al, so it's theoretically
15644   // possible to do an indirect jump trick to avoid saving all of them,
15645   // however this code takes a simpler approach and just executes all
15646   // of the stores if %al is non-zero. It's less code, and it's probably
15647   // easier on the hardware branch predictor, and stores aren't all that
15648   // expensive anyway.
15649
15650   // Create the new basic blocks. One block contains all the XMM stores,
15651   // and one block is the final destination regardless of whether any
15652   // stores were performed.
15653   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15654   MachineFunction *F = MBB->getParent();
15655   MachineFunction::iterator MBBIter = MBB;
15656   ++MBBIter;
15657   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15658   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15659   F->insert(MBBIter, XMMSaveMBB);
15660   F->insert(MBBIter, EndMBB);
15661
15662   // Transfer the remainder of MBB and its successor edges to EndMBB.
15663   EndMBB->splice(EndMBB->begin(), MBB,
15664                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15665   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15666
15667   // The original block will now fall through to the XMM save block.
15668   MBB->addSuccessor(XMMSaveMBB);
15669   // The XMMSaveMBB will fall through to the end block.
15670   XMMSaveMBB->addSuccessor(EndMBB);
15671
15672   // Now add the instructions.
15673   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15674   DebugLoc DL = MI->getDebugLoc();
15675
15676   unsigned CountReg = MI->getOperand(0).getReg();
15677   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15678   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15679
15680   if (!Subtarget->isTargetWin64()) {
15681     // If %al is 0, branch around the XMM save block.
15682     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15683     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15684     MBB->addSuccessor(EndMBB);
15685   }
15686
15687   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15688   // that was just emitted, but clearly shouldn't be "saved".
15689   assert((MI->getNumOperands() <= 3 ||
15690           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15691           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15692          && "Expected last argument to be EFLAGS");
15693   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15694   // In the XMM save block, save all the XMM argument registers.
15695   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15696     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15697     MachineMemOperand *MMO =
15698       F->getMachineMemOperand(
15699           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15700         MachineMemOperand::MOStore,
15701         /*Size=*/16, /*Align=*/16);
15702     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15703       .addFrameIndex(RegSaveFrameIndex)
15704       .addImm(/*Scale=*/1)
15705       .addReg(/*IndexReg=*/0)
15706       .addImm(/*Disp=*/Offset)
15707       .addReg(/*Segment=*/0)
15708       .addReg(MI->getOperand(i).getReg())
15709       .addMemOperand(MMO);
15710   }
15711
15712   MI->eraseFromParent();   // The pseudo instruction is gone now.
15713
15714   return EndMBB;
15715 }
15716
15717 // The EFLAGS operand of SelectItr might be missing a kill marker
15718 // because there were multiple uses of EFLAGS, and ISel didn't know
15719 // which to mark. Figure out whether SelectItr should have had a
15720 // kill marker, and set it if it should. Returns the correct kill
15721 // marker value.
15722 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15723                                      MachineBasicBlock* BB,
15724                                      const TargetRegisterInfo* TRI) {
15725   // Scan forward through BB for a use/def of EFLAGS.
15726   MachineBasicBlock::iterator miI(std::next(SelectItr));
15727   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15728     const MachineInstr& mi = *miI;
15729     if (mi.readsRegister(X86::EFLAGS))
15730       return false;
15731     if (mi.definesRegister(X86::EFLAGS))
15732       break; // Should have kill-flag - update below.
15733   }
15734
15735   // If we hit the end of the block, check whether EFLAGS is live into a
15736   // successor.
15737   if (miI == BB->end()) {
15738     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15739                                           sEnd = BB->succ_end();
15740          sItr != sEnd; ++sItr) {
15741       MachineBasicBlock* succ = *sItr;
15742       if (succ->isLiveIn(X86::EFLAGS))
15743         return false;
15744     }
15745   }
15746
15747   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15748   // out. SelectMI should have a kill flag on EFLAGS.
15749   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15750   return true;
15751 }
15752
15753 MachineBasicBlock *
15754 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15755                                      MachineBasicBlock *BB) const {
15756   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15757   DebugLoc DL = MI->getDebugLoc();
15758
15759   // To "insert" a SELECT_CC instruction, we actually have to insert the
15760   // diamond control-flow pattern.  The incoming instruction knows the
15761   // destination vreg to set, the condition code register to branch on, the
15762   // true/false values to select between, and a branch opcode to use.
15763   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15764   MachineFunction::iterator It = BB;
15765   ++It;
15766
15767   //  thisMBB:
15768   //  ...
15769   //   TrueVal = ...
15770   //   cmpTY ccX, r1, r2
15771   //   bCC copy1MBB
15772   //   fallthrough --> copy0MBB
15773   MachineBasicBlock *thisMBB = BB;
15774   MachineFunction *F = BB->getParent();
15775   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15776   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15777   F->insert(It, copy0MBB);
15778   F->insert(It, sinkMBB);
15779
15780   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15781   // live into the sink and copy blocks.
15782   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15783   if (!MI->killsRegister(X86::EFLAGS) &&
15784       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15785     copy0MBB->addLiveIn(X86::EFLAGS);
15786     sinkMBB->addLiveIn(X86::EFLAGS);
15787   }
15788
15789   // Transfer the remainder of BB and its successor edges to sinkMBB.
15790   sinkMBB->splice(sinkMBB->begin(), BB,
15791                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
15792   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15793
15794   // Add the true and fallthrough blocks as its successors.
15795   BB->addSuccessor(copy0MBB);
15796   BB->addSuccessor(sinkMBB);
15797
15798   // Create the conditional branch instruction.
15799   unsigned Opc =
15800     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15801   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15802
15803   //  copy0MBB:
15804   //   %FalseValue = ...
15805   //   # fallthrough to sinkMBB
15806   copy0MBB->addSuccessor(sinkMBB);
15807
15808   //  sinkMBB:
15809   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15810   //  ...
15811   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15812           TII->get(X86::PHI), MI->getOperand(0).getReg())
15813     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15814     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15815
15816   MI->eraseFromParent();   // The pseudo instruction is gone now.
15817   return sinkMBB;
15818 }
15819
15820 MachineBasicBlock *
15821 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15822                                         bool Is64Bit) const {
15823   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15824   DebugLoc DL = MI->getDebugLoc();
15825   MachineFunction *MF = BB->getParent();
15826   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15827
15828   assert(MF->shouldSplitStack());
15829
15830   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15831   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15832
15833   // BB:
15834   //  ... [Till the alloca]
15835   // If stacklet is not large enough, jump to mallocMBB
15836   //
15837   // bumpMBB:
15838   //  Allocate by subtracting from RSP
15839   //  Jump to continueMBB
15840   //
15841   // mallocMBB:
15842   //  Allocate by call to runtime
15843   //
15844   // continueMBB:
15845   //  ...
15846   //  [rest of original BB]
15847   //
15848
15849   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15850   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15851   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15852
15853   MachineRegisterInfo &MRI = MF->getRegInfo();
15854   const TargetRegisterClass *AddrRegClass =
15855     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15856
15857   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15858     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15859     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15860     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15861     sizeVReg = MI->getOperand(1).getReg(),
15862     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15863
15864   MachineFunction::iterator MBBIter = BB;
15865   ++MBBIter;
15866
15867   MF->insert(MBBIter, bumpMBB);
15868   MF->insert(MBBIter, mallocMBB);
15869   MF->insert(MBBIter, continueMBB);
15870
15871   continueMBB->splice(continueMBB->begin(), BB,
15872                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
15873   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15874
15875   // Add code to the main basic block to check if the stack limit has been hit,
15876   // and if so, jump to mallocMBB otherwise to bumpMBB.
15877   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15878   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15879     .addReg(tmpSPVReg).addReg(sizeVReg);
15880   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15881     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15882     .addReg(SPLimitVReg);
15883   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15884
15885   // bumpMBB simply decreases the stack pointer, since we know the current
15886   // stacklet has enough space.
15887   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15888     .addReg(SPLimitVReg);
15889   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15890     .addReg(SPLimitVReg);
15891   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15892
15893   // Calls into a routine in libgcc to allocate more space from the heap.
15894   const uint32_t *RegMask =
15895     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15896   if (Is64Bit) {
15897     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15898       .addReg(sizeVReg);
15899     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15900       .addExternalSymbol("__morestack_allocate_stack_space")
15901       .addRegMask(RegMask)
15902       .addReg(X86::RDI, RegState::Implicit)
15903       .addReg(X86::RAX, RegState::ImplicitDefine);
15904   } else {
15905     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15906       .addImm(12);
15907     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15908     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15909       .addExternalSymbol("__morestack_allocate_stack_space")
15910       .addRegMask(RegMask)
15911       .addReg(X86::EAX, RegState::ImplicitDefine);
15912   }
15913
15914   if (!Is64Bit)
15915     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15916       .addImm(16);
15917
15918   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15919     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15920   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15921
15922   // Set up the CFG correctly.
15923   BB->addSuccessor(bumpMBB);
15924   BB->addSuccessor(mallocMBB);
15925   mallocMBB->addSuccessor(continueMBB);
15926   bumpMBB->addSuccessor(continueMBB);
15927
15928   // Take care of the PHI nodes.
15929   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15930           MI->getOperand(0).getReg())
15931     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15932     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15933
15934   // Delete the original pseudo instruction.
15935   MI->eraseFromParent();
15936
15937   // And we're done.
15938   return continueMBB;
15939 }
15940
15941 MachineBasicBlock *
15942 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15943                                           MachineBasicBlock *BB) const {
15944   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15945   DebugLoc DL = MI->getDebugLoc();
15946
15947   assert(!Subtarget->isTargetMacho());
15948
15949   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15950   // non-trivial part is impdef of ESP.
15951
15952   if (Subtarget->isTargetWin64()) {
15953     if (Subtarget->isTargetCygMing()) {
15954       // ___chkstk(Mingw64):
15955       // Clobbers R10, R11, RAX and EFLAGS.
15956       // Updates RSP.
15957       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15958         .addExternalSymbol("___chkstk")
15959         .addReg(X86::RAX, RegState::Implicit)
15960         .addReg(X86::RSP, RegState::Implicit)
15961         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15962         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15963         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15964     } else {
15965       // __chkstk(MSVCRT): does not update stack pointer.
15966       // Clobbers R10, R11 and EFLAGS.
15967       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15968         .addExternalSymbol("__chkstk")
15969         .addReg(X86::RAX, RegState::Implicit)
15970         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15971       // RAX has the offset to be subtracted from RSP.
15972       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15973         .addReg(X86::RSP)
15974         .addReg(X86::RAX);
15975     }
15976   } else {
15977     const char *StackProbeSymbol =
15978       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
15979
15980     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15981       .addExternalSymbol(StackProbeSymbol)
15982       .addReg(X86::EAX, RegState::Implicit)
15983       .addReg(X86::ESP, RegState::Implicit)
15984       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15985       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15986       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15987   }
15988
15989   MI->eraseFromParent();   // The pseudo instruction is gone now.
15990   return BB;
15991 }
15992
15993 MachineBasicBlock *
15994 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15995                                       MachineBasicBlock *BB) const {
15996   // This is pretty easy.  We're taking the value that we received from
15997   // our load from the relocation, sticking it in either RDI (x86-64)
15998   // or EAX and doing an indirect call.  The return value will then
15999   // be in the normal return register.
16000   const X86InstrInfo *TII
16001     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16002   DebugLoc DL = MI->getDebugLoc();
16003   MachineFunction *F = BB->getParent();
16004
16005   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16006   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16007
16008   // Get a register mask for the lowered call.
16009   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16010   // proper register mask.
16011   const uint32_t *RegMask =
16012     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16013   if (Subtarget->is64Bit()) {
16014     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16015                                       TII->get(X86::MOV64rm), X86::RDI)
16016     .addReg(X86::RIP)
16017     .addImm(0).addReg(0)
16018     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16019                       MI->getOperand(3).getTargetFlags())
16020     .addReg(0);
16021     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16022     addDirectMem(MIB, X86::RDI);
16023     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16024   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16025     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16026                                       TII->get(X86::MOV32rm), X86::EAX)
16027     .addReg(0)
16028     .addImm(0).addReg(0)
16029     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16030                       MI->getOperand(3).getTargetFlags())
16031     .addReg(0);
16032     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16033     addDirectMem(MIB, X86::EAX);
16034     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16035   } else {
16036     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16037                                       TII->get(X86::MOV32rm), X86::EAX)
16038     .addReg(TII->getGlobalBaseReg(F))
16039     .addImm(0).addReg(0)
16040     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16041                       MI->getOperand(3).getTargetFlags())
16042     .addReg(0);
16043     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16044     addDirectMem(MIB, X86::EAX);
16045     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16046   }
16047
16048   MI->eraseFromParent(); // The pseudo instruction is gone now.
16049   return BB;
16050 }
16051
16052 MachineBasicBlock *
16053 X86TargetLowering::emitEHSjLjSetJmp(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   const BasicBlock *BB = MBB->getBasicBlock();
16062   MachineFunction::iterator I = MBB;
16063   ++I;
16064
16065   // Memory Reference
16066   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16067   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16068
16069   unsigned DstReg;
16070   unsigned MemOpndSlot = 0;
16071
16072   unsigned CurOp = 0;
16073
16074   DstReg = MI->getOperand(CurOp++).getReg();
16075   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16076   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16077   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16078   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16079
16080   MemOpndSlot = CurOp;
16081
16082   MVT PVT = getPointerTy();
16083   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16084          "Invalid Pointer Size!");
16085
16086   // For v = setjmp(buf), we generate
16087   //
16088   // thisMBB:
16089   //  buf[LabelOffset] = restoreMBB
16090   //  SjLjSetup restoreMBB
16091   //
16092   // mainMBB:
16093   //  v_main = 0
16094   //
16095   // sinkMBB:
16096   //  v = phi(main, restore)
16097   //
16098   // restoreMBB:
16099   //  v_restore = 1
16100
16101   MachineBasicBlock *thisMBB = MBB;
16102   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16103   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16104   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16105   MF->insert(I, mainMBB);
16106   MF->insert(I, sinkMBB);
16107   MF->push_back(restoreMBB);
16108
16109   MachineInstrBuilder MIB;
16110
16111   // Transfer the remainder of BB and its successor edges to sinkMBB.
16112   sinkMBB->splice(sinkMBB->begin(), MBB,
16113                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16114   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16115
16116   // thisMBB:
16117   unsigned PtrStoreOpc = 0;
16118   unsigned LabelReg = 0;
16119   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16120   Reloc::Model RM = getTargetMachine().getRelocationModel();
16121   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16122                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16123
16124   // Prepare IP either in reg or imm.
16125   if (!UseImmLabel) {
16126     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16127     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16128     LabelReg = MRI.createVirtualRegister(PtrRC);
16129     if (Subtarget->is64Bit()) {
16130       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16131               .addReg(X86::RIP)
16132               .addImm(0)
16133               .addReg(0)
16134               .addMBB(restoreMBB)
16135               .addReg(0);
16136     } else {
16137       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16138       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16139               .addReg(XII->getGlobalBaseReg(MF))
16140               .addImm(0)
16141               .addReg(0)
16142               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16143               .addReg(0);
16144     }
16145   } else
16146     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16147   // Store IP
16148   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16149   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16150     if (i == X86::AddrDisp)
16151       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16152     else
16153       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16154   }
16155   if (!UseImmLabel)
16156     MIB.addReg(LabelReg);
16157   else
16158     MIB.addMBB(restoreMBB);
16159   MIB.setMemRefs(MMOBegin, MMOEnd);
16160   // Setup
16161   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16162           .addMBB(restoreMBB);
16163
16164   const X86RegisterInfo *RegInfo =
16165     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16166   MIB.addRegMask(RegInfo->getNoPreservedMask());
16167   thisMBB->addSuccessor(mainMBB);
16168   thisMBB->addSuccessor(restoreMBB);
16169
16170   // mainMBB:
16171   //  EAX = 0
16172   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16173   mainMBB->addSuccessor(sinkMBB);
16174
16175   // sinkMBB:
16176   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16177           TII->get(X86::PHI), DstReg)
16178     .addReg(mainDstReg).addMBB(mainMBB)
16179     .addReg(restoreDstReg).addMBB(restoreMBB);
16180
16181   // restoreMBB:
16182   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16183   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16184   restoreMBB->addSuccessor(sinkMBB);
16185
16186   MI->eraseFromParent();
16187   return sinkMBB;
16188 }
16189
16190 MachineBasicBlock *
16191 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16192                                      MachineBasicBlock *MBB) const {
16193   DebugLoc DL = MI->getDebugLoc();
16194   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16195
16196   MachineFunction *MF = MBB->getParent();
16197   MachineRegisterInfo &MRI = MF->getRegInfo();
16198
16199   // Memory Reference
16200   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16201   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16202
16203   MVT PVT = getPointerTy();
16204   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16205          "Invalid Pointer Size!");
16206
16207   const TargetRegisterClass *RC =
16208     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16209   unsigned Tmp = MRI.createVirtualRegister(RC);
16210   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16211   const X86RegisterInfo *RegInfo =
16212     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16213   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16214   unsigned SP = RegInfo->getStackRegister();
16215
16216   MachineInstrBuilder MIB;
16217
16218   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16219   const int64_t SPOffset = 2 * PVT.getStoreSize();
16220
16221   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16222   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16223
16224   // Reload FP
16225   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16226   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16227     MIB.addOperand(MI->getOperand(i));
16228   MIB.setMemRefs(MMOBegin, MMOEnd);
16229   // Reload IP
16230   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16231   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16232     if (i == X86::AddrDisp)
16233       MIB.addDisp(MI->getOperand(i), LabelOffset);
16234     else
16235       MIB.addOperand(MI->getOperand(i));
16236   }
16237   MIB.setMemRefs(MMOBegin, MMOEnd);
16238   // Reload SP
16239   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16240   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16241     if (i == X86::AddrDisp)
16242       MIB.addDisp(MI->getOperand(i), SPOffset);
16243     else
16244       MIB.addOperand(MI->getOperand(i));
16245   }
16246   MIB.setMemRefs(MMOBegin, MMOEnd);
16247   // Jump
16248   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16249
16250   MI->eraseFromParent();
16251   return MBB;
16252 }
16253
16254 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16255 // accumulator loops. Writing back to the accumulator allows the coalescer
16256 // to remove extra copies in the loop.   
16257 MachineBasicBlock *
16258 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16259                                  MachineBasicBlock *MBB) const {
16260   MachineOperand &AddendOp = MI->getOperand(3);
16261
16262   // Bail out early if the addend isn't a register - we can't switch these.
16263   if (!AddendOp.isReg())
16264     return MBB;
16265
16266   MachineFunction &MF = *MBB->getParent();
16267   MachineRegisterInfo &MRI = MF.getRegInfo();
16268
16269   // Check whether the addend is defined by a PHI:
16270   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16271   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16272   if (!AddendDef.isPHI())
16273     return MBB;
16274
16275   // Look for the following pattern:
16276   // loop:
16277   //   %addend = phi [%entry, 0], [%loop, %result]
16278   //   ...
16279   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16280
16281   // Replace with:
16282   //   loop:
16283   //   %addend = phi [%entry, 0], [%loop, %result]
16284   //   ...
16285   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16286
16287   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16288     assert(AddendDef.getOperand(i).isReg());
16289     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16290     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16291     if (&PHISrcInst == MI) {
16292       // Found a matching instruction.
16293       unsigned NewFMAOpc = 0;
16294       switch (MI->getOpcode()) {
16295         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16296         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16297         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16298         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16299         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16300         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16301         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16302         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16303         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16304         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16305         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16306         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16307         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16308         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16309         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16310         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16311         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16312         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16313         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16314         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16315         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16316         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16317         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16318         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16319         default: llvm_unreachable("Unrecognized FMA variant.");
16320       }
16321
16322       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16323       MachineInstrBuilder MIB =
16324         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16325         .addOperand(MI->getOperand(0))
16326         .addOperand(MI->getOperand(3))
16327         .addOperand(MI->getOperand(2))
16328         .addOperand(MI->getOperand(1));
16329       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16330       MI->eraseFromParent();
16331     }
16332   }
16333
16334   return MBB;
16335 }
16336
16337 MachineBasicBlock *
16338 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16339                                                MachineBasicBlock *BB) const {
16340   switch (MI->getOpcode()) {
16341   default: llvm_unreachable("Unexpected instr type to insert");
16342   case X86::TAILJMPd64:
16343   case X86::TAILJMPr64:
16344   case X86::TAILJMPm64:
16345     llvm_unreachable("TAILJMP64 would not be touched here.");
16346   case X86::TCRETURNdi64:
16347   case X86::TCRETURNri64:
16348   case X86::TCRETURNmi64:
16349     return BB;
16350   case X86::WIN_ALLOCA:
16351     return EmitLoweredWinAlloca(MI, BB);
16352   case X86::SEG_ALLOCA_32:
16353     return EmitLoweredSegAlloca(MI, BB, false);
16354   case X86::SEG_ALLOCA_64:
16355     return EmitLoweredSegAlloca(MI, BB, true);
16356   case X86::TLSCall_32:
16357   case X86::TLSCall_64:
16358     return EmitLoweredTLSCall(MI, BB);
16359   case X86::CMOV_GR8:
16360   case X86::CMOV_FR32:
16361   case X86::CMOV_FR64:
16362   case X86::CMOV_V4F32:
16363   case X86::CMOV_V2F64:
16364   case X86::CMOV_V2I64:
16365   case X86::CMOV_V8F32:
16366   case X86::CMOV_V4F64:
16367   case X86::CMOV_V4I64:
16368   case X86::CMOV_V16F32:
16369   case X86::CMOV_V8F64:
16370   case X86::CMOV_V8I64:
16371   case X86::CMOV_GR16:
16372   case X86::CMOV_GR32:
16373   case X86::CMOV_RFP32:
16374   case X86::CMOV_RFP64:
16375   case X86::CMOV_RFP80:
16376     return EmitLoweredSelect(MI, BB);
16377
16378   case X86::FP32_TO_INT16_IN_MEM:
16379   case X86::FP32_TO_INT32_IN_MEM:
16380   case X86::FP32_TO_INT64_IN_MEM:
16381   case X86::FP64_TO_INT16_IN_MEM:
16382   case X86::FP64_TO_INT32_IN_MEM:
16383   case X86::FP64_TO_INT64_IN_MEM:
16384   case X86::FP80_TO_INT16_IN_MEM:
16385   case X86::FP80_TO_INT32_IN_MEM:
16386   case X86::FP80_TO_INT64_IN_MEM: {
16387     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16388     DebugLoc DL = MI->getDebugLoc();
16389
16390     // Change the floating point control register to use "round towards zero"
16391     // mode when truncating to an integer value.
16392     MachineFunction *F = BB->getParent();
16393     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16394     addFrameReference(BuildMI(*BB, MI, DL,
16395                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16396
16397     // Load the old value of the high byte of the control word...
16398     unsigned OldCW =
16399       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16400     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16401                       CWFrameIdx);
16402
16403     // Set the high part to be round to zero...
16404     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16405       .addImm(0xC7F);
16406
16407     // Reload the modified control word now...
16408     addFrameReference(BuildMI(*BB, MI, DL,
16409                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16410
16411     // Restore the memory image of control word to original value
16412     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16413       .addReg(OldCW);
16414
16415     // Get the X86 opcode to use.
16416     unsigned Opc;
16417     switch (MI->getOpcode()) {
16418     default: llvm_unreachable("illegal opcode!");
16419     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16420     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16421     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16422     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16423     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16424     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16425     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16426     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16427     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16428     }
16429
16430     X86AddressMode AM;
16431     MachineOperand &Op = MI->getOperand(0);
16432     if (Op.isReg()) {
16433       AM.BaseType = X86AddressMode::RegBase;
16434       AM.Base.Reg = Op.getReg();
16435     } else {
16436       AM.BaseType = X86AddressMode::FrameIndexBase;
16437       AM.Base.FrameIndex = Op.getIndex();
16438     }
16439     Op = MI->getOperand(1);
16440     if (Op.isImm())
16441       AM.Scale = Op.getImm();
16442     Op = MI->getOperand(2);
16443     if (Op.isImm())
16444       AM.IndexReg = Op.getImm();
16445     Op = MI->getOperand(3);
16446     if (Op.isGlobal()) {
16447       AM.GV = Op.getGlobal();
16448     } else {
16449       AM.Disp = Op.getImm();
16450     }
16451     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16452                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16453
16454     // Reload the original control word now.
16455     addFrameReference(BuildMI(*BB, MI, DL,
16456                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16457
16458     MI->eraseFromParent();   // The pseudo instruction is gone now.
16459     return BB;
16460   }
16461     // String/text processing lowering.
16462   case X86::PCMPISTRM128REG:
16463   case X86::VPCMPISTRM128REG:
16464   case X86::PCMPISTRM128MEM:
16465   case X86::VPCMPISTRM128MEM:
16466   case X86::PCMPESTRM128REG:
16467   case X86::VPCMPESTRM128REG:
16468   case X86::PCMPESTRM128MEM:
16469   case X86::VPCMPESTRM128MEM:
16470     assert(Subtarget->hasSSE42() &&
16471            "Target must have SSE4.2 or AVX features enabled");
16472     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16473
16474   // String/text processing lowering.
16475   case X86::PCMPISTRIREG:
16476   case X86::VPCMPISTRIREG:
16477   case X86::PCMPISTRIMEM:
16478   case X86::VPCMPISTRIMEM:
16479   case X86::PCMPESTRIREG:
16480   case X86::VPCMPESTRIREG:
16481   case X86::PCMPESTRIMEM:
16482   case X86::VPCMPESTRIMEM:
16483     assert(Subtarget->hasSSE42() &&
16484            "Target must have SSE4.2 or AVX features enabled");
16485     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16486
16487   // Thread synchronization.
16488   case X86::MONITOR:
16489     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16490
16491   // xbegin
16492   case X86::XBEGIN:
16493     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16494
16495   // Atomic Lowering.
16496   case X86::ATOMAND8:
16497   case X86::ATOMAND16:
16498   case X86::ATOMAND32:
16499   case X86::ATOMAND64:
16500     // Fall through
16501   case X86::ATOMOR8:
16502   case X86::ATOMOR16:
16503   case X86::ATOMOR32:
16504   case X86::ATOMOR64:
16505     // Fall through
16506   case X86::ATOMXOR16:
16507   case X86::ATOMXOR8:
16508   case X86::ATOMXOR32:
16509   case X86::ATOMXOR64:
16510     // Fall through
16511   case X86::ATOMNAND8:
16512   case X86::ATOMNAND16:
16513   case X86::ATOMNAND32:
16514   case X86::ATOMNAND64:
16515     // Fall through
16516   case X86::ATOMMAX8:
16517   case X86::ATOMMAX16:
16518   case X86::ATOMMAX32:
16519   case X86::ATOMMAX64:
16520     // Fall through
16521   case X86::ATOMMIN8:
16522   case X86::ATOMMIN16:
16523   case X86::ATOMMIN32:
16524   case X86::ATOMMIN64:
16525     // Fall through
16526   case X86::ATOMUMAX8:
16527   case X86::ATOMUMAX16:
16528   case X86::ATOMUMAX32:
16529   case X86::ATOMUMAX64:
16530     // Fall through
16531   case X86::ATOMUMIN8:
16532   case X86::ATOMUMIN16:
16533   case X86::ATOMUMIN32:
16534   case X86::ATOMUMIN64:
16535     return EmitAtomicLoadArith(MI, BB);
16536
16537   // This group does 64-bit operations on a 32-bit host.
16538   case X86::ATOMAND6432:
16539   case X86::ATOMOR6432:
16540   case X86::ATOMXOR6432:
16541   case X86::ATOMNAND6432:
16542   case X86::ATOMADD6432:
16543   case X86::ATOMSUB6432:
16544   case X86::ATOMMAX6432:
16545   case X86::ATOMMIN6432:
16546   case X86::ATOMUMAX6432:
16547   case X86::ATOMUMIN6432:
16548   case X86::ATOMSWAP6432:
16549     return EmitAtomicLoadArith6432(MI, BB);
16550
16551   case X86::VASTART_SAVE_XMM_REGS:
16552     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16553
16554   case X86::VAARG_64:
16555     return EmitVAARG64WithCustomInserter(MI, BB);
16556
16557   case X86::EH_SjLj_SetJmp32:
16558   case X86::EH_SjLj_SetJmp64:
16559     return emitEHSjLjSetJmp(MI, BB);
16560
16561   case X86::EH_SjLj_LongJmp32:
16562   case X86::EH_SjLj_LongJmp64:
16563     return emitEHSjLjLongJmp(MI, BB);
16564
16565   case TargetOpcode::STACKMAP:
16566   case TargetOpcode::PATCHPOINT:
16567     return emitPatchPoint(MI, BB);
16568
16569   case X86::VFMADDPDr213r:
16570   case X86::VFMADDPSr213r:
16571   case X86::VFMADDSDr213r:
16572   case X86::VFMADDSSr213r:
16573   case X86::VFMSUBPDr213r:
16574   case X86::VFMSUBPSr213r:
16575   case X86::VFMSUBSDr213r:
16576   case X86::VFMSUBSSr213r:
16577   case X86::VFNMADDPDr213r:
16578   case X86::VFNMADDPSr213r:
16579   case X86::VFNMADDSDr213r:
16580   case X86::VFNMADDSSr213r:
16581   case X86::VFNMSUBPDr213r:
16582   case X86::VFNMSUBPSr213r:
16583   case X86::VFNMSUBSDr213r:
16584   case X86::VFNMSUBSSr213r:
16585   case X86::VFMADDPDr213rY:
16586   case X86::VFMADDPSr213rY:
16587   case X86::VFMSUBPDr213rY:
16588   case X86::VFMSUBPSr213rY:
16589   case X86::VFNMADDPDr213rY:
16590   case X86::VFNMADDPSr213rY:
16591   case X86::VFNMSUBPDr213rY:
16592   case X86::VFNMSUBPSr213rY:
16593     return emitFMA3Instr(MI, BB);
16594   }
16595 }
16596
16597 //===----------------------------------------------------------------------===//
16598 //                           X86 Optimization Hooks
16599 //===----------------------------------------------------------------------===//
16600
16601 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16602                                                        APInt &KnownZero,
16603                                                        APInt &KnownOne,
16604                                                        const SelectionDAG &DAG,
16605                                                        unsigned Depth) const {
16606   unsigned BitWidth = KnownZero.getBitWidth();
16607   unsigned Opc = Op.getOpcode();
16608   assert((Opc >= ISD::BUILTIN_OP_END ||
16609           Opc == ISD::INTRINSIC_WO_CHAIN ||
16610           Opc == ISD::INTRINSIC_W_CHAIN ||
16611           Opc == ISD::INTRINSIC_VOID) &&
16612          "Should use MaskedValueIsZero if you don't know whether Op"
16613          " is a target node!");
16614
16615   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16616   switch (Opc) {
16617   default: break;
16618   case X86ISD::ADD:
16619   case X86ISD::SUB:
16620   case X86ISD::ADC:
16621   case X86ISD::SBB:
16622   case X86ISD::SMUL:
16623   case X86ISD::UMUL:
16624   case X86ISD::INC:
16625   case X86ISD::DEC:
16626   case X86ISD::OR:
16627   case X86ISD::XOR:
16628   case X86ISD::AND:
16629     // These nodes' second result is a boolean.
16630     if (Op.getResNo() == 0)
16631       break;
16632     // Fallthrough
16633   case X86ISD::SETCC:
16634     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16635     break;
16636   case ISD::INTRINSIC_WO_CHAIN: {
16637     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16638     unsigned NumLoBits = 0;
16639     switch (IntId) {
16640     default: break;
16641     case Intrinsic::x86_sse_movmsk_ps:
16642     case Intrinsic::x86_avx_movmsk_ps_256:
16643     case Intrinsic::x86_sse2_movmsk_pd:
16644     case Intrinsic::x86_avx_movmsk_pd_256:
16645     case Intrinsic::x86_mmx_pmovmskb:
16646     case Intrinsic::x86_sse2_pmovmskb_128:
16647     case Intrinsic::x86_avx2_pmovmskb: {
16648       // High bits of movmskp{s|d}, pmovmskb are known zero.
16649       switch (IntId) {
16650         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16651         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16652         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16653         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16654         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16655         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16656         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16657         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16658       }
16659       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16660       break;
16661     }
16662     }
16663     break;
16664   }
16665   }
16666 }
16667
16668 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16669   SDValue Op,
16670   const SelectionDAG &,
16671   unsigned Depth) const {
16672   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16673   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16674     return Op.getValueType().getScalarType().getSizeInBits();
16675
16676   // Fallback case.
16677   return 1;
16678 }
16679
16680 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16681 /// node is a GlobalAddress + offset.
16682 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16683                                        const GlobalValue* &GA,
16684                                        int64_t &Offset) const {
16685   if (N->getOpcode() == X86ISD::Wrapper) {
16686     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16687       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16688       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16689       return true;
16690     }
16691   }
16692   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16693 }
16694
16695 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16696 /// same as extracting the high 128-bit part of 256-bit vector and then
16697 /// inserting the result into the low part of a new 256-bit vector
16698 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16699   EVT VT = SVOp->getValueType(0);
16700   unsigned NumElems = VT.getVectorNumElements();
16701
16702   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16703   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16704     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16705         SVOp->getMaskElt(j) >= 0)
16706       return false;
16707
16708   return true;
16709 }
16710
16711 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16712 /// same as extracting the low 128-bit part of 256-bit vector and then
16713 /// inserting the result into the high part of a new 256-bit vector
16714 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16715   EVT VT = SVOp->getValueType(0);
16716   unsigned NumElems = VT.getVectorNumElements();
16717
16718   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16719   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16720     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16721         SVOp->getMaskElt(j) >= 0)
16722       return false;
16723
16724   return true;
16725 }
16726
16727 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16728 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16729                                         TargetLowering::DAGCombinerInfo &DCI,
16730                                         const X86Subtarget* Subtarget) {
16731   SDLoc dl(N);
16732   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16733   SDValue V1 = SVOp->getOperand(0);
16734   SDValue V2 = SVOp->getOperand(1);
16735   EVT VT = SVOp->getValueType(0);
16736   unsigned NumElems = VT.getVectorNumElements();
16737
16738   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16739       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16740     //
16741     //                   0,0,0,...
16742     //                      |
16743     //    V      UNDEF    BUILD_VECTOR    UNDEF
16744     //     \      /           \           /
16745     //  CONCAT_VECTOR         CONCAT_VECTOR
16746     //         \                  /
16747     //          \                /
16748     //          RESULT: V + zero extended
16749     //
16750     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16751         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16752         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16753       return SDValue();
16754
16755     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16756       return SDValue();
16757
16758     // To match the shuffle mask, the first half of the mask should
16759     // be exactly the first vector, and all the rest a splat with the
16760     // first element of the second one.
16761     for (unsigned i = 0; i != NumElems/2; ++i)
16762       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16763           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16764         return SDValue();
16765
16766     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16767     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16768       if (Ld->hasNUsesOfValue(1, 0)) {
16769         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16770         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16771         SDValue ResNode =
16772           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16773                                   array_lengthof(Ops),
16774                                   Ld->getMemoryVT(),
16775                                   Ld->getPointerInfo(),
16776                                   Ld->getAlignment(),
16777                                   false/*isVolatile*/, true/*ReadMem*/,
16778                                   false/*WriteMem*/);
16779
16780         // Make sure the newly-created LOAD is in the same position as Ld in
16781         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16782         // and update uses of Ld's output chain to use the TokenFactor.
16783         if (Ld->hasAnyUseOfValue(1)) {
16784           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16785                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16786           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16787           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16788                                  SDValue(ResNode.getNode(), 1));
16789         }
16790
16791         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16792       }
16793     }
16794
16795     // Emit a zeroed vector and insert the desired subvector on its
16796     // first half.
16797     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16798     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16799     return DCI.CombineTo(N, InsV);
16800   }
16801
16802   //===--------------------------------------------------------------------===//
16803   // Combine some shuffles into subvector extracts and inserts:
16804   //
16805
16806   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16807   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16808     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16809     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16810     return DCI.CombineTo(N, InsV);
16811   }
16812
16813   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16814   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16815     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16816     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16817     return DCI.CombineTo(N, InsV);
16818   }
16819
16820   return SDValue();
16821 }
16822
16823 /// PerformShuffleCombine - Performs several different shuffle combines.
16824 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16825                                      TargetLowering::DAGCombinerInfo &DCI,
16826                                      const X86Subtarget *Subtarget) {
16827   SDLoc dl(N);
16828   EVT VT = N->getValueType(0);
16829
16830   // Don't create instructions with illegal types after legalize types has run.
16831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16832   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16833     return SDValue();
16834
16835   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16836   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16837       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16838     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16839
16840   // Only handle 128 wide vector from here on.
16841   if (!VT.is128BitVector())
16842     return SDValue();
16843
16844   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16845   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16846   // consecutive, non-overlapping, and in the right order.
16847   SmallVector<SDValue, 16> Elts;
16848   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16849     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16850
16851   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16852 }
16853
16854 /// PerformTruncateCombine - Converts truncate operation to
16855 /// a sequence of vector shuffle operations.
16856 /// It is possible when we truncate 256-bit vector to 128-bit vector
16857 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16858                                       TargetLowering::DAGCombinerInfo &DCI,
16859                                       const X86Subtarget *Subtarget)  {
16860   return SDValue();
16861 }
16862
16863 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16864 /// specific shuffle of a load can be folded into a single element load.
16865 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16866 /// shuffles have been customed lowered so we need to handle those here.
16867 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16868                                          TargetLowering::DAGCombinerInfo &DCI) {
16869   if (DCI.isBeforeLegalizeOps())
16870     return SDValue();
16871
16872   SDValue InVec = N->getOperand(0);
16873   SDValue EltNo = N->getOperand(1);
16874
16875   if (!isa<ConstantSDNode>(EltNo))
16876     return SDValue();
16877
16878   EVT VT = InVec.getValueType();
16879
16880   bool HasShuffleIntoBitcast = false;
16881   if (InVec.getOpcode() == ISD::BITCAST) {
16882     // Don't duplicate a load with other uses.
16883     if (!InVec.hasOneUse())
16884       return SDValue();
16885     EVT BCVT = InVec.getOperand(0).getValueType();
16886     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16887       return SDValue();
16888     InVec = InVec.getOperand(0);
16889     HasShuffleIntoBitcast = true;
16890   }
16891
16892   if (!isTargetShuffle(InVec.getOpcode()))
16893     return SDValue();
16894
16895   // Don't duplicate a load with other uses.
16896   if (!InVec.hasOneUse())
16897     return SDValue();
16898
16899   SmallVector<int, 16> ShuffleMask;
16900   bool UnaryShuffle;
16901   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16902                             UnaryShuffle))
16903     return SDValue();
16904
16905   // Select the input vector, guarding against out of range extract vector.
16906   unsigned NumElems = VT.getVectorNumElements();
16907   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16908   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16909   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16910                                          : InVec.getOperand(1);
16911
16912   // If inputs to shuffle are the same for both ops, then allow 2 uses
16913   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16914
16915   if (LdNode.getOpcode() == ISD::BITCAST) {
16916     // Don't duplicate a load with other uses.
16917     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16918       return SDValue();
16919
16920     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16921     LdNode = LdNode.getOperand(0);
16922   }
16923
16924   if (!ISD::isNormalLoad(LdNode.getNode()))
16925     return SDValue();
16926
16927   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16928
16929   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16930     return SDValue();
16931
16932   if (HasShuffleIntoBitcast) {
16933     // If there's a bitcast before the shuffle, check if the load type and
16934     // alignment is valid.
16935     unsigned Align = LN0->getAlignment();
16936     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16937     unsigned NewAlign = TLI.getDataLayout()->
16938       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16939
16940     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16941       return SDValue();
16942   }
16943
16944   // All checks match so transform back to vector_shuffle so that DAG combiner
16945   // can finish the job
16946   SDLoc dl(N);
16947
16948   // Create shuffle node taking into account the case that its a unary shuffle
16949   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16950   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16951                                  InVec.getOperand(0), Shuffle,
16952                                  &ShuffleMask[0]);
16953   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16954   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16955                      EltNo);
16956 }
16957
16958 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16959 /// generation and convert it from being a bunch of shuffles and extracts
16960 /// to a simple store and scalar loads to extract the elements.
16961 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16962                                          TargetLowering::DAGCombinerInfo &DCI) {
16963   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16964   if (NewOp.getNode())
16965     return NewOp;
16966
16967   SDValue InputVector = N->getOperand(0);
16968
16969   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16970   // from mmx to v2i32 has a single usage.
16971   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16972       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16973       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16974     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16975                        N->getValueType(0),
16976                        InputVector.getNode()->getOperand(0));
16977
16978   // Only operate on vectors of 4 elements, where the alternative shuffling
16979   // gets to be more expensive.
16980   if (InputVector.getValueType() != MVT::v4i32)
16981     return SDValue();
16982
16983   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16984   // single use which is a sign-extend or zero-extend, and all elements are
16985   // used.
16986   SmallVector<SDNode *, 4> Uses;
16987   unsigned ExtractedElements = 0;
16988   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16989        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16990     if (UI.getUse().getResNo() != InputVector.getResNo())
16991       return SDValue();
16992
16993     SDNode *Extract = *UI;
16994     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16995       return SDValue();
16996
16997     if (Extract->getValueType(0) != MVT::i32)
16998       return SDValue();
16999     if (!Extract->hasOneUse())
17000       return SDValue();
17001     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17002         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17003       return SDValue();
17004     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17005       return SDValue();
17006
17007     // Record which element was extracted.
17008     ExtractedElements |=
17009       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17010
17011     Uses.push_back(Extract);
17012   }
17013
17014   // If not all the elements were used, this may not be worthwhile.
17015   if (ExtractedElements != 15)
17016     return SDValue();
17017
17018   // Ok, we've now decided to do the transformation.
17019   SDLoc dl(InputVector);
17020
17021   // Store the value to a temporary stack slot.
17022   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17023   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17024                             MachinePointerInfo(), false, false, 0);
17025
17026   // Replace each use (extract) with a load of the appropriate element.
17027   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17028        UE = Uses.end(); UI != UE; ++UI) {
17029     SDNode *Extract = *UI;
17030
17031     // cOMpute the element's address.
17032     SDValue Idx = Extract->getOperand(1);
17033     unsigned EltSize =
17034         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17035     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17036     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17037     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17038
17039     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17040                                      StackPtr, OffsetVal);
17041
17042     // Load the scalar.
17043     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17044                                      ScalarAddr, MachinePointerInfo(),
17045                                      false, false, false, 0);
17046
17047     // Replace the exact with the load.
17048     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17049   }
17050
17051   // The replacement was made in place; don't return anything.
17052   return SDValue();
17053 }
17054
17055 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17056 static std::pair<unsigned, bool>
17057 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17058                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17059   if (!VT.isVector())
17060     return std::make_pair(0, false);
17061
17062   bool NeedSplit = false;
17063   switch (VT.getSimpleVT().SimpleTy) {
17064   default: return std::make_pair(0, false);
17065   case MVT::v32i8:
17066   case MVT::v16i16:
17067   case MVT::v8i32:
17068     if (!Subtarget->hasAVX2())
17069       NeedSplit = true;
17070     if (!Subtarget->hasAVX())
17071       return std::make_pair(0, false);
17072     break;
17073   case MVT::v16i8:
17074   case MVT::v8i16:
17075   case MVT::v4i32:
17076     if (!Subtarget->hasSSE2())
17077       return std::make_pair(0, false);
17078   }
17079
17080   // SSE2 has only a small subset of the operations.
17081   bool hasUnsigned = Subtarget->hasSSE41() ||
17082                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17083   bool hasSigned = Subtarget->hasSSE41() ||
17084                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17085
17086   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17087
17088   unsigned Opc = 0;
17089   // Check for x CC y ? x : y.
17090   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17091       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17092     switch (CC) {
17093     default: break;
17094     case ISD::SETULT:
17095     case ISD::SETULE:
17096       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17097     case ISD::SETUGT:
17098     case ISD::SETUGE:
17099       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17100     case ISD::SETLT:
17101     case ISD::SETLE:
17102       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17103     case ISD::SETGT:
17104     case ISD::SETGE:
17105       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17106     }
17107   // Check for x CC y ? y : x -- a min/max with reversed arms.
17108   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17109              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17110     switch (CC) {
17111     default: break;
17112     case ISD::SETULT:
17113     case ISD::SETULE:
17114       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17115     case ISD::SETUGT:
17116     case ISD::SETUGE:
17117       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17118     case ISD::SETLT:
17119     case ISD::SETLE:
17120       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17121     case ISD::SETGT:
17122     case ISD::SETGE:
17123       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17124     }
17125   }
17126
17127   return std::make_pair(Opc, NeedSplit);
17128 }
17129
17130 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17131 /// nodes.
17132 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17133                                     TargetLowering::DAGCombinerInfo &DCI,
17134                                     const X86Subtarget *Subtarget) {
17135   SDLoc DL(N);
17136   SDValue Cond = N->getOperand(0);
17137   // Get the LHS/RHS of the select.
17138   SDValue LHS = N->getOperand(1);
17139   SDValue RHS = N->getOperand(2);
17140   EVT VT = LHS.getValueType();
17141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17142
17143   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17144   // instructions match the semantics of the common C idiom x<y?x:y but not
17145   // x<=y?x:y, because of how they handle negative zero (which can be
17146   // ignored in unsafe-math mode).
17147   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17148       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17149       (Subtarget->hasSSE2() ||
17150        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17151     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17152
17153     unsigned Opcode = 0;
17154     // Check for x CC y ? x : y.
17155     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17156         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17157       switch (CC) {
17158       default: break;
17159       case ISD::SETULT:
17160         // Converting this to a min would handle NaNs incorrectly, and swapping
17161         // the operands would cause it to handle comparisons between positive
17162         // and negative zero incorrectly.
17163         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17164           if (!DAG.getTarget().Options.UnsafeFPMath &&
17165               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17166             break;
17167           std::swap(LHS, RHS);
17168         }
17169         Opcode = X86ISD::FMIN;
17170         break;
17171       case ISD::SETOLE:
17172         // Converting this to a min would handle comparisons between positive
17173         // and negative zero incorrectly.
17174         if (!DAG.getTarget().Options.UnsafeFPMath &&
17175             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17176           break;
17177         Opcode = X86ISD::FMIN;
17178         break;
17179       case ISD::SETULE:
17180         // Converting this to a min would handle both negative zeros and NaNs
17181         // incorrectly, but we can swap the operands to fix both.
17182         std::swap(LHS, RHS);
17183       case ISD::SETOLT:
17184       case ISD::SETLT:
17185       case ISD::SETLE:
17186         Opcode = X86ISD::FMIN;
17187         break;
17188
17189       case ISD::SETOGE:
17190         // Converting this to a max would handle comparisons between positive
17191         // and negative zero incorrectly.
17192         if (!DAG.getTarget().Options.UnsafeFPMath &&
17193             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17194           break;
17195         Opcode = X86ISD::FMAX;
17196         break;
17197       case ISD::SETUGT:
17198         // Converting this to a max would handle NaNs incorrectly, and swapping
17199         // the operands would cause it to handle comparisons between positive
17200         // and negative zero incorrectly.
17201         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17202           if (!DAG.getTarget().Options.UnsafeFPMath &&
17203               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17204             break;
17205           std::swap(LHS, RHS);
17206         }
17207         Opcode = X86ISD::FMAX;
17208         break;
17209       case ISD::SETUGE:
17210         // Converting this to a max would handle both negative zeros and NaNs
17211         // incorrectly, but we can swap the operands to fix both.
17212         std::swap(LHS, RHS);
17213       case ISD::SETOGT:
17214       case ISD::SETGT:
17215       case ISD::SETGE:
17216         Opcode = X86ISD::FMAX;
17217         break;
17218       }
17219     // Check for x CC y ? y : x -- a min/max with reversed arms.
17220     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17221                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17222       switch (CC) {
17223       default: break;
17224       case ISD::SETOGE:
17225         // Converting this to a min would handle comparisons between positive
17226         // and negative zero incorrectly, and swapping the operands would
17227         // cause it to handle NaNs incorrectly.
17228         if (!DAG.getTarget().Options.UnsafeFPMath &&
17229             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17230           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17231             break;
17232           std::swap(LHS, RHS);
17233         }
17234         Opcode = X86ISD::FMIN;
17235         break;
17236       case ISD::SETUGT:
17237         // Converting this to a min would handle NaNs incorrectly.
17238         if (!DAG.getTarget().Options.UnsafeFPMath &&
17239             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17240           break;
17241         Opcode = X86ISD::FMIN;
17242         break;
17243       case ISD::SETUGE:
17244         // Converting this to a min would handle both negative zeros and NaNs
17245         // incorrectly, but we can swap the operands to fix both.
17246         std::swap(LHS, RHS);
17247       case ISD::SETOGT:
17248       case ISD::SETGT:
17249       case ISD::SETGE:
17250         Opcode = X86ISD::FMIN;
17251         break;
17252
17253       case ISD::SETULT:
17254         // Converting this to a max would handle NaNs incorrectly.
17255         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17256           break;
17257         Opcode = X86ISD::FMAX;
17258         break;
17259       case ISD::SETOLE:
17260         // Converting this to a max would handle comparisons between positive
17261         // and negative zero incorrectly, and swapping the operands would
17262         // cause it to handle NaNs incorrectly.
17263         if (!DAG.getTarget().Options.UnsafeFPMath &&
17264             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17265           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17266             break;
17267           std::swap(LHS, RHS);
17268         }
17269         Opcode = X86ISD::FMAX;
17270         break;
17271       case ISD::SETULE:
17272         // Converting this to a max would handle both negative zeros and NaNs
17273         // incorrectly, but we can swap the operands to fix both.
17274         std::swap(LHS, RHS);
17275       case ISD::SETOLT:
17276       case ISD::SETLT:
17277       case ISD::SETLE:
17278         Opcode = X86ISD::FMAX;
17279         break;
17280       }
17281     }
17282
17283     if (Opcode)
17284       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17285   }
17286
17287   EVT CondVT = Cond.getValueType();
17288   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17289       CondVT.getVectorElementType() == MVT::i1) {
17290     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17291     // lowering on AVX-512. In this case we convert it to
17292     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17293     // The same situation for all 128 and 256-bit vectors of i8 and i16
17294     EVT OpVT = LHS.getValueType();
17295     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17296         (OpVT.getVectorElementType() == MVT::i8 ||
17297          OpVT.getVectorElementType() == MVT::i16)) {
17298       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17299       DCI.AddToWorklist(Cond.getNode());
17300       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17301     }
17302   }
17303   // If this is a select between two integer constants, try to do some
17304   // optimizations.
17305   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17306     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17307       // Don't do this for crazy integer types.
17308       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17309         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17310         // so that TrueC (the true value) is larger than FalseC.
17311         bool NeedsCondInvert = false;
17312
17313         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17314             // Efficiently invertible.
17315             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17316              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17317               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17318           NeedsCondInvert = true;
17319           std::swap(TrueC, FalseC);
17320         }
17321
17322         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17323         if (FalseC->getAPIntValue() == 0 &&
17324             TrueC->getAPIntValue().isPowerOf2()) {
17325           if (NeedsCondInvert) // Invert the condition if needed.
17326             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17327                                DAG.getConstant(1, Cond.getValueType()));
17328
17329           // Zero extend the condition if needed.
17330           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17331
17332           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17333           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17334                              DAG.getConstant(ShAmt, MVT::i8));
17335         }
17336
17337         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17338         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17339           if (NeedsCondInvert) // Invert the condition if needed.
17340             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17341                                DAG.getConstant(1, Cond.getValueType()));
17342
17343           // Zero extend the condition if needed.
17344           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17345                              FalseC->getValueType(0), Cond);
17346           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17347                              SDValue(FalseC, 0));
17348         }
17349
17350         // Optimize cases that will turn into an LEA instruction.  This requires
17351         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17352         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17353           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17354           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17355
17356           bool isFastMultiplier = false;
17357           if (Diff < 10) {
17358             switch ((unsigned char)Diff) {
17359               default: break;
17360               case 1:  // result = add base, cond
17361               case 2:  // result = lea base(    , cond*2)
17362               case 3:  // result = lea base(cond, cond*2)
17363               case 4:  // result = lea base(    , cond*4)
17364               case 5:  // result = lea base(cond, cond*4)
17365               case 8:  // result = lea base(    , cond*8)
17366               case 9:  // result = lea base(cond, cond*8)
17367                 isFastMultiplier = true;
17368                 break;
17369             }
17370           }
17371
17372           if (isFastMultiplier) {
17373             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17374             if (NeedsCondInvert) // Invert the condition if needed.
17375               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17376                                  DAG.getConstant(1, Cond.getValueType()));
17377
17378             // Zero extend the condition if needed.
17379             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17380                                Cond);
17381             // Scale the condition by the difference.
17382             if (Diff != 1)
17383               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17384                                  DAG.getConstant(Diff, Cond.getValueType()));
17385
17386             // Add the base if non-zero.
17387             if (FalseC->getAPIntValue() != 0)
17388               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17389                                  SDValue(FalseC, 0));
17390             return Cond;
17391           }
17392         }
17393       }
17394   }
17395
17396   // Canonicalize max and min:
17397   // (x > y) ? x : y -> (x >= y) ? x : y
17398   // (x < y) ? x : y -> (x <= y) ? x : y
17399   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17400   // the need for an extra compare
17401   // against zero. e.g.
17402   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17403   // subl   %esi, %edi
17404   // testl  %edi, %edi
17405   // movl   $0, %eax
17406   // cmovgl %edi, %eax
17407   // =>
17408   // xorl   %eax, %eax
17409   // subl   %esi, $edi
17410   // cmovsl %eax, %edi
17411   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17412       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17413       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17414     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17415     switch (CC) {
17416     default: break;
17417     case ISD::SETLT:
17418     case ISD::SETGT: {
17419       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17420       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17421                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17422       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17423     }
17424     }
17425   }
17426
17427   // Early exit check
17428   if (!TLI.isTypeLegal(VT))
17429     return SDValue();
17430
17431   // Match VSELECTs into subs with unsigned saturation.
17432   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17433       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17434       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17435        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17436     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17437
17438     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17439     // left side invert the predicate to simplify logic below.
17440     SDValue Other;
17441     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17442       Other = RHS;
17443       CC = ISD::getSetCCInverse(CC, true);
17444     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17445       Other = LHS;
17446     }
17447
17448     if (Other.getNode() && Other->getNumOperands() == 2 &&
17449         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17450       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17451       SDValue CondRHS = Cond->getOperand(1);
17452
17453       // Look for a general sub with unsigned saturation first.
17454       // x >= y ? x-y : 0 --> subus x, y
17455       // x >  y ? x-y : 0 --> subus x, y
17456       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17457           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17458         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17459
17460       // If the RHS is a constant we have to reverse the const canonicalization.
17461       // x > C-1 ? x+-C : 0 --> subus x, C
17462       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17463           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17464         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17465         if (CondRHS.getConstantOperandVal(0) == -A-1)
17466           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17467                              DAG.getConstant(-A, VT));
17468       }
17469
17470       // Another special case: If C was a sign bit, the sub has been
17471       // canonicalized into a xor.
17472       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17473       //        it's safe to decanonicalize the xor?
17474       // x s< 0 ? x^C : 0 --> subus x, C
17475       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17476           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17477           isSplatVector(OpRHS.getNode())) {
17478         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17479         if (A.isSignBit())
17480           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17481       }
17482     }
17483   }
17484
17485   // Try to match a min/max vector operation.
17486   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17487     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17488     unsigned Opc = ret.first;
17489     bool NeedSplit = ret.second;
17490
17491     if (Opc && NeedSplit) {
17492       unsigned NumElems = VT.getVectorNumElements();
17493       // Extract the LHS vectors
17494       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17495       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17496
17497       // Extract the RHS vectors
17498       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17499       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17500
17501       // Create min/max for each subvector
17502       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17503       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17504
17505       // Merge the result
17506       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17507     } else if (Opc)
17508       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17509   }
17510
17511   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17512   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17513       // Check if SETCC has already been promoted
17514       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17515       // Check that condition value type matches vselect operand type
17516       CondVT == VT) { 
17517
17518     assert(Cond.getValueType().isVector() &&
17519            "vector select expects a vector selector!");
17520
17521     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17522     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17523
17524     if (!TValIsAllOnes && !FValIsAllZeros) {
17525       // Try invert the condition if true value is not all 1s and false value
17526       // is not all 0s.
17527       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17528       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17529
17530       if (TValIsAllZeros || FValIsAllOnes) {
17531         SDValue CC = Cond.getOperand(2);
17532         ISD::CondCode NewCC =
17533           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17534                                Cond.getOperand(0).getValueType().isInteger());
17535         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17536         std::swap(LHS, RHS);
17537         TValIsAllOnes = FValIsAllOnes;
17538         FValIsAllZeros = TValIsAllZeros;
17539       }
17540     }
17541
17542     if (TValIsAllOnes || FValIsAllZeros) {
17543       SDValue Ret;
17544
17545       if (TValIsAllOnes && FValIsAllZeros)
17546         Ret = Cond;
17547       else if (TValIsAllOnes)
17548         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17549                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17550       else if (FValIsAllZeros)
17551         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17552                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17553
17554       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17555     }
17556   }
17557
17558   // Try to fold this VSELECT into a MOVSS/MOVSD
17559   if (N->getOpcode() == ISD::VSELECT &&
17560       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17561     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17562         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17563       bool CanFold = false;
17564       unsigned NumElems = Cond.getNumOperands();
17565       SDValue A = LHS;
17566       SDValue B = RHS;
17567       
17568       if (isZero(Cond.getOperand(0))) {
17569         CanFold = true;
17570
17571         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17572         // fold (vselect <0,-1> -> (movsd A, B)
17573         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17574           CanFold = isAllOnes(Cond.getOperand(i));
17575       } else if (isAllOnes(Cond.getOperand(0))) {
17576         CanFold = true;
17577         std::swap(A, B);
17578
17579         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17580         // fold (vselect <-1,0> -> (movsd B, A)
17581         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17582           CanFold = isZero(Cond.getOperand(i));
17583       }
17584
17585       if (CanFold) {
17586         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17587           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17588         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17589       }
17590
17591       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17592         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17593         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17594         //                             (v2i64 (bitcast B)))))
17595         //
17596         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17597         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17598         //                             (v2f64 (bitcast B)))))
17599         //
17600         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17601         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17602         //                             (v2i64 (bitcast A)))))
17603         //
17604         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17605         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17606         //                             (v2f64 (bitcast A)))))
17607
17608         CanFold = (isZero(Cond.getOperand(0)) &&
17609                    isZero(Cond.getOperand(1)) &&
17610                    isAllOnes(Cond.getOperand(2)) &&
17611                    isAllOnes(Cond.getOperand(3)));
17612
17613         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17614             isAllOnes(Cond.getOperand(1)) &&
17615             isZero(Cond.getOperand(2)) &&
17616             isZero(Cond.getOperand(3))) {
17617           CanFold = true;
17618           std::swap(LHS, RHS);
17619         }
17620
17621         if (CanFold) {
17622           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17623           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17624           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17625           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17626                                                 NewB, DAG);
17627           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17628         }
17629       }
17630     }
17631   }
17632
17633   // If we know that this node is legal then we know that it is going to be
17634   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17635   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17636   // to simplify previous instructions.
17637   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17638       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17639     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17640
17641     // Don't optimize vector selects that map to mask-registers.
17642     if (BitWidth == 1)
17643       return SDValue();
17644
17645     // Check all uses of that condition operand to check whether it will be
17646     // consumed by non-BLEND instructions, which may depend on all bits are set
17647     // properly.
17648     for (SDNode::use_iterator I = Cond->use_begin(),
17649                               E = Cond->use_end(); I != E; ++I)
17650       if (I->getOpcode() != ISD::VSELECT)
17651         // TODO: Add other opcodes eventually lowered into BLEND.
17652         return SDValue();
17653
17654     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17655     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17656
17657     APInt KnownZero, KnownOne;
17658     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17659                                           DCI.isBeforeLegalizeOps());
17660     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17661         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17662       DCI.CommitTargetLoweringOpt(TLO);
17663   }
17664
17665   return SDValue();
17666 }
17667
17668 // Check whether a boolean test is testing a boolean value generated by
17669 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17670 // code.
17671 //
17672 // Simplify the following patterns:
17673 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17674 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17675 // to (Op EFLAGS Cond)
17676 //
17677 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17678 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17679 // to (Op EFLAGS !Cond)
17680 //
17681 // where Op could be BRCOND or CMOV.
17682 //
17683 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17684   // Quit if not CMP and SUB with its value result used.
17685   if (Cmp.getOpcode() != X86ISD::CMP &&
17686       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17687       return SDValue();
17688
17689   // Quit if not used as a boolean value.
17690   if (CC != X86::COND_E && CC != X86::COND_NE)
17691     return SDValue();
17692
17693   // Check CMP operands. One of them should be 0 or 1 and the other should be
17694   // an SetCC or extended from it.
17695   SDValue Op1 = Cmp.getOperand(0);
17696   SDValue Op2 = Cmp.getOperand(1);
17697
17698   SDValue SetCC;
17699   const ConstantSDNode* C = 0;
17700   bool needOppositeCond = (CC == X86::COND_E);
17701   bool checkAgainstTrue = false; // Is it a comparison against 1?
17702
17703   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17704     SetCC = Op2;
17705   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17706     SetCC = Op1;
17707   else // Quit if all operands are not constants.
17708     return SDValue();
17709
17710   if (C->getZExtValue() == 1) {
17711     needOppositeCond = !needOppositeCond;
17712     checkAgainstTrue = true;
17713   } else if (C->getZExtValue() != 0)
17714     // Quit if the constant is neither 0 or 1.
17715     return SDValue();
17716
17717   bool truncatedToBoolWithAnd = false;
17718   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17719   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17720          SetCC.getOpcode() == ISD::TRUNCATE ||
17721          SetCC.getOpcode() == ISD::AND) {
17722     if (SetCC.getOpcode() == ISD::AND) {
17723       int OpIdx = -1;
17724       ConstantSDNode *CS;
17725       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17726           CS->getZExtValue() == 1)
17727         OpIdx = 1;
17728       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17729           CS->getZExtValue() == 1)
17730         OpIdx = 0;
17731       if (OpIdx == -1)
17732         break;
17733       SetCC = SetCC.getOperand(OpIdx);
17734       truncatedToBoolWithAnd = true;
17735     } else
17736       SetCC = SetCC.getOperand(0);
17737   }
17738
17739   switch (SetCC.getOpcode()) {
17740   case X86ISD::SETCC_CARRY:
17741     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17742     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17743     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17744     // truncated to i1 using 'and'.
17745     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17746       break;
17747     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17748            "Invalid use of SETCC_CARRY!");
17749     // FALL THROUGH
17750   case X86ISD::SETCC:
17751     // Set the condition code or opposite one if necessary.
17752     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17753     if (needOppositeCond)
17754       CC = X86::GetOppositeBranchCondition(CC);
17755     return SetCC.getOperand(1);
17756   case X86ISD::CMOV: {
17757     // Check whether false/true value has canonical one, i.e. 0 or 1.
17758     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17759     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17760     // Quit if true value is not a constant.
17761     if (!TVal)
17762       return SDValue();
17763     // Quit if false value is not a constant.
17764     if (!FVal) {
17765       SDValue Op = SetCC.getOperand(0);
17766       // Skip 'zext' or 'trunc' node.
17767       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17768           Op.getOpcode() == ISD::TRUNCATE)
17769         Op = Op.getOperand(0);
17770       // A special case for rdrand/rdseed, where 0 is set if false cond is
17771       // found.
17772       if ((Op.getOpcode() != X86ISD::RDRAND &&
17773            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17774         return SDValue();
17775     }
17776     // Quit if false value is not the constant 0 or 1.
17777     bool FValIsFalse = true;
17778     if (FVal && FVal->getZExtValue() != 0) {
17779       if (FVal->getZExtValue() != 1)
17780         return SDValue();
17781       // If FVal is 1, opposite cond is needed.
17782       needOppositeCond = !needOppositeCond;
17783       FValIsFalse = false;
17784     }
17785     // Quit if TVal is not the constant opposite of FVal.
17786     if (FValIsFalse && TVal->getZExtValue() != 1)
17787       return SDValue();
17788     if (!FValIsFalse && TVal->getZExtValue() != 0)
17789       return SDValue();
17790     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17791     if (needOppositeCond)
17792       CC = X86::GetOppositeBranchCondition(CC);
17793     return SetCC.getOperand(3);
17794   }
17795   }
17796
17797   return SDValue();
17798 }
17799
17800 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17801 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17802                                   TargetLowering::DAGCombinerInfo &DCI,
17803                                   const X86Subtarget *Subtarget) {
17804   SDLoc DL(N);
17805
17806   // If the flag operand isn't dead, don't touch this CMOV.
17807   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17808     return SDValue();
17809
17810   SDValue FalseOp = N->getOperand(0);
17811   SDValue TrueOp = N->getOperand(1);
17812   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17813   SDValue Cond = N->getOperand(3);
17814
17815   if (CC == X86::COND_E || CC == X86::COND_NE) {
17816     switch (Cond.getOpcode()) {
17817     default: break;
17818     case X86ISD::BSR:
17819     case X86ISD::BSF:
17820       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17821       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17822         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17823     }
17824   }
17825
17826   SDValue Flags;
17827
17828   Flags = checkBoolTestSetCCCombine(Cond, CC);
17829   if (Flags.getNode() &&
17830       // Extra check as FCMOV only supports a subset of X86 cond.
17831       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17832     SDValue Ops[] = { FalseOp, TrueOp,
17833                       DAG.getConstant(CC, MVT::i8), Flags };
17834     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17835                        Ops, array_lengthof(Ops));
17836   }
17837
17838   // If this is a select between two integer constants, try to do some
17839   // optimizations.  Note that the operands are ordered the opposite of SELECT
17840   // operands.
17841   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17842     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17843       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17844       // larger than FalseC (the false value).
17845       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17846         CC = X86::GetOppositeBranchCondition(CC);
17847         std::swap(TrueC, FalseC);
17848         std::swap(TrueOp, FalseOp);
17849       }
17850
17851       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17852       // This is efficient for any integer data type (including i8/i16) and
17853       // shift amount.
17854       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17855         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17856                            DAG.getConstant(CC, MVT::i8), Cond);
17857
17858         // Zero extend the condition if needed.
17859         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17860
17861         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17862         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17863                            DAG.getConstant(ShAmt, MVT::i8));
17864         if (N->getNumValues() == 2)  // Dead flag value?
17865           return DCI.CombineTo(N, Cond, SDValue());
17866         return Cond;
17867       }
17868
17869       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17870       // for any integer data type, including i8/i16.
17871       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17872         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17873                            DAG.getConstant(CC, MVT::i8), Cond);
17874
17875         // Zero extend the condition if needed.
17876         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17877                            FalseC->getValueType(0), Cond);
17878         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17879                            SDValue(FalseC, 0));
17880
17881         if (N->getNumValues() == 2)  // Dead flag value?
17882           return DCI.CombineTo(N, Cond, SDValue());
17883         return Cond;
17884       }
17885
17886       // Optimize cases that will turn into an LEA instruction.  This requires
17887       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17888       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17889         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17890         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17891
17892         bool isFastMultiplier = false;
17893         if (Diff < 10) {
17894           switch ((unsigned char)Diff) {
17895           default: break;
17896           case 1:  // result = add base, cond
17897           case 2:  // result = lea base(    , cond*2)
17898           case 3:  // result = lea base(cond, cond*2)
17899           case 4:  // result = lea base(    , cond*4)
17900           case 5:  // result = lea base(cond, cond*4)
17901           case 8:  // result = lea base(    , cond*8)
17902           case 9:  // result = lea base(cond, cond*8)
17903             isFastMultiplier = true;
17904             break;
17905           }
17906         }
17907
17908         if (isFastMultiplier) {
17909           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17910           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17911                              DAG.getConstant(CC, MVT::i8), Cond);
17912           // Zero extend the condition if needed.
17913           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17914                              Cond);
17915           // Scale the condition by the difference.
17916           if (Diff != 1)
17917             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17918                                DAG.getConstant(Diff, Cond.getValueType()));
17919
17920           // Add the base if non-zero.
17921           if (FalseC->getAPIntValue() != 0)
17922             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17923                                SDValue(FalseC, 0));
17924           if (N->getNumValues() == 2)  // Dead flag value?
17925             return DCI.CombineTo(N, Cond, SDValue());
17926           return Cond;
17927         }
17928       }
17929     }
17930   }
17931
17932   // Handle these cases:
17933   //   (select (x != c), e, c) -> select (x != c), e, x),
17934   //   (select (x == c), c, e) -> select (x == c), x, e)
17935   // where the c is an integer constant, and the "select" is the combination
17936   // of CMOV and CMP.
17937   //
17938   // The rationale for this change is that the conditional-move from a constant
17939   // needs two instructions, however, conditional-move from a register needs
17940   // only one instruction.
17941   //
17942   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17943   //  some instruction-combining opportunities. This opt needs to be
17944   //  postponed as late as possible.
17945   //
17946   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17947     // the DCI.xxxx conditions are provided to postpone the optimization as
17948     // late as possible.
17949
17950     ConstantSDNode *CmpAgainst = 0;
17951     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17952         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17953         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17954
17955       if (CC == X86::COND_NE &&
17956           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17957         CC = X86::GetOppositeBranchCondition(CC);
17958         std::swap(TrueOp, FalseOp);
17959       }
17960
17961       if (CC == X86::COND_E &&
17962           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17963         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17964                           DAG.getConstant(CC, MVT::i8), Cond };
17965         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17966                            array_lengthof(Ops));
17967       }
17968     }
17969   }
17970
17971   return SDValue();
17972 }
17973
17974 /// PerformMulCombine - Optimize a single multiply with constant into two
17975 /// in order to implement it with two cheaper instructions, e.g.
17976 /// LEA + SHL, LEA + LEA.
17977 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17978                                  TargetLowering::DAGCombinerInfo &DCI) {
17979   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17980     return SDValue();
17981
17982   EVT VT = N->getValueType(0);
17983   if (VT != MVT::i64)
17984     return SDValue();
17985
17986   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17987   if (!C)
17988     return SDValue();
17989   uint64_t MulAmt = C->getZExtValue();
17990   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17991     return SDValue();
17992
17993   uint64_t MulAmt1 = 0;
17994   uint64_t MulAmt2 = 0;
17995   if ((MulAmt % 9) == 0) {
17996     MulAmt1 = 9;
17997     MulAmt2 = MulAmt / 9;
17998   } else if ((MulAmt % 5) == 0) {
17999     MulAmt1 = 5;
18000     MulAmt2 = MulAmt / 5;
18001   } else if ((MulAmt % 3) == 0) {
18002     MulAmt1 = 3;
18003     MulAmt2 = MulAmt / 3;
18004   }
18005   if (MulAmt2 &&
18006       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18007     SDLoc DL(N);
18008
18009     if (isPowerOf2_64(MulAmt2) &&
18010         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18011       // If second multiplifer is pow2, issue it first. We want the multiply by
18012       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18013       // is an add.
18014       std::swap(MulAmt1, MulAmt2);
18015
18016     SDValue NewMul;
18017     if (isPowerOf2_64(MulAmt1))
18018       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18019                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18020     else
18021       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18022                            DAG.getConstant(MulAmt1, VT));
18023
18024     if (isPowerOf2_64(MulAmt2))
18025       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18026                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18027     else
18028       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18029                            DAG.getConstant(MulAmt2, VT));
18030
18031     // Do not add new nodes to DAG combiner worklist.
18032     DCI.CombineTo(N, NewMul, false);
18033   }
18034   return SDValue();
18035 }
18036
18037 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18038   SDValue N0 = N->getOperand(0);
18039   SDValue N1 = N->getOperand(1);
18040   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18041   EVT VT = N0.getValueType();
18042
18043   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18044   // since the result of setcc_c is all zero's or all ones.
18045   if (VT.isInteger() && !VT.isVector() &&
18046       N1C && N0.getOpcode() == ISD::AND &&
18047       N0.getOperand(1).getOpcode() == ISD::Constant) {
18048     SDValue N00 = N0.getOperand(0);
18049     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18050         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18051           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18052          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18053       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18054       APInt ShAmt = N1C->getAPIntValue();
18055       Mask = Mask.shl(ShAmt);
18056       if (Mask != 0)
18057         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18058                            N00, DAG.getConstant(Mask, VT));
18059     }
18060   }
18061
18062   // Hardware support for vector shifts is sparse which makes us scalarize the
18063   // vector operations in many cases. Also, on sandybridge ADD is faster than
18064   // shl.
18065   // (shl V, 1) -> add V,V
18066   if (isSplatVector(N1.getNode())) {
18067     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18068     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18069     // We shift all of the values by one. In many cases we do not have
18070     // hardware support for this operation. This is better expressed as an ADD
18071     // of two values.
18072     if (N1C && (1 == N1C->getZExtValue())) {
18073       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18074     }
18075   }
18076
18077   return SDValue();
18078 }
18079
18080 /// \brief Returns a vector of 0s if the node in input is a vector logical
18081 /// shift by a constant amount which is known to be bigger than or equal
18082 /// to the vector element size in bits.
18083 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18084                                       const X86Subtarget *Subtarget) {
18085   EVT VT = N->getValueType(0);
18086
18087   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18088       (!Subtarget->hasInt256() ||
18089        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18090     return SDValue();
18091
18092   SDValue Amt = N->getOperand(1);
18093   SDLoc DL(N);
18094   if (isSplatVector(Amt.getNode())) {
18095     SDValue SclrAmt = Amt->getOperand(0);
18096     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18097       APInt ShiftAmt = C->getAPIntValue();
18098       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18099
18100       // SSE2/AVX2 logical shifts always return a vector of 0s
18101       // if the shift amount is bigger than or equal to
18102       // the element size. The constant shift amount will be
18103       // encoded as a 8-bit immediate.
18104       if (ShiftAmt.trunc(8).uge(MaxAmount))
18105         return getZeroVector(VT, Subtarget, DAG, DL);
18106     }
18107   }
18108
18109   return SDValue();
18110 }
18111
18112 /// PerformShiftCombine - Combine shifts.
18113 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18114                                    TargetLowering::DAGCombinerInfo &DCI,
18115                                    const X86Subtarget *Subtarget) {
18116   if (N->getOpcode() == ISD::SHL) {
18117     SDValue V = PerformSHLCombine(N, DAG);
18118     if (V.getNode()) return V;
18119   }
18120
18121   if (N->getOpcode() != ISD::SRA) {
18122     // Try to fold this logical shift into a zero vector.
18123     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18124     if (V.getNode()) return V;
18125   }
18126
18127   return SDValue();
18128 }
18129
18130 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18131 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18132 // and friends.  Likewise for OR -> CMPNEQSS.
18133 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18134                             TargetLowering::DAGCombinerInfo &DCI,
18135                             const X86Subtarget *Subtarget) {
18136   unsigned opcode;
18137
18138   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18139   // we're requiring SSE2 for both.
18140   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18141     SDValue N0 = N->getOperand(0);
18142     SDValue N1 = N->getOperand(1);
18143     SDValue CMP0 = N0->getOperand(1);
18144     SDValue CMP1 = N1->getOperand(1);
18145     SDLoc DL(N);
18146
18147     // The SETCCs should both refer to the same CMP.
18148     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18149       return SDValue();
18150
18151     SDValue CMP00 = CMP0->getOperand(0);
18152     SDValue CMP01 = CMP0->getOperand(1);
18153     EVT     VT    = CMP00.getValueType();
18154
18155     if (VT == MVT::f32 || VT == MVT::f64) {
18156       bool ExpectingFlags = false;
18157       // Check for any users that want flags:
18158       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18159            !ExpectingFlags && UI != UE; ++UI)
18160         switch (UI->getOpcode()) {
18161         default:
18162         case ISD::BR_CC:
18163         case ISD::BRCOND:
18164         case ISD::SELECT:
18165           ExpectingFlags = true;
18166           break;
18167         case ISD::CopyToReg:
18168         case ISD::SIGN_EXTEND:
18169         case ISD::ZERO_EXTEND:
18170         case ISD::ANY_EXTEND:
18171           break;
18172         }
18173
18174       if (!ExpectingFlags) {
18175         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18176         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18177
18178         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18179           X86::CondCode tmp = cc0;
18180           cc0 = cc1;
18181           cc1 = tmp;
18182         }
18183
18184         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18185             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18186           // FIXME: need symbolic constants for these magic numbers.
18187           // See X86ATTInstPrinter.cpp:printSSECC().
18188           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18189           if (Subtarget->hasAVX512()) {
18190             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18191                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18192             if (N->getValueType(0) != MVT::i1)
18193               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18194                                  FSetCC);
18195             return FSetCC;
18196           }
18197           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18198                                               CMP00.getValueType(), CMP00, CMP01,
18199                                               DAG.getConstant(x86cc, MVT::i8));
18200
18201           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18202           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18203
18204           if (is64BitFP && !Subtarget->is64Bit()) {
18205             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18206             // 64-bit integer, since that's not a legal type. Since
18207             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18208             // bits, but can do this little dance to extract the lowest 32 bits
18209             // and work with those going forward.
18210             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18211                                            OnesOrZeroesF);
18212             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18213                                            Vector64);
18214             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18215                                         Vector32, DAG.getIntPtrConstant(0));
18216             IntVT = MVT::i32;
18217           }
18218
18219           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18220           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18221                                       DAG.getConstant(1, IntVT));
18222           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18223           return OneBitOfTruth;
18224         }
18225       }
18226     }
18227   }
18228   return SDValue();
18229 }
18230
18231 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18232 /// so it can be folded inside ANDNP.
18233 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18234   EVT VT = N->getValueType(0);
18235
18236   // Match direct AllOnes for 128 and 256-bit vectors
18237   if (ISD::isBuildVectorAllOnes(N))
18238     return true;
18239
18240   // Look through a bit convert.
18241   if (N->getOpcode() == ISD::BITCAST)
18242     N = N->getOperand(0).getNode();
18243
18244   // Sometimes the operand may come from a insert_subvector building a 256-bit
18245   // allones vector
18246   if (VT.is256BitVector() &&
18247       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18248     SDValue V1 = N->getOperand(0);
18249     SDValue V2 = N->getOperand(1);
18250
18251     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18252         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18253         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18254         ISD::isBuildVectorAllOnes(V2.getNode()))
18255       return true;
18256   }
18257
18258   return false;
18259 }
18260
18261 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18262 // register. In most cases we actually compare or select YMM-sized registers
18263 // and mixing the two types creates horrible code. This method optimizes
18264 // some of the transition sequences.
18265 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18266                                  TargetLowering::DAGCombinerInfo &DCI,
18267                                  const X86Subtarget *Subtarget) {
18268   EVT VT = N->getValueType(0);
18269   if (!VT.is256BitVector())
18270     return SDValue();
18271
18272   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18273           N->getOpcode() == ISD::ZERO_EXTEND ||
18274           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18275
18276   SDValue Narrow = N->getOperand(0);
18277   EVT NarrowVT = Narrow->getValueType(0);
18278   if (!NarrowVT.is128BitVector())
18279     return SDValue();
18280
18281   if (Narrow->getOpcode() != ISD::XOR &&
18282       Narrow->getOpcode() != ISD::AND &&
18283       Narrow->getOpcode() != ISD::OR)
18284     return SDValue();
18285
18286   SDValue N0  = Narrow->getOperand(0);
18287   SDValue N1  = Narrow->getOperand(1);
18288   SDLoc DL(Narrow);
18289
18290   // The Left side has to be a trunc.
18291   if (N0.getOpcode() != ISD::TRUNCATE)
18292     return SDValue();
18293
18294   // The type of the truncated inputs.
18295   EVT WideVT = N0->getOperand(0)->getValueType(0);
18296   if (WideVT != VT)
18297     return SDValue();
18298
18299   // The right side has to be a 'trunc' or a constant vector.
18300   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18301   bool RHSConst = (isSplatVector(N1.getNode()) &&
18302                    isa<ConstantSDNode>(N1->getOperand(0)));
18303   if (!RHSTrunc && !RHSConst)
18304     return SDValue();
18305
18306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18307
18308   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18309     return SDValue();
18310
18311   // Set N0 and N1 to hold the inputs to the new wide operation.
18312   N0 = N0->getOperand(0);
18313   if (RHSConst) {
18314     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18315                      N1->getOperand(0));
18316     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18317     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18318   } else if (RHSTrunc) {
18319     N1 = N1->getOperand(0);
18320   }
18321
18322   // Generate the wide operation.
18323   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18324   unsigned Opcode = N->getOpcode();
18325   switch (Opcode) {
18326   case ISD::ANY_EXTEND:
18327     return Op;
18328   case ISD::ZERO_EXTEND: {
18329     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18330     APInt Mask = APInt::getAllOnesValue(InBits);
18331     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18332     return DAG.getNode(ISD::AND, DL, VT,
18333                        Op, DAG.getConstant(Mask, VT));
18334   }
18335   case ISD::SIGN_EXTEND:
18336     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18337                        Op, DAG.getValueType(NarrowVT));
18338   default:
18339     llvm_unreachable("Unexpected opcode");
18340   }
18341 }
18342
18343 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18344                                  TargetLowering::DAGCombinerInfo &DCI,
18345                                  const X86Subtarget *Subtarget) {
18346   EVT VT = N->getValueType(0);
18347   if (DCI.isBeforeLegalizeOps())
18348     return SDValue();
18349
18350   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18351   if (R.getNode())
18352     return R;
18353
18354   // Create BEXTR and BZHI instructions
18355   // BZHI is X & ((1 << Y) - 1)
18356   // BEXTR is ((X >> imm) & (2**size-1))
18357   if (VT == MVT::i32 || VT == MVT::i64) {
18358     SDValue N0 = N->getOperand(0);
18359     SDValue N1 = N->getOperand(1);
18360     SDLoc DL(N);
18361
18362     if (Subtarget->hasBMI2()) {
18363       // Check for (and (add (shl 1, Y), -1), X)
18364       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18365         SDValue N00 = N0.getOperand(0);
18366         if (N00.getOpcode() == ISD::SHL) {
18367           SDValue N001 = N00.getOperand(1);
18368           assert(N001.getValueType() == MVT::i8 && "unexpected type");
18369           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18370           if (C && C->getZExtValue() == 1)
18371             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18372         }
18373       }
18374
18375       // Check for (and X, (add (shl 1, Y), -1))
18376       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18377         SDValue N10 = N1.getOperand(0);
18378         if (N10.getOpcode() == ISD::SHL) {
18379           SDValue N101 = N10.getOperand(1);
18380           assert(N101.getValueType() == MVT::i8 && "unexpected type");
18381           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18382           if (C && C->getZExtValue() == 1)
18383             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18384         }
18385       }
18386     }
18387
18388     // Check for BEXTR.
18389     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18390         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18391       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18392       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18393       if (MaskNode && ShiftNode) {
18394         uint64_t Mask = MaskNode->getZExtValue();
18395         uint64_t Shift = ShiftNode->getZExtValue();
18396         if (isMask_64(Mask)) {
18397           uint64_t MaskSize = CountPopulation_64(Mask);
18398           if (Shift + MaskSize <= VT.getSizeInBits())
18399             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18400                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18401         }
18402       }
18403     } // BEXTR
18404
18405     return SDValue();
18406   }
18407
18408   // Want to form ANDNP nodes:
18409   // 1) In the hopes of then easily combining them with OR and AND nodes
18410   //    to form PBLEND/PSIGN.
18411   // 2) To match ANDN packed intrinsics
18412   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18413     return SDValue();
18414
18415   SDValue N0 = N->getOperand(0);
18416   SDValue N1 = N->getOperand(1);
18417   SDLoc DL(N);
18418
18419   // Check LHS for vnot
18420   if (N0.getOpcode() == ISD::XOR &&
18421       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18422       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18423     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18424
18425   // Check RHS for vnot
18426   if (N1.getOpcode() == ISD::XOR &&
18427       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18428       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18429     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18430
18431   return SDValue();
18432 }
18433
18434 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18435                                 TargetLowering::DAGCombinerInfo &DCI,
18436                                 const X86Subtarget *Subtarget) {
18437   if (DCI.isBeforeLegalizeOps())
18438     return SDValue();
18439
18440   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18441   if (R.getNode())
18442     return R;
18443
18444   SDValue N0 = N->getOperand(0);
18445   SDValue N1 = N->getOperand(1);
18446   EVT VT = N->getValueType(0);
18447
18448   // look for psign/blend
18449   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18450     if (!Subtarget->hasSSSE3() ||
18451         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18452       return SDValue();
18453
18454     // Canonicalize pandn to RHS
18455     if (N0.getOpcode() == X86ISD::ANDNP)
18456       std::swap(N0, N1);
18457     // or (and (m, y), (pandn m, x))
18458     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18459       SDValue Mask = N1.getOperand(0);
18460       SDValue X    = N1.getOperand(1);
18461       SDValue Y;
18462       if (N0.getOperand(0) == Mask)
18463         Y = N0.getOperand(1);
18464       if (N0.getOperand(1) == Mask)
18465         Y = N0.getOperand(0);
18466
18467       // Check to see if the mask appeared in both the AND and ANDNP and
18468       if (!Y.getNode())
18469         return SDValue();
18470
18471       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18472       // Look through mask bitcast.
18473       if (Mask.getOpcode() == ISD::BITCAST)
18474         Mask = Mask.getOperand(0);
18475       if (X.getOpcode() == ISD::BITCAST)
18476         X = X.getOperand(0);
18477       if (Y.getOpcode() == ISD::BITCAST)
18478         Y = Y.getOperand(0);
18479
18480       EVT MaskVT = Mask.getValueType();
18481
18482       // Validate that the Mask operand is a vector sra node.
18483       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18484       // there is no psrai.b
18485       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18486       unsigned SraAmt = ~0;
18487       if (Mask.getOpcode() == ISD::SRA) {
18488         SDValue Amt = Mask.getOperand(1);
18489         if (isSplatVector(Amt.getNode())) {
18490           SDValue SclrAmt = Amt->getOperand(0);
18491           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18492             SraAmt = C->getZExtValue();
18493         }
18494       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18495         SDValue SraC = Mask.getOperand(1);
18496         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18497       }
18498       if ((SraAmt + 1) != EltBits)
18499         return SDValue();
18500
18501       SDLoc DL(N);
18502
18503       // Now we know we at least have a plendvb with the mask val.  See if
18504       // we can form a psignb/w/d.
18505       // psign = x.type == y.type == mask.type && y = sub(0, x);
18506       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18507           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18508           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18509         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18510                "Unsupported VT for PSIGN");
18511         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18512         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18513       }
18514       // PBLENDVB only available on SSE 4.1
18515       if (!Subtarget->hasSSE41())
18516         return SDValue();
18517
18518       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18519
18520       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18521       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18522       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18523       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18524       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18525     }
18526   }
18527
18528   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18529     return SDValue();
18530
18531   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18532   MachineFunction &MF = DAG.getMachineFunction();
18533   bool OptForSize = MF.getFunction()->getAttributes().
18534     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18535
18536   // SHLD/SHRD instructions have lower register pressure, but on some
18537   // platforms they have higher latency than the equivalent
18538   // series of shifts/or that would otherwise be generated.
18539   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18540   // have higher latencies and we are not optimizing for size.
18541   if (!OptForSize && Subtarget->isSHLDSlow())
18542     return SDValue();
18543
18544   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18545     std::swap(N0, N1);
18546   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18547     return SDValue();
18548   if (!N0.hasOneUse() || !N1.hasOneUse())
18549     return SDValue();
18550
18551   SDValue ShAmt0 = N0.getOperand(1);
18552   if (ShAmt0.getValueType() != MVT::i8)
18553     return SDValue();
18554   SDValue ShAmt1 = N1.getOperand(1);
18555   if (ShAmt1.getValueType() != MVT::i8)
18556     return SDValue();
18557   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18558     ShAmt0 = ShAmt0.getOperand(0);
18559   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18560     ShAmt1 = ShAmt1.getOperand(0);
18561
18562   SDLoc DL(N);
18563   unsigned Opc = X86ISD::SHLD;
18564   SDValue Op0 = N0.getOperand(0);
18565   SDValue Op1 = N1.getOperand(0);
18566   if (ShAmt0.getOpcode() == ISD::SUB) {
18567     Opc = X86ISD::SHRD;
18568     std::swap(Op0, Op1);
18569     std::swap(ShAmt0, ShAmt1);
18570   }
18571
18572   unsigned Bits = VT.getSizeInBits();
18573   if (ShAmt1.getOpcode() == ISD::SUB) {
18574     SDValue Sum = ShAmt1.getOperand(0);
18575     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18576       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18577       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18578         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18579       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18580         return DAG.getNode(Opc, DL, VT,
18581                            Op0, Op1,
18582                            DAG.getNode(ISD::TRUNCATE, DL,
18583                                        MVT::i8, ShAmt0));
18584     }
18585   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18586     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18587     if (ShAmt0C &&
18588         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18589       return DAG.getNode(Opc, DL, VT,
18590                          N0.getOperand(0), N1.getOperand(0),
18591                          DAG.getNode(ISD::TRUNCATE, DL,
18592                                        MVT::i8, ShAmt0));
18593   }
18594
18595   return SDValue();
18596 }
18597
18598 // Generate NEG and CMOV for integer abs.
18599 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18600   EVT VT = N->getValueType(0);
18601
18602   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18603   // 8-bit integer abs to NEG and CMOV.
18604   if (VT.isInteger() && VT.getSizeInBits() == 8)
18605     return SDValue();
18606
18607   SDValue N0 = N->getOperand(0);
18608   SDValue N1 = N->getOperand(1);
18609   SDLoc DL(N);
18610
18611   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18612   // and change it to SUB and CMOV.
18613   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18614       N0.getOpcode() == ISD::ADD &&
18615       N0.getOperand(1) == N1 &&
18616       N1.getOpcode() == ISD::SRA &&
18617       N1.getOperand(0) == N0.getOperand(0))
18618     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18619       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18620         // Generate SUB & CMOV.
18621         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18622                                   DAG.getConstant(0, VT), N0.getOperand(0));
18623
18624         SDValue Ops[] = { N0.getOperand(0), Neg,
18625                           DAG.getConstant(X86::COND_GE, MVT::i8),
18626                           SDValue(Neg.getNode(), 1) };
18627         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18628                            Ops, array_lengthof(Ops));
18629       }
18630   return SDValue();
18631 }
18632
18633 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18634 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18635                                  TargetLowering::DAGCombinerInfo &DCI,
18636                                  const X86Subtarget *Subtarget) {
18637   if (DCI.isBeforeLegalizeOps())
18638     return SDValue();
18639
18640   if (Subtarget->hasCMov()) {
18641     SDValue RV = performIntegerAbsCombine(N, DAG);
18642     if (RV.getNode())
18643       return RV;
18644   }
18645
18646   return SDValue();
18647 }
18648
18649 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18650 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18651                                   TargetLowering::DAGCombinerInfo &DCI,
18652                                   const X86Subtarget *Subtarget) {
18653   LoadSDNode *Ld = cast<LoadSDNode>(N);
18654   EVT RegVT = Ld->getValueType(0);
18655   EVT MemVT = Ld->getMemoryVT();
18656   SDLoc dl(Ld);
18657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18658   unsigned RegSz = RegVT.getSizeInBits();
18659
18660   // On Sandybridge unaligned 256bit loads are inefficient.
18661   ISD::LoadExtType Ext = Ld->getExtensionType();
18662   unsigned Alignment = Ld->getAlignment();
18663   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18664   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18665       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18666     unsigned NumElems = RegVT.getVectorNumElements();
18667     if (NumElems < 2)
18668       return SDValue();
18669
18670     SDValue Ptr = Ld->getBasePtr();
18671     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18672
18673     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18674                                   NumElems/2);
18675     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18676                                 Ld->getPointerInfo(), Ld->isVolatile(),
18677                                 Ld->isNonTemporal(), Ld->isInvariant(),
18678                                 Alignment);
18679     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18680     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18681                                 Ld->getPointerInfo(), Ld->isVolatile(),
18682                                 Ld->isNonTemporal(), Ld->isInvariant(),
18683                                 std::min(16U, Alignment));
18684     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18685                              Load1.getValue(1),
18686                              Load2.getValue(1));
18687
18688     SDValue NewVec = DAG.getUNDEF(RegVT);
18689     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18690     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18691     return DCI.CombineTo(N, NewVec, TF, true);
18692   }
18693
18694   // If this is a vector EXT Load then attempt to optimize it using a
18695   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18696   // expansion is still better than scalar code.
18697   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18698   // emit a shuffle and a arithmetic shift.
18699   // TODO: It is possible to support ZExt by zeroing the undef values
18700   // during the shuffle phase or after the shuffle.
18701   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18702       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18703     assert(MemVT != RegVT && "Cannot extend to the same type");
18704     assert(MemVT.isVector() && "Must load a vector from memory");
18705
18706     unsigned NumElems = RegVT.getVectorNumElements();
18707     unsigned MemSz = MemVT.getSizeInBits();
18708     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18709
18710     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18711       return SDValue();
18712
18713     // All sizes must be a power of two.
18714     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18715       return SDValue();
18716
18717     // Attempt to load the original value using scalar loads.
18718     // Find the largest scalar type that divides the total loaded size.
18719     MVT SclrLoadTy = MVT::i8;
18720     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18721          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18722       MVT Tp = (MVT::SimpleValueType)tp;
18723       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18724         SclrLoadTy = Tp;
18725       }
18726     }
18727
18728     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18729     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18730         (64 <= MemSz))
18731       SclrLoadTy = MVT::f64;
18732
18733     // Calculate the number of scalar loads that we need to perform
18734     // in order to load our vector from memory.
18735     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18736     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18737       return SDValue();
18738
18739     unsigned loadRegZize = RegSz;
18740     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18741       loadRegZize /= 2;
18742
18743     // Represent our vector as a sequence of elements which are the
18744     // largest scalar that we can load.
18745     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18746       loadRegZize/SclrLoadTy.getSizeInBits());
18747
18748     // Represent the data using the same element type that is stored in
18749     // memory. In practice, we ''widen'' MemVT.
18750     EVT WideVecVT =
18751           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18752                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18753
18754     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18755       "Invalid vector type");
18756
18757     // We can't shuffle using an illegal type.
18758     if (!TLI.isTypeLegal(WideVecVT))
18759       return SDValue();
18760
18761     SmallVector<SDValue, 8> Chains;
18762     SDValue Ptr = Ld->getBasePtr();
18763     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18764                                         TLI.getPointerTy());
18765     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18766
18767     for (unsigned i = 0; i < NumLoads; ++i) {
18768       // Perform a single load.
18769       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18770                                        Ptr, Ld->getPointerInfo(),
18771                                        Ld->isVolatile(), Ld->isNonTemporal(),
18772                                        Ld->isInvariant(), Ld->getAlignment());
18773       Chains.push_back(ScalarLoad.getValue(1));
18774       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18775       // another round of DAGCombining.
18776       if (i == 0)
18777         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18778       else
18779         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18780                           ScalarLoad, DAG.getIntPtrConstant(i));
18781
18782       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18783     }
18784
18785     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18786                                Chains.size());
18787
18788     // Bitcast the loaded value to a vector of the original element type, in
18789     // the size of the target vector type.
18790     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18791     unsigned SizeRatio = RegSz/MemSz;
18792
18793     if (Ext == ISD::SEXTLOAD) {
18794       // If we have SSE4.1 we can directly emit a VSEXT node.
18795       if (Subtarget->hasSSE41()) {
18796         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18797         return DCI.CombineTo(N, Sext, TF, true);
18798       }
18799
18800       // Otherwise we'll shuffle the small elements in the high bits of the
18801       // larger type and perform an arithmetic shift. If the shift is not legal
18802       // it's better to scalarize.
18803       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18804         return SDValue();
18805
18806       // Redistribute the loaded elements into the different locations.
18807       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18808       for (unsigned i = 0; i != NumElems; ++i)
18809         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18810
18811       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18812                                            DAG.getUNDEF(WideVecVT),
18813                                            &ShuffleVec[0]);
18814
18815       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18816
18817       // Build the arithmetic shift.
18818       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18819                      MemVT.getVectorElementType().getSizeInBits();
18820       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18821                           DAG.getConstant(Amt, RegVT));
18822
18823       return DCI.CombineTo(N, Shuff, TF, true);
18824     }
18825
18826     // Redistribute the loaded elements into the different locations.
18827     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18828     for (unsigned i = 0; i != NumElems; ++i)
18829       ShuffleVec[i*SizeRatio] = i;
18830
18831     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18832                                          DAG.getUNDEF(WideVecVT),
18833                                          &ShuffleVec[0]);
18834
18835     // Bitcast to the requested type.
18836     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18837     // Replace the original load with the new sequence
18838     // and return the new chain.
18839     return DCI.CombineTo(N, Shuff, TF, true);
18840   }
18841
18842   return SDValue();
18843 }
18844
18845 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18846 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18847                                    const X86Subtarget *Subtarget) {
18848   StoreSDNode *St = cast<StoreSDNode>(N);
18849   EVT VT = St->getValue().getValueType();
18850   EVT StVT = St->getMemoryVT();
18851   SDLoc dl(St);
18852   SDValue StoredVal = St->getOperand(1);
18853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18854
18855   // If we are saving a concatenation of two XMM registers, perform two stores.
18856   // On Sandy Bridge, 256-bit memory operations are executed by two
18857   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18858   // memory  operation.
18859   unsigned Alignment = St->getAlignment();
18860   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18861   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18862       StVT == VT && !IsAligned) {
18863     unsigned NumElems = VT.getVectorNumElements();
18864     if (NumElems < 2)
18865       return SDValue();
18866
18867     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18868     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18869
18870     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18871     SDValue Ptr0 = St->getBasePtr();
18872     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18873
18874     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18875                                 St->getPointerInfo(), St->isVolatile(),
18876                                 St->isNonTemporal(), Alignment);
18877     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18878                                 St->getPointerInfo(), St->isVolatile(),
18879                                 St->isNonTemporal(),
18880                                 std::min(16U, Alignment));
18881     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18882   }
18883
18884   // Optimize trunc store (of multiple scalars) to shuffle and store.
18885   // First, pack all of the elements in one place. Next, store to memory
18886   // in fewer chunks.
18887   if (St->isTruncatingStore() && VT.isVector()) {
18888     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18889     unsigned NumElems = VT.getVectorNumElements();
18890     assert(StVT != VT && "Cannot truncate to the same type");
18891     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18892     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18893
18894     // From, To sizes and ElemCount must be pow of two
18895     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18896     // We are going to use the original vector elt for storing.
18897     // Accumulated smaller vector elements must be a multiple of the store size.
18898     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18899
18900     unsigned SizeRatio  = FromSz / ToSz;
18901
18902     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18903
18904     // Create a type on which we perform the shuffle
18905     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18906             StVT.getScalarType(), NumElems*SizeRatio);
18907
18908     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18909
18910     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18911     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18912     for (unsigned i = 0; i != NumElems; ++i)
18913       ShuffleVec[i] = i * SizeRatio;
18914
18915     // Can't shuffle using an illegal type.
18916     if (!TLI.isTypeLegal(WideVecVT))
18917       return SDValue();
18918
18919     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18920                                          DAG.getUNDEF(WideVecVT),
18921                                          &ShuffleVec[0]);
18922     // At this point all of the data is stored at the bottom of the
18923     // register. We now need to save it to mem.
18924
18925     // Find the largest store unit
18926     MVT StoreType = MVT::i8;
18927     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18928          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18929       MVT Tp = (MVT::SimpleValueType)tp;
18930       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18931         StoreType = Tp;
18932     }
18933
18934     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18935     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18936         (64 <= NumElems * ToSz))
18937       StoreType = MVT::f64;
18938
18939     // Bitcast the original vector into a vector of store-size units
18940     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18941             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18942     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18943     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18944     SmallVector<SDValue, 8> Chains;
18945     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18946                                         TLI.getPointerTy());
18947     SDValue Ptr = St->getBasePtr();
18948
18949     // Perform one or more big stores into memory.
18950     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18951       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18952                                    StoreType, ShuffWide,
18953                                    DAG.getIntPtrConstant(i));
18954       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18955                                 St->getPointerInfo(), St->isVolatile(),
18956                                 St->isNonTemporal(), St->getAlignment());
18957       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18958       Chains.push_back(Ch);
18959     }
18960
18961     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18962                                Chains.size());
18963   }
18964
18965   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18966   // the FP state in cases where an emms may be missing.
18967   // A preferable solution to the general problem is to figure out the right
18968   // places to insert EMMS.  This qualifies as a quick hack.
18969
18970   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18971   if (VT.getSizeInBits() != 64)
18972     return SDValue();
18973
18974   const Function *F = DAG.getMachineFunction().getFunction();
18975   bool NoImplicitFloatOps = F->getAttributes().
18976     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18977   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18978                      && Subtarget->hasSSE2();
18979   if ((VT.isVector() ||
18980        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18981       isa<LoadSDNode>(St->getValue()) &&
18982       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18983       St->getChain().hasOneUse() && !St->isVolatile()) {
18984     SDNode* LdVal = St->getValue().getNode();
18985     LoadSDNode *Ld = 0;
18986     int TokenFactorIndex = -1;
18987     SmallVector<SDValue, 8> Ops;
18988     SDNode* ChainVal = St->getChain().getNode();
18989     // Must be a store of a load.  We currently handle two cases:  the load
18990     // is a direct child, and it's under an intervening TokenFactor.  It is
18991     // possible to dig deeper under nested TokenFactors.
18992     if (ChainVal == LdVal)
18993       Ld = cast<LoadSDNode>(St->getChain());
18994     else if (St->getValue().hasOneUse() &&
18995              ChainVal->getOpcode() == ISD::TokenFactor) {
18996       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18997         if (ChainVal->getOperand(i).getNode() == LdVal) {
18998           TokenFactorIndex = i;
18999           Ld = cast<LoadSDNode>(St->getValue());
19000         } else
19001           Ops.push_back(ChainVal->getOperand(i));
19002       }
19003     }
19004
19005     if (!Ld || !ISD::isNormalLoad(Ld))
19006       return SDValue();
19007
19008     // If this is not the MMX case, i.e. we are just turning i64 load/store
19009     // into f64 load/store, avoid the transformation if there are multiple
19010     // uses of the loaded value.
19011     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19012       return SDValue();
19013
19014     SDLoc LdDL(Ld);
19015     SDLoc StDL(N);
19016     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19017     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19018     // pair instead.
19019     if (Subtarget->is64Bit() || F64IsLegal) {
19020       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19021       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19022                                   Ld->getPointerInfo(), Ld->isVolatile(),
19023                                   Ld->isNonTemporal(), Ld->isInvariant(),
19024                                   Ld->getAlignment());
19025       SDValue NewChain = NewLd.getValue(1);
19026       if (TokenFactorIndex != -1) {
19027         Ops.push_back(NewChain);
19028         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19029                                Ops.size());
19030       }
19031       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19032                           St->getPointerInfo(),
19033                           St->isVolatile(), St->isNonTemporal(),
19034                           St->getAlignment());
19035     }
19036
19037     // Otherwise, lower to two pairs of 32-bit loads / stores.
19038     SDValue LoAddr = Ld->getBasePtr();
19039     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19040                                  DAG.getConstant(4, MVT::i32));
19041
19042     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19043                                Ld->getPointerInfo(),
19044                                Ld->isVolatile(), Ld->isNonTemporal(),
19045                                Ld->isInvariant(), Ld->getAlignment());
19046     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19047                                Ld->getPointerInfo().getWithOffset(4),
19048                                Ld->isVolatile(), Ld->isNonTemporal(),
19049                                Ld->isInvariant(),
19050                                MinAlign(Ld->getAlignment(), 4));
19051
19052     SDValue NewChain = LoLd.getValue(1);
19053     if (TokenFactorIndex != -1) {
19054       Ops.push_back(LoLd);
19055       Ops.push_back(HiLd);
19056       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19057                              Ops.size());
19058     }
19059
19060     LoAddr = St->getBasePtr();
19061     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19062                          DAG.getConstant(4, MVT::i32));
19063
19064     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19065                                 St->getPointerInfo(),
19066                                 St->isVolatile(), St->isNonTemporal(),
19067                                 St->getAlignment());
19068     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19069                                 St->getPointerInfo().getWithOffset(4),
19070                                 St->isVolatile(),
19071                                 St->isNonTemporal(),
19072                                 MinAlign(St->getAlignment(), 4));
19073     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19074   }
19075   return SDValue();
19076 }
19077
19078 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19079 /// and return the operands for the horizontal operation in LHS and RHS.  A
19080 /// horizontal operation performs the binary operation on successive elements
19081 /// of its first operand, then on successive elements of its second operand,
19082 /// returning the resulting values in a vector.  For example, if
19083 ///   A = < float a0, float a1, float a2, float a3 >
19084 /// and
19085 ///   B = < float b0, float b1, float b2, float b3 >
19086 /// then the result of doing a horizontal operation on A and B is
19087 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19088 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19089 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19090 /// set to A, RHS to B, and the routine returns 'true'.
19091 /// Note that the binary operation should have the property that if one of the
19092 /// operands is UNDEF then the result is UNDEF.
19093 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19094   // Look for the following pattern: if
19095   //   A = < float a0, float a1, float a2, float a3 >
19096   //   B = < float b0, float b1, float b2, float b3 >
19097   // and
19098   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19099   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19100   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19101   // which is A horizontal-op B.
19102
19103   // At least one of the operands should be a vector shuffle.
19104   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19105       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19106     return false;
19107
19108   MVT VT = LHS.getSimpleValueType();
19109
19110   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19111          "Unsupported vector type for horizontal add/sub");
19112
19113   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19114   // operate independently on 128-bit lanes.
19115   unsigned NumElts = VT.getVectorNumElements();
19116   unsigned NumLanes = VT.getSizeInBits()/128;
19117   unsigned NumLaneElts = NumElts / NumLanes;
19118   assert((NumLaneElts % 2 == 0) &&
19119          "Vector type should have an even number of elements in each lane");
19120   unsigned HalfLaneElts = NumLaneElts/2;
19121
19122   // View LHS in the form
19123   //   LHS = VECTOR_SHUFFLE A, B, LMask
19124   // If LHS is not a shuffle then pretend it is the shuffle
19125   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19126   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19127   // type VT.
19128   SDValue A, B;
19129   SmallVector<int, 16> LMask(NumElts);
19130   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19131     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19132       A = LHS.getOperand(0);
19133     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19134       B = LHS.getOperand(1);
19135     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19136     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19137   } else {
19138     if (LHS.getOpcode() != ISD::UNDEF)
19139       A = LHS;
19140     for (unsigned i = 0; i != NumElts; ++i)
19141       LMask[i] = i;
19142   }
19143
19144   // Likewise, view RHS in the form
19145   //   RHS = VECTOR_SHUFFLE C, D, RMask
19146   SDValue C, D;
19147   SmallVector<int, 16> RMask(NumElts);
19148   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19149     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19150       C = RHS.getOperand(0);
19151     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19152       D = RHS.getOperand(1);
19153     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19154     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19155   } else {
19156     if (RHS.getOpcode() != ISD::UNDEF)
19157       C = RHS;
19158     for (unsigned i = 0; i != NumElts; ++i)
19159       RMask[i] = i;
19160   }
19161
19162   // Check that the shuffles are both shuffling the same vectors.
19163   if (!(A == C && B == D) && !(A == D && B == C))
19164     return false;
19165
19166   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19167   if (!A.getNode() && !B.getNode())
19168     return false;
19169
19170   // If A and B occur in reverse order in RHS, then "swap" them (which means
19171   // rewriting the mask).
19172   if (A != C)
19173     CommuteVectorShuffleMask(RMask, NumElts);
19174
19175   // At this point LHS and RHS are equivalent to
19176   //   LHS = VECTOR_SHUFFLE A, B, LMask
19177   //   RHS = VECTOR_SHUFFLE A, B, RMask
19178   // Check that the masks correspond to performing a horizontal operation.
19179   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19180     for (unsigned i = 0; i != NumLaneElts; ++i) {
19181       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19182
19183       // Ignore any UNDEF components.
19184       if (LIdx < 0 || RIdx < 0 ||
19185           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19186           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19187         continue;
19188
19189       // Check that successive elements are being operated on.  If not, this is
19190       // not a horizontal operation.
19191       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19192       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19193       if (!(LIdx == Index && RIdx == Index + 1) &&
19194           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19195         return false;
19196     }
19197   }
19198
19199   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19200   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19201   return true;
19202 }
19203
19204 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19205 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19206                                   const X86Subtarget *Subtarget) {
19207   EVT VT = N->getValueType(0);
19208   SDValue LHS = N->getOperand(0);
19209   SDValue RHS = N->getOperand(1);
19210
19211   // Try to synthesize horizontal adds from adds of shuffles.
19212   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19213        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19214       isHorizontalBinOp(LHS, RHS, true))
19215     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19216   return SDValue();
19217 }
19218
19219 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19220 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19221                                   const X86Subtarget *Subtarget) {
19222   EVT VT = N->getValueType(0);
19223   SDValue LHS = N->getOperand(0);
19224   SDValue RHS = N->getOperand(1);
19225
19226   // Try to synthesize horizontal subs from subs of shuffles.
19227   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19228        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19229       isHorizontalBinOp(LHS, RHS, false))
19230     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19231   return SDValue();
19232 }
19233
19234 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19235 /// X86ISD::FXOR nodes.
19236 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19237   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19238   // F[X]OR(0.0, x) -> x
19239   // F[X]OR(x, 0.0) -> x
19240   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19241     if (C->getValueAPF().isPosZero())
19242       return N->getOperand(1);
19243   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19244     if (C->getValueAPF().isPosZero())
19245       return N->getOperand(0);
19246   return SDValue();
19247 }
19248
19249 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19250 /// X86ISD::FMAX nodes.
19251 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19252   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19253
19254   // Only perform optimizations if UnsafeMath is used.
19255   if (!DAG.getTarget().Options.UnsafeFPMath)
19256     return SDValue();
19257
19258   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19259   // into FMINC and FMAXC, which are Commutative operations.
19260   unsigned NewOp = 0;
19261   switch (N->getOpcode()) {
19262     default: llvm_unreachable("unknown opcode");
19263     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19264     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19265   }
19266
19267   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19268                      N->getOperand(0), N->getOperand(1));
19269 }
19270
19271 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19272 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19273   // FAND(0.0, x) -> 0.0
19274   // FAND(x, 0.0) -> 0.0
19275   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19276     if (C->getValueAPF().isPosZero())
19277       return N->getOperand(0);
19278   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19279     if (C->getValueAPF().isPosZero())
19280       return N->getOperand(1);
19281   return SDValue();
19282 }
19283
19284 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19285 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19286   // FANDN(x, 0.0) -> 0.0
19287   // FANDN(0.0, x) -> x
19288   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19289     if (C->getValueAPF().isPosZero())
19290       return N->getOperand(1);
19291   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19292     if (C->getValueAPF().isPosZero())
19293       return N->getOperand(1);
19294   return SDValue();
19295 }
19296
19297 static SDValue PerformBTCombine(SDNode *N,
19298                                 SelectionDAG &DAG,
19299                                 TargetLowering::DAGCombinerInfo &DCI) {
19300   // BT ignores high bits in the bit index operand.
19301   SDValue Op1 = N->getOperand(1);
19302   if (Op1.hasOneUse()) {
19303     unsigned BitWidth = Op1.getValueSizeInBits();
19304     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19305     APInt KnownZero, KnownOne;
19306     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19307                                           !DCI.isBeforeLegalizeOps());
19308     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19309     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19310         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19311       DCI.CommitTargetLoweringOpt(TLO);
19312   }
19313   return SDValue();
19314 }
19315
19316 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19317   SDValue Op = N->getOperand(0);
19318   if (Op.getOpcode() == ISD::BITCAST)
19319     Op = Op.getOperand(0);
19320   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19321   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19322       VT.getVectorElementType().getSizeInBits() ==
19323       OpVT.getVectorElementType().getSizeInBits()) {
19324     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19325   }
19326   return SDValue();
19327 }
19328
19329 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19330                                                const X86Subtarget *Subtarget) {
19331   EVT VT = N->getValueType(0);
19332   if (!VT.isVector())
19333     return SDValue();
19334
19335   SDValue N0 = N->getOperand(0);
19336   SDValue N1 = N->getOperand(1);
19337   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19338   SDLoc dl(N);
19339
19340   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19341   // both SSE and AVX2 since there is no sign-extended shift right
19342   // operation on a vector with 64-bit elements.
19343   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19344   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19345   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19346       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19347     SDValue N00 = N0.getOperand(0);
19348
19349     // EXTLOAD has a better solution on AVX2,
19350     // it may be replaced with X86ISD::VSEXT node.
19351     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19352       if (!ISD::isNormalLoad(N00.getNode()))
19353         return SDValue();
19354
19355     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19356         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19357                                   N00, N1);
19358       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19359     }
19360   }
19361   return SDValue();
19362 }
19363
19364 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19365                                   TargetLowering::DAGCombinerInfo &DCI,
19366                                   const X86Subtarget *Subtarget) {
19367   if (!DCI.isBeforeLegalizeOps())
19368     return SDValue();
19369
19370   if (!Subtarget->hasFp256())
19371     return SDValue();
19372
19373   EVT VT = N->getValueType(0);
19374   if (VT.isVector() && VT.getSizeInBits() == 256) {
19375     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19376     if (R.getNode())
19377       return R;
19378   }
19379
19380   return SDValue();
19381 }
19382
19383 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19384                                  const X86Subtarget* Subtarget) {
19385   SDLoc dl(N);
19386   EVT VT = N->getValueType(0);
19387
19388   // Let legalize expand this if it isn't a legal type yet.
19389   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19390     return SDValue();
19391
19392   EVT ScalarVT = VT.getScalarType();
19393   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19394       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19395     return SDValue();
19396
19397   SDValue A = N->getOperand(0);
19398   SDValue B = N->getOperand(1);
19399   SDValue C = N->getOperand(2);
19400
19401   bool NegA = (A.getOpcode() == ISD::FNEG);
19402   bool NegB = (B.getOpcode() == ISD::FNEG);
19403   bool NegC = (C.getOpcode() == ISD::FNEG);
19404
19405   // Negative multiplication when NegA xor NegB
19406   bool NegMul = (NegA != NegB);
19407   if (NegA)
19408     A = A.getOperand(0);
19409   if (NegB)
19410     B = B.getOperand(0);
19411   if (NegC)
19412     C = C.getOperand(0);
19413
19414   unsigned Opcode;
19415   if (!NegMul)
19416     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19417   else
19418     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19419
19420   return DAG.getNode(Opcode, dl, VT, A, B, C);
19421 }
19422
19423 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19424                                   TargetLowering::DAGCombinerInfo &DCI,
19425                                   const X86Subtarget *Subtarget) {
19426   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19427   //           (and (i32 x86isd::setcc_carry), 1)
19428   // This eliminates the zext. This transformation is necessary because
19429   // ISD::SETCC is always legalized to i8.
19430   SDLoc dl(N);
19431   SDValue N0 = N->getOperand(0);
19432   EVT VT = N->getValueType(0);
19433
19434   if (N0.getOpcode() == ISD::AND &&
19435       N0.hasOneUse() &&
19436       N0.getOperand(0).hasOneUse()) {
19437     SDValue N00 = N0.getOperand(0);
19438     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19439       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19440       if (!C || C->getZExtValue() != 1)
19441         return SDValue();
19442       return DAG.getNode(ISD::AND, dl, VT,
19443                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19444                                      N00.getOperand(0), N00.getOperand(1)),
19445                          DAG.getConstant(1, VT));
19446     }
19447   }
19448
19449   if (N0.getOpcode() == ISD::TRUNCATE &&
19450       N0.hasOneUse() &&
19451       N0.getOperand(0).hasOneUse()) {
19452     SDValue N00 = N0.getOperand(0);
19453     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19454       return DAG.getNode(ISD::AND, dl, VT,
19455                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19456                                      N00.getOperand(0), N00.getOperand(1)),
19457                          DAG.getConstant(1, VT));
19458     }
19459   }
19460   if (VT.is256BitVector()) {
19461     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19462     if (R.getNode())
19463       return R;
19464   }
19465
19466   return SDValue();
19467 }
19468
19469 // Optimize x == -y --> x+y == 0
19470 //          x != -y --> x+y != 0
19471 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19472                                       const X86Subtarget* Subtarget) {
19473   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19474   SDValue LHS = N->getOperand(0);
19475   SDValue RHS = N->getOperand(1);
19476   EVT VT = N->getValueType(0);
19477   SDLoc DL(N);
19478
19479   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19481       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19482         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19483                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19484         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19485                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19486       }
19487   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19488     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19489       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19490         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19491                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19492         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19493                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19494       }
19495
19496   if (VT.getScalarType() == MVT::i1) {
19497     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19498       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19499     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19500     if (!IsSEXT0 && !IsVZero0)
19501       return SDValue();
19502     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19503       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19504     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19505
19506     if (!IsSEXT1 && !IsVZero1)
19507       return SDValue();
19508
19509     if (IsSEXT0 && IsVZero1) {
19510       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19511       if (CC == ISD::SETEQ)
19512         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19513       return LHS.getOperand(0);
19514     }
19515     if (IsSEXT1 && IsVZero0) {
19516       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19517       if (CC == ISD::SETEQ)
19518         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19519       return RHS.getOperand(0);
19520     }
19521   }
19522
19523   return SDValue();
19524 }
19525
19526 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19527 // as "sbb reg,reg", since it can be extended without zext and produces
19528 // an all-ones bit which is more useful than 0/1 in some cases.
19529 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19530                                MVT VT) {
19531   if (VT == MVT::i8)
19532     return DAG.getNode(ISD::AND, DL, VT,
19533                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19534                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19535                        DAG.getConstant(1, VT));
19536   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19537   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19538                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19539                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19540 }
19541
19542 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19543 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19544                                    TargetLowering::DAGCombinerInfo &DCI,
19545                                    const X86Subtarget *Subtarget) {
19546   SDLoc DL(N);
19547   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19548   SDValue EFLAGS = N->getOperand(1);
19549
19550   if (CC == X86::COND_A) {
19551     // Try to convert COND_A into COND_B in an attempt to facilitate
19552     // materializing "setb reg".
19553     //
19554     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19555     // cannot take an immediate as its first operand.
19556     //
19557     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19558         EFLAGS.getValueType().isInteger() &&
19559         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19560       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19561                                    EFLAGS.getNode()->getVTList(),
19562                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19563       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19564       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19565     }
19566   }
19567
19568   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19569   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19570   // cases.
19571   if (CC == X86::COND_B)
19572     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19573
19574   SDValue Flags;
19575
19576   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19577   if (Flags.getNode()) {
19578     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19579     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19580   }
19581
19582   return SDValue();
19583 }
19584
19585 // Optimize branch condition evaluation.
19586 //
19587 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19588                                     TargetLowering::DAGCombinerInfo &DCI,
19589                                     const X86Subtarget *Subtarget) {
19590   SDLoc DL(N);
19591   SDValue Chain = N->getOperand(0);
19592   SDValue Dest = N->getOperand(1);
19593   SDValue EFLAGS = N->getOperand(3);
19594   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19595
19596   SDValue Flags;
19597
19598   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19599   if (Flags.getNode()) {
19600     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19601     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19602                        Flags);
19603   }
19604
19605   return SDValue();
19606 }
19607
19608 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19609                                         const X86TargetLowering *XTLI) {
19610   SDValue Op0 = N->getOperand(0);
19611   EVT InVT = Op0->getValueType(0);
19612
19613   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19614   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19615     SDLoc dl(N);
19616     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19617     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19618     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19619   }
19620
19621   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19622   // a 32-bit target where SSE doesn't support i64->FP operations.
19623   if (Op0.getOpcode() == ISD::LOAD) {
19624     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19625     EVT VT = Ld->getValueType(0);
19626     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19627         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19628         !XTLI->getSubtarget()->is64Bit() &&
19629         VT == MVT::i64) {
19630       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19631                                           Ld->getChain(), Op0, DAG);
19632       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19633       return FILDChain;
19634     }
19635   }
19636   return SDValue();
19637 }
19638
19639 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19640 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19641                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19642   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19643   // the result is either zero or one (depending on the input carry bit).
19644   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19645   if (X86::isZeroNode(N->getOperand(0)) &&
19646       X86::isZeroNode(N->getOperand(1)) &&
19647       // We don't have a good way to replace an EFLAGS use, so only do this when
19648       // dead right now.
19649       SDValue(N, 1).use_empty()) {
19650     SDLoc DL(N);
19651     EVT VT = N->getValueType(0);
19652     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19653     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19654                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19655                                            DAG.getConstant(X86::COND_B,MVT::i8),
19656                                            N->getOperand(2)),
19657                                DAG.getConstant(1, VT));
19658     return DCI.CombineTo(N, Res1, CarryOut);
19659   }
19660
19661   return SDValue();
19662 }
19663
19664 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19665 //      (add Y, (setne X, 0)) -> sbb -1, Y
19666 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19667 //      (sub (setne X, 0), Y) -> adc -1, Y
19668 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19669   SDLoc DL(N);
19670
19671   // Look through ZExts.
19672   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19673   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19674     return SDValue();
19675
19676   SDValue SetCC = Ext.getOperand(0);
19677   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19678     return SDValue();
19679
19680   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19681   if (CC != X86::COND_E && CC != X86::COND_NE)
19682     return SDValue();
19683
19684   SDValue Cmp = SetCC.getOperand(1);
19685   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19686       !X86::isZeroNode(Cmp.getOperand(1)) ||
19687       !Cmp.getOperand(0).getValueType().isInteger())
19688     return SDValue();
19689
19690   SDValue CmpOp0 = Cmp.getOperand(0);
19691   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19692                                DAG.getConstant(1, CmpOp0.getValueType()));
19693
19694   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19695   if (CC == X86::COND_NE)
19696     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19697                        DL, OtherVal.getValueType(), OtherVal,
19698                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19699   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19700                      DL, OtherVal.getValueType(), OtherVal,
19701                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19702 }
19703
19704 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19705 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19706                                  const X86Subtarget *Subtarget) {
19707   EVT VT = N->getValueType(0);
19708   SDValue Op0 = N->getOperand(0);
19709   SDValue Op1 = N->getOperand(1);
19710
19711   // Try to synthesize horizontal adds from adds of shuffles.
19712   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19713        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19714       isHorizontalBinOp(Op0, Op1, true))
19715     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19716
19717   return OptimizeConditionalInDecrement(N, DAG);
19718 }
19719
19720 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19721                                  const X86Subtarget *Subtarget) {
19722   SDValue Op0 = N->getOperand(0);
19723   SDValue Op1 = N->getOperand(1);
19724
19725   // X86 can't encode an immediate LHS of a sub. See if we can push the
19726   // negation into a preceding instruction.
19727   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19728     // If the RHS of the sub is a XOR with one use and a constant, invert the
19729     // immediate. Then add one to the LHS of the sub so we can turn
19730     // X-Y -> X+~Y+1, saving one register.
19731     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19732         isa<ConstantSDNode>(Op1.getOperand(1))) {
19733       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19734       EVT VT = Op0.getValueType();
19735       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19736                                    Op1.getOperand(0),
19737                                    DAG.getConstant(~XorC, VT));
19738       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19739                          DAG.getConstant(C->getAPIntValue()+1, VT));
19740     }
19741   }
19742
19743   // Try to synthesize horizontal adds from adds of shuffles.
19744   EVT VT = N->getValueType(0);
19745   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19746        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19747       isHorizontalBinOp(Op0, Op1, true))
19748     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19749
19750   return OptimizeConditionalInDecrement(N, DAG);
19751 }
19752
19753 /// performVZEXTCombine - Performs build vector combines
19754 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19755                                         TargetLowering::DAGCombinerInfo &DCI,
19756                                         const X86Subtarget *Subtarget) {
19757   // (vzext (bitcast (vzext (x)) -> (vzext x)
19758   SDValue In = N->getOperand(0);
19759   while (In.getOpcode() == ISD::BITCAST)
19760     In = In.getOperand(0);
19761
19762   if (In.getOpcode() != X86ISD::VZEXT)
19763     return SDValue();
19764
19765   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19766                      In.getOperand(0));
19767 }
19768
19769 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19770                                              DAGCombinerInfo &DCI) const {
19771   SelectionDAG &DAG = DCI.DAG;
19772   switch (N->getOpcode()) {
19773   default: break;
19774   case ISD::EXTRACT_VECTOR_ELT:
19775     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19776   case ISD::VSELECT:
19777   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19778   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19779   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19780   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19781   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19782   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19783   case ISD::SHL:
19784   case ISD::SRA:
19785   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19786   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19787   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19788   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19789   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19790   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19791   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19792   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19793   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19794   case X86ISD::FXOR:
19795   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19796   case X86ISD::FMIN:
19797   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19798   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19799   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19800   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19801   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19802   case ISD::ANY_EXTEND:
19803   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19804   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19805   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19806   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19807   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
19808   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19809   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19810   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19811   case X86ISD::SHUFP:       // Handle all target specific shuffles
19812   case X86ISD::PALIGNR:
19813   case X86ISD::UNPCKH:
19814   case X86ISD::UNPCKL:
19815   case X86ISD::MOVHLPS:
19816   case X86ISD::MOVLHPS:
19817   case X86ISD::PSHUFD:
19818   case X86ISD::PSHUFHW:
19819   case X86ISD::PSHUFLW:
19820   case X86ISD::MOVSS:
19821   case X86ISD::MOVSD:
19822   case X86ISD::VPERMILP:
19823   case X86ISD::VPERM2X128:
19824   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19825   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19826   }
19827
19828   return SDValue();
19829 }
19830
19831 /// isTypeDesirableForOp - Return true if the target has native support for
19832 /// the specified value type and it is 'desirable' to use the type for the
19833 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19834 /// instruction encodings are longer and some i16 instructions are slow.
19835 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19836   if (!isTypeLegal(VT))
19837     return false;
19838   if (VT != MVT::i16)
19839     return true;
19840
19841   switch (Opc) {
19842   default:
19843     return true;
19844   case ISD::LOAD:
19845   case ISD::SIGN_EXTEND:
19846   case ISD::ZERO_EXTEND:
19847   case ISD::ANY_EXTEND:
19848   case ISD::SHL:
19849   case ISD::SRL:
19850   case ISD::SUB:
19851   case ISD::ADD:
19852   case ISD::MUL:
19853   case ISD::AND:
19854   case ISD::OR:
19855   case ISD::XOR:
19856     return false;
19857   }
19858 }
19859
19860 /// IsDesirableToPromoteOp - This method query the target whether it is
19861 /// beneficial for dag combiner to promote the specified node. If true, it
19862 /// should return the desired promotion type by reference.
19863 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19864   EVT VT = Op.getValueType();
19865   if (VT != MVT::i16)
19866     return false;
19867
19868   bool Promote = false;
19869   bool Commute = false;
19870   switch (Op.getOpcode()) {
19871   default: break;
19872   case ISD::LOAD: {
19873     LoadSDNode *LD = cast<LoadSDNode>(Op);
19874     // If the non-extending load has a single use and it's not live out, then it
19875     // might be folded.
19876     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19877                                                      Op.hasOneUse()*/) {
19878       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19879              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19880         // The only case where we'd want to promote LOAD (rather then it being
19881         // promoted as an operand is when it's only use is liveout.
19882         if (UI->getOpcode() != ISD::CopyToReg)
19883           return false;
19884       }
19885     }
19886     Promote = true;
19887     break;
19888   }
19889   case ISD::SIGN_EXTEND:
19890   case ISD::ZERO_EXTEND:
19891   case ISD::ANY_EXTEND:
19892     Promote = true;
19893     break;
19894   case ISD::SHL:
19895   case ISD::SRL: {
19896     SDValue N0 = Op.getOperand(0);
19897     // Look out for (store (shl (load), x)).
19898     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19899       return false;
19900     Promote = true;
19901     break;
19902   }
19903   case ISD::ADD:
19904   case ISD::MUL:
19905   case ISD::AND:
19906   case ISD::OR:
19907   case ISD::XOR:
19908     Commute = true;
19909     // fallthrough
19910   case ISD::SUB: {
19911     SDValue N0 = Op.getOperand(0);
19912     SDValue N1 = Op.getOperand(1);
19913     if (!Commute && MayFoldLoad(N1))
19914       return false;
19915     // Avoid disabling potential load folding opportunities.
19916     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19917       return false;
19918     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19919       return false;
19920     Promote = true;
19921   }
19922   }
19923
19924   PVT = MVT::i32;
19925   return Promote;
19926 }
19927
19928 //===----------------------------------------------------------------------===//
19929 //                           X86 Inline Assembly Support
19930 //===----------------------------------------------------------------------===//
19931
19932 namespace {
19933   // Helper to match a string separated by whitespace.
19934   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19935     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19936
19937     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19938       StringRef piece(*args[i]);
19939       if (!s.startswith(piece)) // Check if the piece matches.
19940         return false;
19941
19942       s = s.substr(piece.size());
19943       StringRef::size_type pos = s.find_first_not_of(" \t");
19944       if (pos == 0) // We matched a prefix.
19945         return false;
19946
19947       s = s.substr(pos);
19948     }
19949
19950     return s.empty();
19951   }
19952   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19953 }
19954
19955 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19956
19957   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19958     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19959         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19960         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19961
19962       if (AsmPieces.size() == 3)
19963         return true;
19964       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19965         return true;
19966     }
19967   }
19968   return false;
19969 }
19970
19971 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19972   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19973
19974   std::string AsmStr = IA->getAsmString();
19975
19976   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19977   if (!Ty || Ty->getBitWidth() % 16 != 0)
19978     return false;
19979
19980   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19981   SmallVector<StringRef, 4> AsmPieces;
19982   SplitString(AsmStr, AsmPieces, ";\n");
19983
19984   switch (AsmPieces.size()) {
19985   default: return false;
19986   case 1:
19987     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19988     // we will turn this bswap into something that will be lowered to logical
19989     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19990     // lower so don't worry about this.
19991     // bswap $0
19992     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19993         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19994         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19995         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19996         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19997         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19998       // No need to check constraints, nothing other than the equivalent of
19999       // "=r,0" would be valid here.
20000       return IntrinsicLowering::LowerToByteSwap(CI);
20001     }
20002
20003     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20004     if (CI->getType()->isIntegerTy(16) &&
20005         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20006         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20007          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20008       AsmPieces.clear();
20009       const std::string &ConstraintsStr = IA->getConstraintString();
20010       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20011       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20012       if (clobbersFlagRegisters(AsmPieces))
20013         return IntrinsicLowering::LowerToByteSwap(CI);
20014     }
20015     break;
20016   case 3:
20017     if (CI->getType()->isIntegerTy(32) &&
20018         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20019         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20020         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20021         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20022       AsmPieces.clear();
20023       const std::string &ConstraintsStr = IA->getConstraintString();
20024       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20025       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20026       if (clobbersFlagRegisters(AsmPieces))
20027         return IntrinsicLowering::LowerToByteSwap(CI);
20028     }
20029
20030     if (CI->getType()->isIntegerTy(64)) {
20031       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20032       if (Constraints.size() >= 2 &&
20033           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20034           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20035         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20036         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20037             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20038             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20039           return IntrinsicLowering::LowerToByteSwap(CI);
20040       }
20041     }
20042     break;
20043   }
20044   return false;
20045 }
20046
20047 /// getConstraintType - Given a constraint letter, return the type of
20048 /// constraint it is for this target.
20049 X86TargetLowering::ConstraintType
20050 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20051   if (Constraint.size() == 1) {
20052     switch (Constraint[0]) {
20053     case 'R':
20054     case 'q':
20055     case 'Q':
20056     case 'f':
20057     case 't':
20058     case 'u':
20059     case 'y':
20060     case 'x':
20061     case 'Y':
20062     case 'l':
20063       return C_RegisterClass;
20064     case 'a':
20065     case 'b':
20066     case 'c':
20067     case 'd':
20068     case 'S':
20069     case 'D':
20070     case 'A':
20071       return C_Register;
20072     case 'I':
20073     case 'J':
20074     case 'K':
20075     case 'L':
20076     case 'M':
20077     case 'N':
20078     case 'G':
20079     case 'C':
20080     case 'e':
20081     case 'Z':
20082       return C_Other;
20083     default:
20084       break;
20085     }
20086   }
20087   return TargetLowering::getConstraintType(Constraint);
20088 }
20089
20090 /// Examine constraint type and operand type and determine a weight value.
20091 /// This object must already have been set up with the operand type
20092 /// and the current alternative constraint selected.
20093 TargetLowering::ConstraintWeight
20094   X86TargetLowering::getSingleConstraintMatchWeight(
20095     AsmOperandInfo &info, const char *constraint) const {
20096   ConstraintWeight weight = CW_Invalid;
20097   Value *CallOperandVal = info.CallOperandVal;
20098     // If we don't have a value, we can't do a match,
20099     // but allow it at the lowest weight.
20100   if (CallOperandVal == NULL)
20101     return CW_Default;
20102   Type *type = CallOperandVal->getType();
20103   // Look at the constraint type.
20104   switch (*constraint) {
20105   default:
20106     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20107   case 'R':
20108   case 'q':
20109   case 'Q':
20110   case 'a':
20111   case 'b':
20112   case 'c':
20113   case 'd':
20114   case 'S':
20115   case 'D':
20116   case 'A':
20117     if (CallOperandVal->getType()->isIntegerTy())
20118       weight = CW_SpecificReg;
20119     break;
20120   case 'f':
20121   case 't':
20122   case 'u':
20123     if (type->isFloatingPointTy())
20124       weight = CW_SpecificReg;
20125     break;
20126   case 'y':
20127     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20128       weight = CW_SpecificReg;
20129     break;
20130   case 'x':
20131   case 'Y':
20132     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20133         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20134       weight = CW_Register;
20135     break;
20136   case 'I':
20137     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20138       if (C->getZExtValue() <= 31)
20139         weight = CW_Constant;
20140     }
20141     break;
20142   case 'J':
20143     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20144       if (C->getZExtValue() <= 63)
20145         weight = CW_Constant;
20146     }
20147     break;
20148   case 'K':
20149     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20150       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20151         weight = CW_Constant;
20152     }
20153     break;
20154   case 'L':
20155     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20156       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20157         weight = CW_Constant;
20158     }
20159     break;
20160   case 'M':
20161     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20162       if (C->getZExtValue() <= 3)
20163         weight = CW_Constant;
20164     }
20165     break;
20166   case 'N':
20167     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20168       if (C->getZExtValue() <= 0xff)
20169         weight = CW_Constant;
20170     }
20171     break;
20172   case 'G':
20173   case 'C':
20174     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20175       weight = CW_Constant;
20176     }
20177     break;
20178   case 'e':
20179     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20180       if ((C->getSExtValue() >= -0x80000000LL) &&
20181           (C->getSExtValue() <= 0x7fffffffLL))
20182         weight = CW_Constant;
20183     }
20184     break;
20185   case 'Z':
20186     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20187       if (C->getZExtValue() <= 0xffffffff)
20188         weight = CW_Constant;
20189     }
20190     break;
20191   }
20192   return weight;
20193 }
20194
20195 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20196 /// with another that has more specific requirements based on the type of the
20197 /// corresponding operand.
20198 const char *X86TargetLowering::
20199 LowerXConstraint(EVT ConstraintVT) const {
20200   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20201   // 'f' like normal targets.
20202   if (ConstraintVT.isFloatingPoint()) {
20203     if (Subtarget->hasSSE2())
20204       return "Y";
20205     if (Subtarget->hasSSE1())
20206       return "x";
20207   }
20208
20209   return TargetLowering::LowerXConstraint(ConstraintVT);
20210 }
20211
20212 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20213 /// vector.  If it is invalid, don't add anything to Ops.
20214 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20215                                                      std::string &Constraint,
20216                                                      std::vector<SDValue>&Ops,
20217                                                      SelectionDAG &DAG) const {
20218   SDValue Result(0, 0);
20219
20220   // Only support length 1 constraints for now.
20221   if (Constraint.length() > 1) return;
20222
20223   char ConstraintLetter = Constraint[0];
20224   switch (ConstraintLetter) {
20225   default: break;
20226   case 'I':
20227     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20228       if (C->getZExtValue() <= 31) {
20229         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20230         break;
20231       }
20232     }
20233     return;
20234   case 'J':
20235     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20236       if (C->getZExtValue() <= 63) {
20237         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20238         break;
20239       }
20240     }
20241     return;
20242   case 'K':
20243     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20244       if (isInt<8>(C->getSExtValue())) {
20245         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20246         break;
20247       }
20248     }
20249     return;
20250   case 'N':
20251     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20252       if (C->getZExtValue() <= 255) {
20253         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20254         break;
20255       }
20256     }
20257     return;
20258   case 'e': {
20259     // 32-bit signed value
20260     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20261       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20262                                            C->getSExtValue())) {
20263         // Widen to 64 bits here to get it sign extended.
20264         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20265         break;
20266       }
20267     // FIXME gcc accepts some relocatable values here too, but only in certain
20268     // memory models; it's complicated.
20269     }
20270     return;
20271   }
20272   case 'Z': {
20273     // 32-bit unsigned value
20274     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20275       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20276                                            C->getZExtValue())) {
20277         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20278         break;
20279       }
20280     }
20281     // FIXME gcc accepts some relocatable values here too, but only in certain
20282     // memory models; it's complicated.
20283     return;
20284   }
20285   case 'i': {
20286     // Literal immediates are always ok.
20287     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20288       // Widen to 64 bits here to get it sign extended.
20289       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20290       break;
20291     }
20292
20293     // In any sort of PIC mode addresses need to be computed at runtime by
20294     // adding in a register or some sort of table lookup.  These can't
20295     // be used as immediates.
20296     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20297       return;
20298
20299     // If we are in non-pic codegen mode, we allow the address of a global (with
20300     // an optional displacement) to be used with 'i'.
20301     GlobalAddressSDNode *GA = 0;
20302     int64_t Offset = 0;
20303
20304     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20305     while (1) {
20306       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20307         Offset += GA->getOffset();
20308         break;
20309       } else if (Op.getOpcode() == ISD::ADD) {
20310         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20311           Offset += C->getZExtValue();
20312           Op = Op.getOperand(0);
20313           continue;
20314         }
20315       } else if (Op.getOpcode() == ISD::SUB) {
20316         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20317           Offset += -C->getZExtValue();
20318           Op = Op.getOperand(0);
20319           continue;
20320         }
20321       }
20322
20323       // Otherwise, this isn't something we can handle, reject it.
20324       return;
20325     }
20326
20327     const GlobalValue *GV = GA->getGlobal();
20328     // If we require an extra load to get this address, as in PIC mode, we
20329     // can't accept it.
20330     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20331                                                         getTargetMachine())))
20332       return;
20333
20334     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20335                                         GA->getValueType(0), Offset);
20336     break;
20337   }
20338   }
20339
20340   if (Result.getNode()) {
20341     Ops.push_back(Result);
20342     return;
20343   }
20344   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20345 }
20346
20347 std::pair<unsigned, const TargetRegisterClass*>
20348 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20349                                                 MVT VT) const {
20350   // First, see if this is a constraint that directly corresponds to an LLVM
20351   // register class.
20352   if (Constraint.size() == 1) {
20353     // GCC Constraint Letters
20354     switch (Constraint[0]) {
20355     default: break;
20356       // TODO: Slight differences here in allocation order and leaving
20357       // RIP in the class. Do they matter any more here than they do
20358       // in the normal allocation?
20359     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20360       if (Subtarget->is64Bit()) {
20361         if (VT == MVT::i32 || VT == MVT::f32)
20362           return std::make_pair(0U, &X86::GR32RegClass);
20363         if (VT == MVT::i16)
20364           return std::make_pair(0U, &X86::GR16RegClass);
20365         if (VT == MVT::i8 || VT == MVT::i1)
20366           return std::make_pair(0U, &X86::GR8RegClass);
20367         if (VT == MVT::i64 || VT == MVT::f64)
20368           return std::make_pair(0U, &X86::GR64RegClass);
20369         break;
20370       }
20371       // 32-bit fallthrough
20372     case 'Q':   // Q_REGS
20373       if (VT == MVT::i32 || VT == MVT::f32)
20374         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20375       if (VT == MVT::i16)
20376         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20377       if (VT == MVT::i8 || VT == MVT::i1)
20378         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20379       if (VT == MVT::i64)
20380         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20381       break;
20382     case 'r':   // GENERAL_REGS
20383     case 'l':   // INDEX_REGS
20384       if (VT == MVT::i8 || VT == MVT::i1)
20385         return std::make_pair(0U, &X86::GR8RegClass);
20386       if (VT == MVT::i16)
20387         return std::make_pair(0U, &X86::GR16RegClass);
20388       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20389         return std::make_pair(0U, &X86::GR32RegClass);
20390       return std::make_pair(0U, &X86::GR64RegClass);
20391     case 'R':   // LEGACY_REGS
20392       if (VT == MVT::i8 || VT == MVT::i1)
20393         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20394       if (VT == MVT::i16)
20395         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20396       if (VT == MVT::i32 || !Subtarget->is64Bit())
20397         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20398       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20399     case 'f':  // FP Stack registers.
20400       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20401       // value to the correct fpstack register class.
20402       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20403         return std::make_pair(0U, &X86::RFP32RegClass);
20404       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20405         return std::make_pair(0U, &X86::RFP64RegClass);
20406       return std::make_pair(0U, &X86::RFP80RegClass);
20407     case 'y':   // MMX_REGS if MMX allowed.
20408       if (!Subtarget->hasMMX()) break;
20409       return std::make_pair(0U, &X86::VR64RegClass);
20410     case 'Y':   // SSE_REGS if SSE2 allowed
20411       if (!Subtarget->hasSSE2()) break;
20412       // FALL THROUGH.
20413     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20414       if (!Subtarget->hasSSE1()) break;
20415
20416       switch (VT.SimpleTy) {
20417       default: break;
20418       // Scalar SSE types.
20419       case MVT::f32:
20420       case MVT::i32:
20421         return std::make_pair(0U, &X86::FR32RegClass);
20422       case MVT::f64:
20423       case MVT::i64:
20424         return std::make_pair(0U, &X86::FR64RegClass);
20425       // Vector types.
20426       case MVT::v16i8:
20427       case MVT::v8i16:
20428       case MVT::v4i32:
20429       case MVT::v2i64:
20430       case MVT::v4f32:
20431       case MVT::v2f64:
20432         return std::make_pair(0U, &X86::VR128RegClass);
20433       // AVX types.
20434       case MVT::v32i8:
20435       case MVT::v16i16:
20436       case MVT::v8i32:
20437       case MVT::v4i64:
20438       case MVT::v8f32:
20439       case MVT::v4f64:
20440         return std::make_pair(0U, &X86::VR256RegClass);
20441       case MVT::v8f64:
20442       case MVT::v16f32:
20443       case MVT::v16i32:
20444       case MVT::v8i64:
20445         return std::make_pair(0U, &X86::VR512RegClass);
20446       }
20447       break;
20448     }
20449   }
20450
20451   // Use the default implementation in TargetLowering to convert the register
20452   // constraint into a member of a register class.
20453   std::pair<unsigned, const TargetRegisterClass*> Res;
20454   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20455
20456   // Not found as a standard register?
20457   if (Res.second == 0) {
20458     // Map st(0) -> st(7) -> ST0
20459     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20460         tolower(Constraint[1]) == 's' &&
20461         tolower(Constraint[2]) == 't' &&
20462         Constraint[3] == '(' &&
20463         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20464         Constraint[5] == ')' &&
20465         Constraint[6] == '}') {
20466
20467       Res.first = X86::ST0+Constraint[4]-'0';
20468       Res.second = &X86::RFP80RegClass;
20469       return Res;
20470     }
20471
20472     // GCC allows "st(0)" to be called just plain "st".
20473     if (StringRef("{st}").equals_lower(Constraint)) {
20474       Res.first = X86::ST0;
20475       Res.second = &X86::RFP80RegClass;
20476       return Res;
20477     }
20478
20479     // flags -> EFLAGS
20480     if (StringRef("{flags}").equals_lower(Constraint)) {
20481       Res.first = X86::EFLAGS;
20482       Res.second = &X86::CCRRegClass;
20483       return Res;
20484     }
20485
20486     // 'A' means EAX + EDX.
20487     if (Constraint == "A") {
20488       Res.first = X86::EAX;
20489       Res.second = &X86::GR32_ADRegClass;
20490       return Res;
20491     }
20492     return Res;
20493   }
20494
20495   // Otherwise, check to see if this is a register class of the wrong value
20496   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20497   // turn into {ax},{dx}.
20498   if (Res.second->hasType(VT))
20499     return Res;   // Correct type already, nothing to do.
20500
20501   // All of the single-register GCC register classes map their values onto
20502   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20503   // really want an 8-bit or 32-bit register, map to the appropriate register
20504   // class and return the appropriate register.
20505   if (Res.second == &X86::GR16RegClass) {
20506     if (VT == MVT::i8 || VT == MVT::i1) {
20507       unsigned DestReg = 0;
20508       switch (Res.first) {
20509       default: break;
20510       case X86::AX: DestReg = X86::AL; break;
20511       case X86::DX: DestReg = X86::DL; break;
20512       case X86::CX: DestReg = X86::CL; break;
20513       case X86::BX: DestReg = X86::BL; break;
20514       }
20515       if (DestReg) {
20516         Res.first = DestReg;
20517         Res.second = &X86::GR8RegClass;
20518       }
20519     } else if (VT == MVT::i32 || VT == MVT::f32) {
20520       unsigned DestReg = 0;
20521       switch (Res.first) {
20522       default: break;
20523       case X86::AX: DestReg = X86::EAX; break;
20524       case X86::DX: DestReg = X86::EDX; break;
20525       case X86::CX: DestReg = X86::ECX; break;
20526       case X86::BX: DestReg = X86::EBX; break;
20527       case X86::SI: DestReg = X86::ESI; break;
20528       case X86::DI: DestReg = X86::EDI; break;
20529       case X86::BP: DestReg = X86::EBP; break;
20530       case X86::SP: DestReg = X86::ESP; break;
20531       }
20532       if (DestReg) {
20533         Res.first = DestReg;
20534         Res.second = &X86::GR32RegClass;
20535       }
20536     } else if (VT == MVT::i64 || VT == MVT::f64) {
20537       unsigned DestReg = 0;
20538       switch (Res.first) {
20539       default: break;
20540       case X86::AX: DestReg = X86::RAX; break;
20541       case X86::DX: DestReg = X86::RDX; break;
20542       case X86::CX: DestReg = X86::RCX; break;
20543       case X86::BX: DestReg = X86::RBX; break;
20544       case X86::SI: DestReg = X86::RSI; break;
20545       case X86::DI: DestReg = X86::RDI; break;
20546       case X86::BP: DestReg = X86::RBP; break;
20547       case X86::SP: DestReg = X86::RSP; break;
20548       }
20549       if (DestReg) {
20550         Res.first = DestReg;
20551         Res.second = &X86::GR64RegClass;
20552       }
20553     }
20554   } else if (Res.second == &X86::FR32RegClass ||
20555              Res.second == &X86::FR64RegClass ||
20556              Res.second == &X86::VR128RegClass ||
20557              Res.second == &X86::VR256RegClass ||
20558              Res.second == &X86::FR32XRegClass ||
20559              Res.second == &X86::FR64XRegClass ||
20560              Res.second == &X86::VR128XRegClass ||
20561              Res.second == &X86::VR256XRegClass ||
20562              Res.second == &X86::VR512RegClass) {
20563     // Handle references to XMM physical registers that got mapped into the
20564     // wrong class.  This can happen with constraints like {xmm0} where the
20565     // target independent register mapper will just pick the first match it can
20566     // find, ignoring the required type.
20567
20568     if (VT == MVT::f32 || VT == MVT::i32)
20569       Res.second = &X86::FR32RegClass;
20570     else if (VT == MVT::f64 || VT == MVT::i64)
20571       Res.second = &X86::FR64RegClass;
20572     else if (X86::VR128RegClass.hasType(VT))
20573       Res.second = &X86::VR128RegClass;
20574     else if (X86::VR256RegClass.hasType(VT))
20575       Res.second = &X86::VR256RegClass;
20576     else if (X86::VR512RegClass.hasType(VT))
20577       Res.second = &X86::VR512RegClass;
20578   }
20579
20580   return Res;
20581 }