Implement inalloca codegen for x86 with the new inalloca design
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86CallingConv.h"
20 #include "X86InstrBuilder.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetWindows())
193     return new X86WindowsTargetObjectFile();
194   if (Subtarget->isTargetCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(TM)) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird, it always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit since we have so many registers use the ILP scheduler, for
234   // 32-bit code use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2
247   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248     addBypassSlowDiv(32, 8);
249     if (Subtarget->is64Bit())
250       addBypassSlowDiv(64, 16);
251   }
252
253   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
254     // Setup Windows compiler runtime calls.
255     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257     setLibcallName(RTLIB::SREM_I64, "_allrem");
258     setLibcallName(RTLIB::UREM_I64, "_aullrem");
259     setLibcallName(RTLIB::MUL_I64, "_allmul");
260     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265
266     // The _ftol2 runtime function has an unusual calling conv, which
267     // is modeled by a special pseudo-instruction.
268     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
272   }
273
274   if (Subtarget->isTargetDarwin()) {
275     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276     setUseUnderscoreSetJmp(false);
277     setUseUnderscoreLongJmp(false);
278   } else if (Subtarget->isTargetMingw()) {
279     // MS runtime is weird: it exports _setjmp, but longjmp!
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(false);
282   } else {
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(true);
285   }
286
287   // Set up the register classes.
288   addRegisterClass(MVT::i8, &X86::GR8RegClass);
289   addRegisterClass(MVT::i16, &X86::GR16RegClass);
290   addRegisterClass(MVT::i32, &X86::GR32RegClass);
291   if (Subtarget->is64Bit())
292     addRegisterClass(MVT::i64, &X86::GR64RegClass);
293
294   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295
296   // We don't accept any truncstore of integer registers.
297   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
303
304   // SETOEQ and SETUNE require checking two conditions.
305   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311
312   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313   // operation.
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
321   } else if (!TM.Options.UseSoftFloat) {
322     // We have an algorithm for SSE2->double, and we turn this into a
323     // 64-bit FILD followed by conditional FADD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
325     // We have an algorithm for SSE2, and we turn this into a 64-bit
326     // FILD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
328   }
329
330   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331   // this operation.
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
334
335   if (!TM.Options.UseSoftFloat) {
336     // SSE has no i16 to fp conversion, only i32
337     if (X86ScalarSSEf32) {
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
339       // f32 and f64 cases are Legal, f80 case is not
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     } else {
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     }
345   } else {
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
348   }
349
350   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
351   // are Legal, f80 is custom lowered.
352   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
353   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
354
355   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
359
360   if (X86ScalarSSEf32) {
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
362     // f32 and f64 cases are Legal, f80 case is not
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   } else {
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   }
368
369   // Handle FP_TO_UINT by promoting the destination to a larger signed
370   // conversion.
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
374
375   if (Subtarget->is64Bit()) {
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
378   } else if (!TM.Options.UseSoftFloat) {
379     // Since AVX is a superset of SSE3, only check for SSE here.
380     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381       // Expand FP_TO_UINT into a select.
382       // FIXME: We would like to use a Custom expander here eventually to do
383       // the optimal thing for SSE vs. the default expansion in the legalizer.
384       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
385     else
386       // With SSE3 we can use fisttpll to convert to a signed i64; without
387       // SSE, we're stuck with a fistpll.
388       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
389   }
390
391   if (isTargetFTOL()) {
392     // Use the _ftol2 runtime function, which has a pseudo-instruction
393     // to handle its weird calling convention.
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
395   }
396
397   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398   if (!X86ScalarSSEf64) {
399     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
400     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
401     if (Subtarget->is64Bit()) {
402       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
403       // Without SSE, i64->f64 goes through memory.
404       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
405     }
406   }
407
408   // Scalar integer divide and remainder are lowered to use operations that
409   // produce two results, to match the available instructions. This exposes
410   // the two-result form to trivial CSE, which is able to combine x/y and x%y
411   // into a single instruction.
412   //
413   // Scalar integer multiply-high is also lowered to use two-result
414   // operations, to match the available instructions. However, plain multiply
415   // (low) operations are left as Legal, as there are single-result
416   // instructions for this in x86. Using the two-result multiply instructions
417   // when both high and low results are needed must be arranged by dagcombine.
418   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419     MVT VT = IntVTs[i];
420     setOperationAction(ISD::MULHS, VT, Expand);
421     setOperationAction(ISD::MULHU, VT, Expand);
422     setOperationAction(ISD::SDIV, VT, Expand);
423     setOperationAction(ISD::UDIV, VT, Expand);
424     setOperationAction(ISD::SREM, VT, Expand);
425     setOperationAction(ISD::UREM, VT, Expand);
426
427     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428     setOperationAction(ISD::ADDC, VT, Custom);
429     setOperationAction(ISD::ADDE, VT, Custom);
430     setOperationAction(ISD::SUBC, VT, Custom);
431     setOperationAction(ISD::SUBE, VT, Custom);
432   }
433
434   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
435   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
436   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
443   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
444   if (Subtarget->is64Bit())
445     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
449   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
453   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
454
455   // Promote the i8 variants and force them on up to i32 which has a shorter
456   // encoding.
457   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
459   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
460   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
461   if (Subtarget->hasBMI()) {
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
466   } else {
467     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
468     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
469     if (Subtarget->is64Bit())
470       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasLZCNT()) {
474     // When promoting the i8 variants, force them to i32 for a shorter
475     // encoding.
476     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
479     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
482     if (Subtarget->is64Bit())
483       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
484   } else {
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
491     if (Subtarget->is64Bit()) {
492       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
493       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
494     }
495   }
496
497   if (Subtarget->hasPOPCNT()) {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
499   } else {
500     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
505   }
506
507   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
508   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
509
510   // These should be promoted to a larger select which is supported.
511   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
512   // X86 wants to expand cmov itself.
513   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
514   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
520   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
525   if (Subtarget->is64Bit()) {
526     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
527     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
528   }
529   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
530   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
531   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
532   // support continuation, user-level threading, and etc.. As a result, no
533   // other SjLj exception interfaces are implemented and please don't build
534   // your own exception handling based on them.
535   // LLVM/Clang supports zero-cost DWARF exception handling.
536   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
537   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
538
539   // Darwin ABI issue.
540   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
541   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
542   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
543   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
544   if (Subtarget->is64Bit())
545     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
546   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
547   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
548   if (Subtarget->is64Bit()) {
549     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
550     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
551     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
552     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
553     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
554   }
555   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
556   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
557   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
558   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
559   if (Subtarget->is64Bit()) {
560     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
561     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
562     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
563   }
564
565   if (Subtarget->hasSSE1())
566     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
567
568   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
569
570   // Expand certain atomics
571   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
572     MVT VT = IntVTs[i];
573     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
574     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
575     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
576   }
577
578   if (!Subtarget->is64Bit()) {
579     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
591   }
592
593   if (Subtarget->hasCmpxchg16b()) {
594     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
595   }
596
597   // FIXME - use subtarget debug flags
598   if (!Subtarget->isTargetDarwin() &&
599       !Subtarget->isTargetELF() &&
600       !Subtarget->isTargetCygMing()) {
601     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
602   }
603
604   if (Subtarget->is64Bit()) {
605     setExceptionPointerRegister(X86::RAX);
606     setExceptionSelectorRegister(X86::RDX);
607   } else {
608     setExceptionPointerRegister(X86::EAX);
609     setExceptionSelectorRegister(X86::EDX);
610   }
611   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
612   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
613
614   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
615   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
616
617   setOperationAction(ISD::TRAP, MVT::Other, Legal);
618   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
619
620   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
621   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
622   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
623   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
624     // TargetInfo::X86_64ABIBuiltinVaList
625     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
626     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
627   } else {
628     // TargetInfo::CharPtrBuiltinVaList
629     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
630     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
631   }
632
633   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
634   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
635
636   if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
637     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
638                        MVT::i64 : MVT::i32, Custom);
639   else if (TM.Options.EnableSegmentedStacks)
640     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
641                        MVT::i64 : MVT::i32, Custom);
642   else
643     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
644                        MVT::i64 : MVT::i32, Expand);
645
646   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
647     // f32 and f64 use SSE.
648     // Set up the FP register classes.
649     addRegisterClass(MVT::f32, &X86::FR32RegClass);
650     addRegisterClass(MVT::f64, &X86::FR64RegClass);
651
652     // Use ANDPD to simulate FABS.
653     setOperationAction(ISD::FABS , MVT::f64, Custom);
654     setOperationAction(ISD::FABS , MVT::f32, Custom);
655
656     // Use XORP to simulate FNEG.
657     setOperationAction(ISD::FNEG , MVT::f64, Custom);
658     setOperationAction(ISD::FNEG , MVT::f32, Custom);
659
660     // Use ANDPD and ORPD to simulate FCOPYSIGN.
661     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
662     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
663
664     // Lower this to FGETSIGNx86 plus an AND.
665     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
666     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
667
668     // We don't support sin/cos/fmod
669     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
670     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
671     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
672     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
673     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
674     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
675
676     // Expand FP immediates into loads from the stack, except for the special
677     // cases we handle.
678     addLegalFPImmediate(APFloat(+0.0)); // xorpd
679     addLegalFPImmediate(APFloat(+0.0f)); // xorps
680   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
681     // Use SSE for f32, x87 for f64.
682     // Set up the FP register classes.
683     addRegisterClass(MVT::f32, &X86::FR32RegClass);
684     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
685
686     // Use ANDPS to simulate FABS.
687     setOperationAction(ISD::FABS , MVT::f32, Custom);
688
689     // Use XORP to simulate FNEG.
690     setOperationAction(ISD::FNEG , MVT::f32, Custom);
691
692     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
693
694     // Use ANDPS and ORPS to simulate FCOPYSIGN.
695     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
696     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
697
698     // We don't support sin/cos/fmod
699     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
700     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
701     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
702
703     // Special cases we handle for FP constants.
704     addLegalFPImmediate(APFloat(+0.0f)); // xorps
705     addLegalFPImmediate(APFloat(+0.0)); // FLD0
706     addLegalFPImmediate(APFloat(+1.0)); // FLD1
707     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
708     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
709
710     if (!TM.Options.UnsafeFPMath) {
711       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
712       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
713       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714     }
715   } else if (!TM.Options.UseSoftFloat) {
716     // f32 and f64 in x87.
717     // Set up the FP register classes.
718     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
719     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
720
721     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
722     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
723     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
724     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
725
726     if (!TM.Options.UnsafeFPMath) {
727       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
728       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
729       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
733     }
734     addLegalFPImmediate(APFloat(+0.0)); // FLD0
735     addLegalFPImmediate(APFloat(+1.0)); // FLD1
736     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
737     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
738     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
739     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
740     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
741     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
742   }
743
744   // We don't support FMA.
745   setOperationAction(ISD::FMA, MVT::f64, Expand);
746   setOperationAction(ISD::FMA, MVT::f32, Expand);
747
748   // Long double always uses X87.
749   if (!TM.Options.UseSoftFloat) {
750     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
751     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
752     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
753     {
754       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
755       addLegalFPImmediate(TmpFlt);  // FLD0
756       TmpFlt.changeSign();
757       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
758
759       bool ignored;
760       APFloat TmpFlt2(+1.0);
761       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
762                       &ignored);
763       addLegalFPImmediate(TmpFlt2);  // FLD1
764       TmpFlt2.changeSign();
765       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
766     }
767
768     if (!TM.Options.UnsafeFPMath) {
769       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
770       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
771       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
772     }
773
774     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
775     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
776     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
777     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
778     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
779     setOperationAction(ISD::FMA, MVT::f80, Expand);
780   }
781
782   // Always use a library call for pow.
783   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
784   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
785   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
786
787   setOperationAction(ISD::FLOG, MVT::f80, Expand);
788   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
789   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
790   setOperationAction(ISD::FEXP, MVT::f80, Expand);
791   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
792
793   // First set operation action for all vector types to either promote
794   // (for widening) or expand (for scalarization). Then we will selectively
795   // turn on ones that can be effectively codegen'd.
796   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
797            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
798     MVT VT = (MVT::SimpleValueType)i;
799     setOperationAction(ISD::ADD , VT, Expand);
800     setOperationAction(ISD::SUB , VT, Expand);
801     setOperationAction(ISD::FADD, VT, Expand);
802     setOperationAction(ISD::FNEG, VT, Expand);
803     setOperationAction(ISD::FSUB, VT, Expand);
804     setOperationAction(ISD::MUL , VT, Expand);
805     setOperationAction(ISD::FMUL, VT, Expand);
806     setOperationAction(ISD::SDIV, VT, Expand);
807     setOperationAction(ISD::UDIV, VT, Expand);
808     setOperationAction(ISD::FDIV, VT, Expand);
809     setOperationAction(ISD::SREM, VT, Expand);
810     setOperationAction(ISD::UREM, VT, Expand);
811     setOperationAction(ISD::LOAD, VT, Expand);
812     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
813     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
814     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
815     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
816     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
817     setOperationAction(ISD::FABS, VT, Expand);
818     setOperationAction(ISD::FSIN, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FCOS, VT, Expand);
821     setOperationAction(ISD::FSINCOS, VT, Expand);
822     setOperationAction(ISD::FREM, VT, Expand);
823     setOperationAction(ISD::FMA,  VT, Expand);
824     setOperationAction(ISD::FPOWI, VT, Expand);
825     setOperationAction(ISD::FSQRT, VT, Expand);
826     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
827     setOperationAction(ISD::FFLOOR, VT, Expand);
828     setOperationAction(ISD::FCEIL, VT, Expand);
829     setOperationAction(ISD::FTRUNC, VT, Expand);
830     setOperationAction(ISD::FRINT, VT, Expand);
831     setOperationAction(ISD::FNEARBYINT, VT, Expand);
832     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
834     setOperationAction(ISD::SDIVREM, VT, Expand);
835     setOperationAction(ISD::UDIVREM, VT, Expand);
836     setOperationAction(ISD::FPOW, VT, Expand);
837     setOperationAction(ISD::CTPOP, VT, Expand);
838     setOperationAction(ISD::CTTZ, VT, Expand);
839     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::CTLZ, VT, Expand);
841     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::SHL, VT, Expand);
843     setOperationAction(ISD::SRA, VT, Expand);
844     setOperationAction(ISD::SRL, VT, Expand);
845     setOperationAction(ISD::ROTL, VT, Expand);
846     setOperationAction(ISD::ROTR, VT, Expand);
847     setOperationAction(ISD::BSWAP, VT, Expand);
848     setOperationAction(ISD::SETCC, VT, Expand);
849     setOperationAction(ISD::FLOG, VT, Expand);
850     setOperationAction(ISD::FLOG2, VT, Expand);
851     setOperationAction(ISD::FLOG10, VT, Expand);
852     setOperationAction(ISD::FEXP, VT, Expand);
853     setOperationAction(ISD::FEXP2, VT, Expand);
854     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859     setOperationAction(ISD::TRUNCATE, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863     setOperationAction(ISD::VSELECT, VT, Expand);
864     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866       setTruncStoreAction(VT,
867                           (MVT::SimpleValueType)InnerVT, Expand);
868     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871   }
872
873   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874   // with -msoft-float, disable use of MMX as well.
875   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877     // No operations on x86mmx supported, everything uses intrinsics.
878   }
879
880   // MMX-sized vectors (other than x86mmx) are expected to be expanded
881   // into smaller operations.
882   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
883   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
885   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
886   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
887   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
888   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
889   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
890   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
891   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
892   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
893   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
894   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
895   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
896   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
897   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
902   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
904   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
906   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
911
912   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914
915     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
920     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
921     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
922     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
924     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
925     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
927   }
928
929   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931
932     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933     // registers cannot be used even for integer operations.
934     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938
939     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
940     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
941     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
942     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
943     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
944     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
945     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
946     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
947     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
948     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
949     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
950     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
955     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
956     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
957
958     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
962
963     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
964     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
968
969     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
970     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
971       MVT VT = (MVT::SimpleValueType)i;
972       // Do not attempt to custom lower non-power-of-2 vectors
973       if (!isPowerOf2_32(VT.getVectorNumElements()))
974         continue;
975       // Do not attempt to custom lower non-128-bit vectors
976       if (!VT.is128BitVector())
977         continue;
978       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
979       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
980       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
981     }
982
983     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
985     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
986     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
988     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
989
990     if (Subtarget->is64Bit()) {
991       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
992       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
993     }
994
995     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
996     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
997       MVT VT = (MVT::SimpleValueType)i;
998
999       // Do not attempt to promote non-128-bit vectors
1000       if (!VT.is128BitVector())
1001         continue;
1002
1003       setOperationAction(ISD::AND,    VT, Promote);
1004       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1005       setOperationAction(ISD::OR,     VT, Promote);
1006       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1007       setOperationAction(ISD::XOR,    VT, Promote);
1008       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1009       setOperationAction(ISD::LOAD,   VT, Promote);
1010       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1011       setOperationAction(ISD::SELECT, VT, Promote);
1012       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1013     }
1014
1015     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1016
1017     // Custom lower v2i64 and v2f64 selects.
1018     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1019     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1020     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1021     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1022
1023     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1024     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1025
1026     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1028     // As there is no 64-bit GPR available, we need build a special custom
1029     // sequence to convert from v2i32 to v2f32.
1030     if (!Subtarget->is64Bit())
1031       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1032
1033     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1034     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1035
1036     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1037   }
1038
1039   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1040     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1041     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1042     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1043     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1044     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1045     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1046     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1047     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1048     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1049     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1050
1051     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1052     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1053     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1054     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1055     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1061
1062     // FIXME: Do we need to handle scalar-to-vector here?
1063     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1064
1065     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1069     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1070
1071     // i8 and i16 vectors are custom , because the source register and source
1072     // source memory operand types are not the same width.  f32 vectors are
1073     // custom since the immediate controlling the insert encodes additional
1074     // information.
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1079
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1084
1085     // FIXME: these should be Legal but thats only for the case where
1086     // the index is constant.  For now custom expand to deal with that.
1087     if (Subtarget->is64Bit()) {
1088       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1089       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1090     }
1091   }
1092
1093   if (Subtarget->hasSSE2()) {
1094     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1095     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1096
1097     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1098     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1099
1100     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1101     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1102
1103     // In the customized shift lowering, the legal cases in AVX2 will be
1104     // recognized.
1105     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1106     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1107
1108     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1109     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1112
1113     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1114     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1115   }
1116
1117   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1118     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1120     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1123     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1124
1125     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1126     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1127     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1128
1129     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1133     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1137     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1138     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1139     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1140     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1141
1142     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1150     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1151     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1152     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1153     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1154
1155     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1156
1157     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1160     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1161
1162     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1163     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1164
1165     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1166
1167     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1168     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1169
1170     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1171     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1172
1173     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1174     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1175
1176     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1177
1178     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1182
1183     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1185     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1186
1187     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1191
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1203     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1204
1205     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1206       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1212     }
1213
1214     if (Subtarget->hasInt256()) {
1215       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1218       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1219
1220       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1223       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1224
1225       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1227       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1228       // Don't lower v32i8 because there is no 128-bit byte mul
1229
1230       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1231
1232       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1233     } else {
1234       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1236       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1237       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1238
1239       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1241       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1242       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1243
1244       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1245       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1246       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1247       // Don't lower v32i8 because there is no 128-bit byte mul
1248     }
1249
1250     // In the customized shift lowering, the legal cases in AVX2 will be
1251     // recognized.
1252     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1253     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1254
1255     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1256     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1257
1258     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1259
1260     // Custom lower several nodes for 256-bit types.
1261     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1262              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1263       MVT VT = (MVT::SimpleValueType)i;
1264
1265       // Extract subvector is special because the value type
1266       // (result) is 128-bit but the source is 256-bit wide.
1267       if (VT.is128BitVector())
1268         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1269
1270       // Do not attempt to custom lower other non-256-bit vectors
1271       if (!VT.is256BitVector())
1272         continue;
1273
1274       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1275       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1276       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1277       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1278       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1279       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1280       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1281     }
1282
1283     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1284     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1285       MVT VT = (MVT::SimpleValueType)i;
1286
1287       // Do not attempt to promote non-256-bit vectors
1288       if (!VT.is256BitVector())
1289         continue;
1290
1291       setOperationAction(ISD::AND,    VT, Promote);
1292       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1293       setOperationAction(ISD::OR,     VT, Promote);
1294       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1295       setOperationAction(ISD::XOR,    VT, Promote);
1296       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1297       setOperationAction(ISD::LOAD,   VT, Promote);
1298       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1299       setOperationAction(ISD::SELECT, VT, Promote);
1300       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1301     }
1302   }
1303
1304   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1305     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1308     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1309
1310     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1311     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1312     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1313
1314     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1315     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1316     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1317     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1318     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1319     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1325
1326     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1330     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1331     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1332
1333     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1337     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1338     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1339     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1340     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1341     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1342
1343     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1344     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1345     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1347     if (Subtarget->is64Bit()) {
1348       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1349       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1350       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1351       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1352     }
1353     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1355     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1359     setOperationAction(ISD::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::BUILD_VECTOR,       MVT::v8i1, Custom);
1391     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1392     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1393     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1394     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1395
1396     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1397     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1398
1399     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1400     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1403
1404     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1405     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1406
1407     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1408     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1409
1410     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1414     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1415     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1416     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1417     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1418     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1419
1420     // Custom lower several nodes.
1421     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1422              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1423       MVT VT = (MVT::SimpleValueType)i;
1424
1425       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1426       // Extract subvector is special because the value type
1427       // (result) is 256/128-bit but the source is 512-bit wide.
1428       if (VT.is128BitVector() || VT.is256BitVector())
1429         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1430
1431       if (VT.getVectorElementType() == MVT::i1)
1432         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1433
1434       // Do not attempt to custom lower other non-512-bit vectors
1435       if (!VT.is512BitVector())
1436         continue;
1437
1438       if ( EltSize >= 32) {
1439         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1440         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1441         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1442         setOperationAction(ISD::VSELECT,             VT, Legal);
1443         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1444         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1445         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1446       }
1447     }
1448     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1449       MVT VT = (MVT::SimpleValueType)i;
1450
1451       // Do not attempt to promote non-256-bit vectors
1452       if (!VT.is512BitVector())
1453         continue;
1454
1455       setOperationAction(ISD::SELECT, VT, Promote);
1456       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1457     }
1458   }// has  AVX-512
1459
1460   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1461   // of this type with custom code.
1462   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1463            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1464     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1465                        Custom);
1466   }
1467
1468   // We want to custom lower some of our intrinsics.
1469   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1470   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1471   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1472
1473   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1474   // handle type legalization for these operations here.
1475   //
1476   // FIXME: We really should do custom legalization for addition and
1477   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1478   // than generic legalization for 64-bit multiplication-with-overflow, though.
1479   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1480     // Add/Sub/Mul with overflow operations are custom lowered.
1481     MVT VT = IntVTs[i];
1482     setOperationAction(ISD::SADDO, VT, Custom);
1483     setOperationAction(ISD::UADDO, VT, Custom);
1484     setOperationAction(ISD::SSUBO, VT, Custom);
1485     setOperationAction(ISD::USUBO, VT, Custom);
1486     setOperationAction(ISD::SMULO, VT, Custom);
1487     setOperationAction(ISD::UMULO, VT, Custom);
1488   }
1489
1490   // There are no 8-bit 3-address imul/mul instructions
1491   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1492   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1493
1494   if (!Subtarget->is64Bit()) {
1495     // These libcalls are not available in 32-bit.
1496     setLibcallName(RTLIB::SHL_I128, 0);
1497     setLibcallName(RTLIB::SRL_I128, 0);
1498     setLibcallName(RTLIB::SRA_I128, 0);
1499   }
1500
1501   // Combine sin / cos into one node or libcall if possible.
1502   if (Subtarget->hasSinCos()) {
1503     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1504     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1505     if (Subtarget->isTargetDarwin()) {
1506       // For MacOSX, we don't want to the normal expansion of a libcall to
1507       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1508       // traffic.
1509       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1510       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1511     }
1512   }
1513
1514   // We have target-specific dag combine patterns for the following nodes:
1515   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1516   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1517   setTargetDAGCombine(ISD::VSELECT);
1518   setTargetDAGCombine(ISD::SELECT);
1519   setTargetDAGCombine(ISD::SHL);
1520   setTargetDAGCombine(ISD::SRA);
1521   setTargetDAGCombine(ISD::SRL);
1522   setTargetDAGCombine(ISD::OR);
1523   setTargetDAGCombine(ISD::AND);
1524   setTargetDAGCombine(ISD::ADD);
1525   setTargetDAGCombine(ISD::FADD);
1526   setTargetDAGCombine(ISD::FSUB);
1527   setTargetDAGCombine(ISD::FMA);
1528   setTargetDAGCombine(ISD::SUB);
1529   setTargetDAGCombine(ISD::LOAD);
1530   setTargetDAGCombine(ISD::STORE);
1531   setTargetDAGCombine(ISD::ZERO_EXTEND);
1532   setTargetDAGCombine(ISD::ANY_EXTEND);
1533   setTargetDAGCombine(ISD::SIGN_EXTEND);
1534   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1535   setTargetDAGCombine(ISD::TRUNCATE);
1536   setTargetDAGCombine(ISD::SINT_TO_FP);
1537   setTargetDAGCombine(ISD::SETCC);
1538   if (Subtarget->is64Bit())
1539     setTargetDAGCombine(ISD::MUL);
1540   setTargetDAGCombine(ISD::XOR);
1541
1542   computeRegisterProperties();
1543
1544   // On Darwin, -Os means optimize for size without hurting performance,
1545   // do not reduce the limit.
1546   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1547   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1548   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1549   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1550   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1551   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1552   setPrefLoopAlignment(4); // 2^4 bytes.
1553
1554   // Predictable cmov don't hurt on atom because it's in-order.
1555   PredictableSelectIsExpensive = !Subtarget->isAtom();
1556
1557   setPrefFunctionAlignment(4); // 2^4 bytes.
1558 }
1559
1560 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1561   if (!VT.isVector())
1562     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1563
1564   if (Subtarget->hasAVX512())
1565     switch(VT.getVectorNumElements()) {
1566     case  8: return MVT::v8i1;
1567     case 16: return MVT::v16i1;
1568   }
1569
1570   return VT.changeVectorElementTypeToInteger();
1571 }
1572
1573 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1574 /// the desired ByVal argument alignment.
1575 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1576   if (MaxAlign == 16)
1577     return;
1578   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1579     if (VTy->getBitWidth() == 128)
1580       MaxAlign = 16;
1581   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1582     unsigned EltAlign = 0;
1583     getMaxByValAlign(ATy->getElementType(), EltAlign);
1584     if (EltAlign > MaxAlign)
1585       MaxAlign = EltAlign;
1586   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1587     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1588       unsigned EltAlign = 0;
1589       getMaxByValAlign(STy->getElementType(i), EltAlign);
1590       if (EltAlign > MaxAlign)
1591         MaxAlign = EltAlign;
1592       if (MaxAlign == 16)
1593         break;
1594     }
1595   }
1596 }
1597
1598 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1599 /// function arguments in the caller parameter area. For X86, aggregates
1600 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1601 /// are at 4-byte boundaries.
1602 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1603   if (Subtarget->is64Bit()) {
1604     // Max of 8 and alignment of type.
1605     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1606     if (TyAlign > 8)
1607       return TyAlign;
1608     return 8;
1609   }
1610
1611   unsigned Align = 4;
1612   if (Subtarget->hasSSE1())
1613     getMaxByValAlign(Ty, Align);
1614   return Align;
1615 }
1616
1617 /// getOptimalMemOpType - Returns the target specific optimal type for load
1618 /// and store operations as a result of memset, memcpy, and memmove
1619 /// lowering. If DstAlign is zero that means it's safe to destination
1620 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1621 /// means there isn't a need to check it against alignment requirement,
1622 /// probably because the source does not need to be loaded. If 'IsMemset' is
1623 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1624 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1625 /// source is constant so it does not need to be loaded.
1626 /// It returns EVT::Other if the type should be determined using generic
1627 /// target-independent logic.
1628 EVT
1629 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1630                                        unsigned DstAlign, unsigned SrcAlign,
1631                                        bool IsMemset, bool ZeroMemset,
1632                                        bool MemcpyStrSrc,
1633                                        MachineFunction &MF) const {
1634   const Function *F = MF.getFunction();
1635   if ((!IsMemset || ZeroMemset) &&
1636       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1637                                        Attribute::NoImplicitFloat)) {
1638     if (Size >= 16 &&
1639         (Subtarget->isUnalignedMemAccessFast() ||
1640          ((DstAlign == 0 || DstAlign >= 16) &&
1641           (SrcAlign == 0 || SrcAlign >= 16)))) {
1642       if (Size >= 32) {
1643         if (Subtarget->hasInt256())
1644           return MVT::v8i32;
1645         if (Subtarget->hasFp256())
1646           return MVT::v8f32;
1647       }
1648       if (Subtarget->hasSSE2())
1649         return MVT::v4i32;
1650       if (Subtarget->hasSSE1())
1651         return MVT::v4f32;
1652     } else if (!MemcpyStrSrc && Size >= 8 &&
1653                !Subtarget->is64Bit() &&
1654                Subtarget->hasSSE2()) {
1655       // Do not use f64 to lower memcpy if source is string constant. It's
1656       // better to use i32 to avoid the loads.
1657       return MVT::f64;
1658     }
1659   }
1660   if (Subtarget->is64Bit() && Size >= 8)
1661     return MVT::i64;
1662   return MVT::i32;
1663 }
1664
1665 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1666   if (VT == MVT::f32)
1667     return X86ScalarSSEf32;
1668   else if (VT == MVT::f64)
1669     return X86ScalarSSEf64;
1670   return true;
1671 }
1672
1673 bool
1674 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1675   if (Fast)
1676     *Fast = Subtarget->isUnalignedMemAccessFast();
1677   return true;
1678 }
1679
1680 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1681 /// current function.  The returned value is a member of the
1682 /// MachineJumpTableInfo::JTEntryKind enum.
1683 unsigned X86TargetLowering::getJumpTableEncoding() const {
1684   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1685   // symbol.
1686   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1687       Subtarget->isPICStyleGOT())
1688     return MachineJumpTableInfo::EK_Custom32;
1689
1690   // Otherwise, use the normal jump table encoding heuristics.
1691   return TargetLowering::getJumpTableEncoding();
1692 }
1693
1694 const MCExpr *
1695 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1696                                              const MachineBasicBlock *MBB,
1697                                              unsigned uid,MCContext &Ctx) const{
1698   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1699          Subtarget->isPICStyleGOT());
1700   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1701   // entries.
1702   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1703                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1704 }
1705
1706 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1707 /// jumptable.
1708 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1709                                                     SelectionDAG &DAG) const {
1710   if (!Subtarget->is64Bit())
1711     // This doesn't have SDLoc associated with it, but is not really the
1712     // same as a Register.
1713     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1714   return Table;
1715 }
1716
1717 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1718 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1719 /// MCExpr.
1720 const MCExpr *X86TargetLowering::
1721 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1722                              MCContext &Ctx) const {
1723   // X86-64 uses RIP relative addressing based on the jump table label.
1724   if (Subtarget->isPICStyleRIPRel())
1725     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1726
1727   // Otherwise, the reference is relative to the PIC base.
1728   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1729 }
1730
1731 // FIXME: Why this routine is here? Move to RegInfo!
1732 std::pair<const TargetRegisterClass*, uint8_t>
1733 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1734   const TargetRegisterClass *RRC = 0;
1735   uint8_t Cost = 1;
1736   switch (VT.SimpleTy) {
1737   default:
1738     return TargetLowering::findRepresentativeClass(VT);
1739   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1740     RRC = Subtarget->is64Bit() ?
1741       (const TargetRegisterClass*)&X86::GR64RegClass :
1742       (const TargetRegisterClass*)&X86::GR32RegClass;
1743     break;
1744   case MVT::x86mmx:
1745     RRC = &X86::VR64RegClass;
1746     break;
1747   case MVT::f32: case MVT::f64:
1748   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1749   case MVT::v4f32: case MVT::v2f64:
1750   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1751   case MVT::v4f64:
1752     RRC = &X86::VR128RegClass;
1753     break;
1754   }
1755   return std::make_pair(RRC, Cost);
1756 }
1757
1758 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1759                                                unsigned &Offset) const {
1760   if (!Subtarget->isTargetLinux())
1761     return false;
1762
1763   if (Subtarget->is64Bit()) {
1764     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1765     Offset = 0x28;
1766     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1767       AddressSpace = 256;
1768     else
1769       AddressSpace = 257;
1770   } else {
1771     // %gs:0x14 on i386
1772     Offset = 0x14;
1773     AddressSpace = 256;
1774   }
1775   return true;
1776 }
1777
1778 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1779                                             unsigned DestAS) const {
1780   assert(SrcAS != DestAS && "Expected different address spaces!");
1781
1782   return SrcAS < 256 && DestAS < 256;
1783 }
1784
1785 //===----------------------------------------------------------------------===//
1786 //               Return Value Calling Convention Implementation
1787 //===----------------------------------------------------------------------===//
1788
1789 #include "X86GenCallingConv.inc"
1790
1791 bool
1792 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1793                                   MachineFunction &MF, bool isVarArg,
1794                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1795                         LLVMContext &Context) const {
1796   SmallVector<CCValAssign, 16> RVLocs;
1797   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1798                  RVLocs, Context);
1799   return CCInfo.CheckReturn(Outs, RetCC_X86);
1800 }
1801
1802 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1803   static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1804   return ScratchRegs;
1805 }
1806
1807 SDValue
1808 X86TargetLowering::LowerReturn(SDValue Chain,
1809                                CallingConv::ID CallConv, bool isVarArg,
1810                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1811                                const SmallVectorImpl<SDValue> &OutVals,
1812                                SDLoc dl, SelectionDAG &DAG) const {
1813   MachineFunction &MF = DAG.getMachineFunction();
1814   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1815
1816   SmallVector<CCValAssign, 16> RVLocs;
1817   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1818                  RVLocs, *DAG.getContext());
1819   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1820
1821   SDValue Flag;
1822   SmallVector<SDValue, 6> RetOps;
1823   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1824   // Operand #1 = Bytes To Pop
1825   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1826                    MVT::i16));
1827
1828   // Copy the result values into the output registers.
1829   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1830     CCValAssign &VA = RVLocs[i];
1831     assert(VA.isRegLoc() && "Can only return in registers!");
1832     SDValue ValToCopy = OutVals[i];
1833     EVT ValVT = ValToCopy.getValueType();
1834
1835     // Promote values to the appropriate types
1836     if (VA.getLocInfo() == CCValAssign::SExt)
1837       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1838     else if (VA.getLocInfo() == CCValAssign::ZExt)
1839       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1840     else if (VA.getLocInfo() == CCValAssign::AExt)
1841       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1842     else if (VA.getLocInfo() == CCValAssign::BCvt)
1843       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1844
1845     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1846            "Unexpected FP-extend for return value.");  
1847
1848     // If this is x86-64, and we disabled SSE, we can't return FP values,
1849     // or SSE or MMX vectors.
1850     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1851          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1852           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1853       report_fatal_error("SSE register return with SSE disabled");
1854     }
1855     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1856     // llvm-gcc has never done it right and no one has noticed, so this
1857     // should be OK for now.
1858     if (ValVT == MVT::f64 &&
1859         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1860       report_fatal_error("SSE2 register return with SSE2 disabled");
1861
1862     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1863     // the RET instruction and handled by the FP Stackifier.
1864     if (VA.getLocReg() == X86::ST0 ||
1865         VA.getLocReg() == X86::ST1) {
1866       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1867       // change the value to the FP stack register class.
1868       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1869         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1870       RetOps.push_back(ValToCopy);
1871       // Don't emit a copytoreg.
1872       continue;
1873     }
1874
1875     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1876     // which is returned in RAX / RDX.
1877     if (Subtarget->is64Bit()) {
1878       if (ValVT == MVT::x86mmx) {
1879         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1880           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1881           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1882                                   ValToCopy);
1883           // If we don't have SSE2 available, convert to v4f32 so the generated
1884           // register is legal.
1885           if (!Subtarget->hasSSE2())
1886             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1887         }
1888       }
1889     }
1890
1891     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1892     Flag = Chain.getValue(1);
1893     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1894   }
1895
1896   // The x86-64 ABIs require that for returning structs by value we copy
1897   // the sret argument into %rax/%eax (depending on ABI) for the return.
1898   // Win32 requires us to put the sret argument to %eax as well.
1899   // We saved the argument into a virtual register in the entry block,
1900   // so now we copy the value out and into %rax/%eax.
1901   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1902       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1903     MachineFunction &MF = DAG.getMachineFunction();
1904     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1905     unsigned Reg = FuncInfo->getSRetReturnReg();
1906     assert(Reg &&
1907            "SRetReturnReg should have been set in LowerFormalArguments().");
1908     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1909
1910     unsigned RetValReg
1911         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1912           X86::RAX : X86::EAX;
1913     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1914     Flag = Chain.getValue(1);
1915
1916     // RAX/EAX now acts like a return value.
1917     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1918   }
1919
1920   RetOps[0] = Chain;  // Update chain.
1921
1922   // Add the flag if we have it.
1923   if (Flag.getNode())
1924     RetOps.push_back(Flag);
1925
1926   return DAG.getNode(X86ISD::RET_FLAG, dl,
1927                      MVT::Other, &RetOps[0], RetOps.size());
1928 }
1929
1930 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1931   if (N->getNumValues() != 1)
1932     return false;
1933   if (!N->hasNUsesOfValue(1, 0))
1934     return false;
1935
1936   SDValue TCChain = Chain;
1937   SDNode *Copy = *N->use_begin();
1938   if (Copy->getOpcode() == ISD::CopyToReg) {
1939     // If the copy has a glue operand, we conservatively assume it isn't safe to
1940     // perform a tail call.
1941     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1942       return false;
1943     TCChain = Copy->getOperand(0);
1944   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1945     return false;
1946
1947   bool HasRet = false;
1948   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1949        UI != UE; ++UI) {
1950     if (UI->getOpcode() != X86ISD::RET_FLAG)
1951       return false;
1952     HasRet = true;
1953   }
1954
1955   if (!HasRet)
1956     return false;
1957
1958   Chain = TCChain;
1959   return true;
1960 }
1961
1962 MVT
1963 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1964                                             ISD::NodeType ExtendKind) const {
1965   MVT ReturnMVT;
1966   // TODO: Is this also valid on 32-bit?
1967   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1968     ReturnMVT = MVT::i8;
1969   else
1970     ReturnMVT = MVT::i32;
1971
1972   MVT MinVT = getRegisterType(ReturnMVT);
1973   return VT.bitsLT(MinVT) ? MinVT : VT;
1974 }
1975
1976 /// LowerCallResult - Lower the result values of a call into the
1977 /// appropriate copies out of appropriate physical registers.
1978 ///
1979 SDValue
1980 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1981                                    CallingConv::ID CallConv, bool isVarArg,
1982                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1983                                    SDLoc dl, SelectionDAG &DAG,
1984                                    SmallVectorImpl<SDValue> &InVals) const {
1985
1986   // Assign locations to each value returned by this call.
1987   SmallVector<CCValAssign, 16> RVLocs;
1988   bool Is64Bit = Subtarget->is64Bit();
1989   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1990                  getTargetMachine(), RVLocs, *DAG.getContext());
1991   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1992
1993   // Copy all of the result registers out of their specified physreg.
1994   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1995     CCValAssign &VA = RVLocs[i];
1996     EVT CopyVT = VA.getValVT();
1997
1998     // If this is x86-64, and we disabled SSE, we can't return FP values
1999     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2000         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2001       report_fatal_error("SSE register return with SSE disabled");
2002     }
2003
2004     SDValue Val;
2005
2006     // If this is a call to a function that returns an fp value on the floating
2007     // point stack, we must guarantee the value is popped from the stack, so
2008     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2009     // if the return value is not used. We use the FpPOP_RETVAL instruction
2010     // instead.
2011     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2012       // If we prefer to use the value in xmm registers, copy it out as f80 and
2013       // use a truncate to move it from fp stack reg to xmm reg.
2014       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2015       SDValue Ops[] = { Chain, InFlag };
2016       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2017                                          MVT::Other, MVT::Glue, Ops), 1);
2018       Val = Chain.getValue(0);
2019
2020       // Round the f80 to the right size, which also moves it to the appropriate
2021       // xmm register.
2022       if (CopyVT != VA.getValVT())
2023         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2024                           // This truncation won't change the value.
2025                           DAG.getIntPtrConstant(1));
2026     } else {
2027       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2028                                  CopyVT, InFlag).getValue(1);
2029       Val = Chain.getValue(0);
2030     }
2031     InFlag = Chain.getValue(2);
2032     InVals.push_back(Val);
2033   }
2034
2035   return Chain;
2036 }
2037
2038 //===----------------------------------------------------------------------===//
2039 //                C & StdCall & Fast Calling Convention implementation
2040 //===----------------------------------------------------------------------===//
2041 //  StdCall calling convention seems to be standard for many Windows' API
2042 //  routines and around. It differs from C calling convention just a little:
2043 //  callee should clean up the stack, not caller. Symbols should be also
2044 //  decorated in some fancy way :) It doesn't support any vector arguments.
2045 //  For info on fast calling convention see Fast Calling Convention (tail call)
2046 //  implementation LowerX86_32FastCCCallTo.
2047
2048 /// CallIsStructReturn - Determines whether a call uses struct return
2049 /// semantics.
2050 enum StructReturnType {
2051   NotStructReturn,
2052   RegStructReturn,
2053   StackStructReturn
2054 };
2055 static StructReturnType
2056 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2057   if (Outs.empty())
2058     return NotStructReturn;
2059
2060   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2061   if (!Flags.isSRet())
2062     return NotStructReturn;
2063   if (Flags.isInReg())
2064     return RegStructReturn;
2065   return StackStructReturn;
2066 }
2067
2068 /// ArgsAreStructReturn - Determines whether a function uses struct
2069 /// return semantics.
2070 static StructReturnType
2071 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2072   if (Ins.empty())
2073     return NotStructReturn;
2074
2075   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2076   if (!Flags.isSRet())
2077     return NotStructReturn;
2078   if (Flags.isInReg())
2079     return RegStructReturn;
2080   return StackStructReturn;
2081 }
2082
2083 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2084 /// by "Src" to address "Dst" with size and alignment information specified by
2085 /// the specific parameter attribute. The copy will be passed as a byval
2086 /// function parameter.
2087 static SDValue
2088 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2089                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2090                           SDLoc dl) {
2091   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2092
2093   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2094                        /*isVolatile*/false, /*AlwaysInline=*/true,
2095                        MachinePointerInfo(), MachinePointerInfo());
2096 }
2097
2098 /// IsTailCallConvention - Return true if the calling convention is one that
2099 /// supports tail call optimization.
2100 static bool IsTailCallConvention(CallingConv::ID CC) {
2101   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2102           CC == CallingConv::HiPE);
2103 }
2104
2105 /// \brief Return true if the calling convention is a C calling convention.
2106 static bool IsCCallConvention(CallingConv::ID CC) {
2107   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2108           CC == CallingConv::X86_64_SysV);
2109 }
2110
2111 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2112   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2113     return false;
2114
2115   CallSite CS(CI);
2116   CallingConv::ID CalleeCC = CS.getCallingConv();
2117   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2118     return false;
2119
2120   return true;
2121 }
2122
2123 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2124 /// a tailcall target by changing its ABI.
2125 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2126                                    bool GuaranteedTailCallOpt) {
2127   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2128 }
2129
2130 SDValue
2131 X86TargetLowering::LowerMemArgument(SDValue Chain,
2132                                     CallingConv::ID CallConv,
2133                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2134                                     SDLoc dl, SelectionDAG &DAG,
2135                                     const CCValAssign &VA,
2136                                     MachineFrameInfo *MFI,
2137                                     unsigned i) const {
2138   // Create the nodes corresponding to a load from this parameter slot.
2139   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2140   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2141                               getTargetMachine().Options.GuaranteedTailCallOpt);
2142   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2143   EVT ValVT;
2144
2145   // If value is passed by pointer we have address passed instead of the value
2146   // itself.
2147   if (VA.getLocInfo() == CCValAssign::Indirect)
2148     ValVT = VA.getLocVT();
2149   else
2150     ValVT = VA.getValVT();
2151
2152   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2153   // changed with more analysis.
2154   // In case of tail call optimization mark all arguments mutable. Since they
2155   // could be overwritten by lowering of arguments in case of a tail call.
2156   if (Flags.isByVal()) {
2157     unsigned Bytes = Flags.getByValSize();
2158     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2159     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2160     return DAG.getFrameIndex(FI, getPointerTy());
2161   } else {
2162     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2163                                     VA.getLocMemOffset(), isImmutable);
2164     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2165     return DAG.getLoad(ValVT, dl, Chain, FIN,
2166                        MachinePointerInfo::getFixedStack(FI),
2167                        false, false, false, 0);
2168   }
2169 }
2170
2171 SDValue
2172 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2173                                         CallingConv::ID CallConv,
2174                                         bool isVarArg,
2175                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2176                                         SDLoc dl,
2177                                         SelectionDAG &DAG,
2178                                         SmallVectorImpl<SDValue> &InVals)
2179                                           const {
2180   MachineFunction &MF = DAG.getMachineFunction();
2181   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2182
2183   const Function* Fn = MF.getFunction();
2184   if (Fn->hasExternalLinkage() &&
2185       Subtarget->isTargetCygMing() &&
2186       Fn->getName() == "main")
2187     FuncInfo->setForceFramePointer(true);
2188
2189   MachineFrameInfo *MFI = MF.getFrameInfo();
2190   bool Is64Bit = Subtarget->is64Bit();
2191   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2192
2193   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2194          "Var args not supported with calling convention fastcc, ghc or hipe");
2195
2196   // Assign locations to all of the incoming arguments.
2197   SmallVector<CCValAssign, 16> ArgLocs;
2198   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2199                  ArgLocs, *DAG.getContext());
2200
2201   // Allocate shadow area for Win64
2202   if (IsWin64)
2203     CCInfo.AllocateStack(32, 8);
2204
2205   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2206
2207   unsigned LastVal = ~0U;
2208   SDValue ArgValue;
2209   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2210     CCValAssign &VA = ArgLocs[i];
2211     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2212     // places.
2213     assert(VA.getValNo() != LastVal &&
2214            "Don't support value assigned to multiple locs yet");
2215     (void)LastVal;
2216     LastVal = VA.getValNo();
2217
2218     if (VA.isRegLoc()) {
2219       EVT RegVT = VA.getLocVT();
2220       const TargetRegisterClass *RC;
2221       if (RegVT == MVT::i32)
2222         RC = &X86::GR32RegClass;
2223       else if (Is64Bit && RegVT == MVT::i64)
2224         RC = &X86::GR64RegClass;
2225       else if (RegVT == MVT::f32)
2226         RC = &X86::FR32RegClass;
2227       else if (RegVT == MVT::f64)
2228         RC = &X86::FR64RegClass;
2229       else if (RegVT.is512BitVector())
2230         RC = &X86::VR512RegClass;
2231       else if (RegVT.is256BitVector())
2232         RC = &X86::VR256RegClass;
2233       else if (RegVT.is128BitVector())
2234         RC = &X86::VR128RegClass;
2235       else if (RegVT == MVT::x86mmx)
2236         RC = &X86::VR64RegClass;
2237       else if (RegVT == MVT::i1)
2238         RC = &X86::VK1RegClass;
2239       else if (RegVT == MVT::v8i1)
2240         RC = &X86::VK8RegClass;
2241       else if (RegVT == MVT::v16i1)
2242         RC = &X86::VK16RegClass;
2243       else
2244         llvm_unreachable("Unknown argument type!");
2245
2246       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2247       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2248
2249       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2250       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2251       // right size.
2252       if (VA.getLocInfo() == CCValAssign::SExt)
2253         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2254                                DAG.getValueType(VA.getValVT()));
2255       else if (VA.getLocInfo() == CCValAssign::ZExt)
2256         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2257                                DAG.getValueType(VA.getValVT()));
2258       else if (VA.getLocInfo() == CCValAssign::BCvt)
2259         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2260
2261       if (VA.isExtInLoc()) {
2262         // Handle MMX values passed in XMM regs.
2263         if (RegVT.isVector())
2264           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2265         else
2266           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2267       }
2268     } else {
2269       assert(VA.isMemLoc());
2270       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2271     }
2272
2273     // If value is passed via pointer - do a load.
2274     if (VA.getLocInfo() == CCValAssign::Indirect)
2275       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2276                              MachinePointerInfo(), false, false, false, 0);
2277
2278     InVals.push_back(ArgValue);
2279   }
2280
2281   // The x86-64 ABIs require that for returning structs by value we copy
2282   // the sret argument into %rax/%eax (depending on ABI) for the return.
2283   // Win32 requires us to put the sret argument to %eax as well.
2284   // Save the argument into a virtual register so that we can access it
2285   // from the return points.
2286   if (MF.getFunction()->hasStructRetAttr() &&
2287       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2288     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2289     unsigned Reg = FuncInfo->getSRetReturnReg();
2290     if (!Reg) {
2291       MVT PtrTy = getPointerTy();
2292       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2293       FuncInfo->setSRetReturnReg(Reg);
2294     }
2295     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2296     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2297   }
2298
2299   unsigned StackSize = CCInfo.getNextStackOffset();
2300   // Align stack specially for tail calls.
2301   if (FuncIsMadeTailCallSafe(CallConv,
2302                              MF.getTarget().Options.GuaranteedTailCallOpt))
2303     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2304
2305   // If the function takes variable number of arguments, make a frame index for
2306   // the start of the first vararg value... for expansion of llvm.va_start.
2307   if (isVarArg) {
2308     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2309                     CallConv != CallingConv::X86_ThisCall)) {
2310       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2311     }
2312     if (Is64Bit) {
2313       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2314
2315       // FIXME: We should really autogenerate these arrays
2316       static const uint16_t GPR64ArgRegsWin64[] = {
2317         X86::RCX, X86::RDX, X86::R8,  X86::R9
2318       };
2319       static const uint16_t GPR64ArgRegs64Bit[] = {
2320         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2321       };
2322       static const uint16_t XMMArgRegs64Bit[] = {
2323         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2324         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2325       };
2326       const uint16_t *GPR64ArgRegs;
2327       unsigned NumXMMRegs = 0;
2328
2329       if (IsWin64) {
2330         // The XMM registers which might contain var arg parameters are shadowed
2331         // in their paired GPR.  So we only need to save the GPR to their home
2332         // slots.
2333         TotalNumIntRegs = 4;
2334         GPR64ArgRegs = GPR64ArgRegsWin64;
2335       } else {
2336         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2337         GPR64ArgRegs = GPR64ArgRegs64Bit;
2338
2339         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2340                                                 TotalNumXMMRegs);
2341       }
2342       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2343                                                        TotalNumIntRegs);
2344
2345       bool NoImplicitFloatOps = Fn->getAttributes().
2346         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2347       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2348              "SSE register cannot be used when SSE is disabled!");
2349       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2350                NoImplicitFloatOps) &&
2351              "SSE register cannot be used when SSE is disabled!");
2352       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2353           !Subtarget->hasSSE1())
2354         // Kernel mode asks for SSE to be disabled, so don't push them
2355         // on the stack.
2356         TotalNumXMMRegs = 0;
2357
2358       if (IsWin64) {
2359         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2360         // Get to the caller-allocated home save location.  Add 8 to account
2361         // for the return address.
2362         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2363         FuncInfo->setRegSaveFrameIndex(
2364           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2365         // Fixup to set vararg frame on shadow area (4 x i64).
2366         if (NumIntRegs < 4)
2367           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2368       } else {
2369         // For X86-64, if there are vararg parameters that are passed via
2370         // registers, then we must store them to their spots on the stack so
2371         // they may be loaded by deferencing the result of va_next.
2372         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2373         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2374         FuncInfo->setRegSaveFrameIndex(
2375           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2376                                false));
2377       }
2378
2379       // Store the integer parameter registers.
2380       SmallVector<SDValue, 8> MemOps;
2381       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2382                                         getPointerTy());
2383       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2384       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2385         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2386                                   DAG.getIntPtrConstant(Offset));
2387         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2388                                      &X86::GR64RegClass);
2389         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2390         SDValue Store =
2391           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2392                        MachinePointerInfo::getFixedStack(
2393                          FuncInfo->getRegSaveFrameIndex(), Offset),
2394                        false, false, 0);
2395         MemOps.push_back(Store);
2396         Offset += 8;
2397       }
2398
2399       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2400         // Now store the XMM (fp + vector) parameter registers.
2401         SmallVector<SDValue, 11> SaveXMMOps;
2402         SaveXMMOps.push_back(Chain);
2403
2404         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2405         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2406         SaveXMMOps.push_back(ALVal);
2407
2408         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2409                                FuncInfo->getRegSaveFrameIndex()));
2410         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2411                                FuncInfo->getVarArgsFPOffset()));
2412
2413         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2414           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2415                                        &X86::VR128RegClass);
2416           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2417           SaveXMMOps.push_back(Val);
2418         }
2419         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2420                                      MVT::Other,
2421                                      &SaveXMMOps[0], SaveXMMOps.size()));
2422       }
2423
2424       if (!MemOps.empty())
2425         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2426                             &MemOps[0], MemOps.size());
2427     }
2428   }
2429
2430   // Some CCs need callee pop.
2431   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2432                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2433     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2434   } else {
2435     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2436     // If this is an sret function, the return should pop the hidden pointer.
2437     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2438         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2439         argsAreStructReturn(Ins) == StackStructReturn)
2440       FuncInfo->setBytesToPopOnReturn(4);
2441   }
2442
2443   if (!Is64Bit) {
2444     // RegSaveFrameIndex is X86-64 only.
2445     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2446     if (CallConv == CallingConv::X86_FastCall ||
2447         CallConv == CallingConv::X86_ThisCall)
2448       // fastcc functions can't have varargs.
2449       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2450   }
2451
2452   FuncInfo->setArgumentStackSize(StackSize);
2453
2454   return Chain;
2455 }
2456
2457 SDValue
2458 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2459                                     SDValue StackPtr, SDValue Arg,
2460                                     SDLoc dl, SelectionDAG &DAG,
2461                                     const CCValAssign &VA,
2462                                     ISD::ArgFlagsTy Flags) const {
2463   unsigned LocMemOffset = VA.getLocMemOffset();
2464   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2465   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2466   if (Flags.isByVal())
2467     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2468
2469   return DAG.getStore(Chain, dl, Arg, PtrOff,
2470                       MachinePointerInfo::getStack(LocMemOffset),
2471                       false, false, 0);
2472 }
2473
2474 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2475 /// optimization is performed and it is required.
2476 SDValue
2477 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2478                                            SDValue &OutRetAddr, SDValue Chain,
2479                                            bool IsTailCall, bool Is64Bit,
2480                                            int FPDiff, SDLoc dl) const {
2481   // Adjust the Return address stack slot.
2482   EVT VT = getPointerTy();
2483   OutRetAddr = getReturnAddressFrameIndex(DAG);
2484
2485   // Load the "old" Return address.
2486   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2487                            false, false, false, 0);
2488   return SDValue(OutRetAddr.getNode(), 1);
2489 }
2490
2491 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2492 /// optimization is performed and it is required (FPDiff!=0).
2493 static SDValue
2494 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2495                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2496                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2497   // Store the return address to the appropriate stack slot.
2498   if (!FPDiff) return Chain;
2499   // Calculate the new stack slot for the return address.
2500   int NewReturnAddrFI =
2501     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2502                                          false);
2503   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2504   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2505                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2506                        false, false, 0);
2507   return Chain;
2508 }
2509
2510 SDValue
2511 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2512                              SmallVectorImpl<SDValue> &InVals) const {
2513   SelectionDAG &DAG                     = CLI.DAG;
2514   SDLoc &dl                             = CLI.DL;
2515   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2516   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2517   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2518   SDValue Chain                         = CLI.Chain;
2519   SDValue Callee                        = CLI.Callee;
2520   CallingConv::ID CallConv              = CLI.CallConv;
2521   bool &isTailCall                      = CLI.IsTailCall;
2522   bool isVarArg                         = CLI.IsVarArg;
2523
2524   MachineFunction &MF = DAG.getMachineFunction();
2525   bool Is64Bit        = Subtarget->is64Bit();
2526   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2527   StructReturnType SR = callIsStructReturn(Outs);
2528   bool IsSibcall      = false;
2529
2530   if (MF.getTarget().Options.DisableTailCalls)
2531     isTailCall = false;
2532
2533   if (isTailCall) {
2534     // Check if it's really possible to do a tail call.
2535     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2536                     isVarArg, SR != NotStructReturn,
2537                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2538                     Outs, OutVals, Ins, DAG);
2539
2540     // Sibcalls are automatically detected tailcalls which do not require
2541     // ABI changes.
2542     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2543       IsSibcall = true;
2544
2545     if (isTailCall)
2546       ++NumTailCalls;
2547   }
2548
2549   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2550          "Var args not supported with calling convention fastcc, ghc or hipe");
2551
2552   // Analyze operands of the call, assigning locations to each operand.
2553   SmallVector<CCValAssign, 16> ArgLocs;
2554   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2555                  ArgLocs, *DAG.getContext());
2556
2557   // Allocate shadow area for Win64
2558   if (IsWin64)
2559     CCInfo.AllocateStack(32, 8);
2560
2561   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2562
2563   // Get a count of how many bytes are to be pushed on the stack.
2564   unsigned NumBytes = CCInfo.getNextStackOffset();
2565   if (IsSibcall)
2566     // This is a sibcall. The memory operands are available in caller's
2567     // own caller's stack.
2568     NumBytes = 0;
2569   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2570            IsTailCallConvention(CallConv))
2571     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2572
2573   int FPDiff = 0;
2574   if (isTailCall && !IsSibcall) {
2575     // Lower arguments at fp - stackoffset + fpdiff.
2576     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2577     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2578
2579     FPDiff = NumBytesCallerPushed - NumBytes;
2580
2581     // Set the delta of movement of the returnaddr stackslot.
2582     // But only set if delta is greater than previous delta.
2583     if (FPDiff < X86Info->getTCReturnAddrDelta())
2584       X86Info->setTCReturnAddrDelta(FPDiff);
2585   }
2586
2587   unsigned NumBytesToPush = NumBytes;
2588   unsigned NumBytesToPop = NumBytes;
2589
2590   // If we have an inalloca argument, all stack space has already been allocated
2591   // for us and be right at the top of the stack.  We don't support multiple
2592   // arguments passed in memory when using inalloca.
2593   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2594     NumBytesToPush = 0;
2595     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2596            "an inalloca argument must be the only memory argument");
2597   }
2598
2599   if (!IsSibcall)
2600     Chain = DAG.getCALLSEQ_START(
2601         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2602
2603   SDValue RetAddrFrIdx;
2604   // Load return address for tail calls.
2605   if (isTailCall && FPDiff)
2606     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2607                                     Is64Bit, FPDiff, dl);
2608
2609   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2610   SmallVector<SDValue, 8> MemOpChains;
2611   SDValue StackPtr;
2612
2613   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2614   // of tail call optimization arguments are handle later.
2615   const X86RegisterInfo *RegInfo =
2616     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2617   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2618     // Skip inalloca arguments, they have already been written.
2619     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2620     if (Flags.isInAlloca())
2621       continue;
2622
2623     CCValAssign &VA = ArgLocs[i];
2624     EVT RegVT = VA.getLocVT();
2625     SDValue Arg = OutVals[i];
2626     bool isByVal = Flags.isByVal();
2627
2628     // Promote the value if needed.
2629     switch (VA.getLocInfo()) {
2630     default: llvm_unreachable("Unknown loc info!");
2631     case CCValAssign::Full: break;
2632     case CCValAssign::SExt:
2633       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2634       break;
2635     case CCValAssign::ZExt:
2636       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2637       break;
2638     case CCValAssign::AExt:
2639       if (RegVT.is128BitVector()) {
2640         // Special case: passing MMX values in XMM registers.
2641         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2642         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2643         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2644       } else
2645         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2646       break;
2647     case CCValAssign::BCvt:
2648       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2649       break;
2650     case CCValAssign::Indirect: {
2651       // Store the argument.
2652       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2653       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2654       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2655                            MachinePointerInfo::getFixedStack(FI),
2656                            false, false, 0);
2657       Arg = SpillSlot;
2658       break;
2659     }
2660     }
2661
2662     if (VA.isRegLoc()) {
2663       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2664       if (isVarArg && IsWin64) {
2665         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2666         // shadow reg if callee is a varargs function.
2667         unsigned ShadowReg = 0;
2668         switch (VA.getLocReg()) {
2669         case X86::XMM0: ShadowReg = X86::RCX; break;
2670         case X86::XMM1: ShadowReg = X86::RDX; break;
2671         case X86::XMM2: ShadowReg = X86::R8; break;
2672         case X86::XMM3: ShadowReg = X86::R9; break;
2673         }
2674         if (ShadowReg)
2675           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2676       }
2677     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2678       assert(VA.isMemLoc());
2679       if (StackPtr.getNode() == 0)
2680         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2681                                       getPointerTy());
2682       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2683                                              dl, DAG, VA, Flags));
2684     }
2685   }
2686
2687   if (!MemOpChains.empty())
2688     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2689                         &MemOpChains[0], MemOpChains.size());
2690
2691   if (Subtarget->isPICStyleGOT()) {
2692     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2693     // GOT pointer.
2694     if (!isTailCall) {
2695       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2696                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2697     } else {
2698       // If we are tail calling and generating PIC/GOT style code load the
2699       // address of the callee into ECX. The value in ecx is used as target of
2700       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2701       // for tail calls on PIC/GOT architectures. Normally we would just put the
2702       // address of GOT into ebx and then call target@PLT. But for tail calls
2703       // ebx would be restored (since ebx is callee saved) before jumping to the
2704       // target@PLT.
2705
2706       // Note: The actual moving to ECX is done further down.
2707       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2708       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2709           !G->getGlobal()->hasProtectedVisibility())
2710         Callee = LowerGlobalAddress(Callee, DAG);
2711       else if (isa<ExternalSymbolSDNode>(Callee))
2712         Callee = LowerExternalSymbol(Callee, DAG);
2713     }
2714   }
2715
2716   if (Is64Bit && isVarArg && !IsWin64) {
2717     // From AMD64 ABI document:
2718     // For calls that may call functions that use varargs or stdargs
2719     // (prototype-less calls or calls to functions containing ellipsis (...) in
2720     // the declaration) %al is used as hidden argument to specify the number
2721     // of SSE registers used. The contents of %al do not need to match exactly
2722     // the number of registers, but must be an ubound on the number of SSE
2723     // registers used and is in the range 0 - 8 inclusive.
2724
2725     // Count the number of XMM registers allocated.
2726     static const uint16_t XMMArgRegs[] = {
2727       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2728       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2729     };
2730     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2731     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2732            && "SSE registers cannot be used when SSE is disabled");
2733
2734     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2735                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2736   }
2737
2738   // For tail calls lower the arguments to the 'real' stack slot.
2739   if (isTailCall) {
2740     // Force all the incoming stack arguments to be loaded from the stack
2741     // before any new outgoing arguments are stored to the stack, because the
2742     // outgoing stack slots may alias the incoming argument stack slots, and
2743     // the alias isn't otherwise explicit. This is slightly more conservative
2744     // than necessary, because it means that each store effectively depends
2745     // on every argument instead of just those arguments it would clobber.
2746     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2747
2748     SmallVector<SDValue, 8> MemOpChains2;
2749     SDValue FIN;
2750     int FI = 0;
2751     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2752       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2753         CCValAssign &VA = ArgLocs[i];
2754         if (VA.isRegLoc())
2755           continue;
2756         assert(VA.isMemLoc());
2757         SDValue Arg = OutVals[i];
2758         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2759         // Create frame index.
2760         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2761         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2762         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2763         FIN = DAG.getFrameIndex(FI, getPointerTy());
2764
2765         if (Flags.isByVal()) {
2766           // Copy relative to framepointer.
2767           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2768           if (StackPtr.getNode() == 0)
2769             StackPtr = DAG.getCopyFromReg(Chain, dl,
2770                                           RegInfo->getStackRegister(),
2771                                           getPointerTy());
2772           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2773
2774           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2775                                                            ArgChain,
2776                                                            Flags, DAG, dl));
2777         } else {
2778           // Store relative to framepointer.
2779           MemOpChains2.push_back(
2780             DAG.getStore(ArgChain, dl, Arg, FIN,
2781                          MachinePointerInfo::getFixedStack(FI),
2782                          false, false, 0));
2783         }
2784       }
2785     }
2786
2787     if (!MemOpChains2.empty())
2788       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2789                           &MemOpChains2[0], MemOpChains2.size());
2790
2791     // Store the return address to the appropriate stack slot.
2792     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2793                                      getPointerTy(), RegInfo->getSlotSize(),
2794                                      FPDiff, dl);
2795   }
2796
2797   // Build a sequence of copy-to-reg nodes chained together with token chain
2798   // and flag operands which copy the outgoing args into registers.
2799   SDValue InFlag;
2800   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2801     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2802                              RegsToPass[i].second, InFlag);
2803     InFlag = Chain.getValue(1);
2804   }
2805
2806   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2807     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2808     // In the 64-bit large code model, we have to make all calls
2809     // through a register, since the call instruction's 32-bit
2810     // pc-relative offset may not be large enough to hold the whole
2811     // address.
2812   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2813     // If the callee is a GlobalAddress node (quite common, every direct call
2814     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2815     // it.
2816
2817     // We should use extra load for direct calls to dllimported functions in
2818     // non-JIT mode.
2819     const GlobalValue *GV = G->getGlobal();
2820     if (!GV->hasDLLImportStorageClass()) {
2821       unsigned char OpFlags = 0;
2822       bool ExtraLoad = false;
2823       unsigned WrapperKind = ISD::DELETED_NODE;
2824
2825       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2826       // external symbols most go through the PLT in PIC mode.  If the symbol
2827       // has hidden or protected visibility, or if it is static or local, then
2828       // we don't need to use the PLT - we can directly call it.
2829       if (Subtarget->isTargetELF() &&
2830           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2831           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2832         OpFlags = X86II::MO_PLT;
2833       } else if (Subtarget->isPICStyleStubAny() &&
2834                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2835                  (!Subtarget->getTargetTriple().isMacOSX() ||
2836                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2837         // PC-relative references to external symbols should go through $stub,
2838         // unless we're building with the leopard linker or later, which
2839         // automatically synthesizes these stubs.
2840         OpFlags = X86II::MO_DARWIN_STUB;
2841       } else if (Subtarget->isPICStyleRIPRel() &&
2842                  isa<Function>(GV) &&
2843                  cast<Function>(GV)->getAttributes().
2844                    hasAttribute(AttributeSet::FunctionIndex,
2845                                 Attribute::NonLazyBind)) {
2846         // If the function is marked as non-lazy, generate an indirect call
2847         // which loads from the GOT directly. This avoids runtime overhead
2848         // at the cost of eager binding (and one extra byte of encoding).
2849         OpFlags = X86II::MO_GOTPCREL;
2850         WrapperKind = X86ISD::WrapperRIP;
2851         ExtraLoad = true;
2852       }
2853
2854       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2855                                           G->getOffset(), OpFlags);
2856
2857       // Add a wrapper if needed.
2858       if (WrapperKind != ISD::DELETED_NODE)
2859         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2860       // Add extra indirection if needed.
2861       if (ExtraLoad)
2862         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2863                              MachinePointerInfo::getGOT(),
2864                              false, false, false, 0);
2865     }
2866   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2867     unsigned char OpFlags = 0;
2868
2869     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2870     // external symbols should go through the PLT.
2871     if (Subtarget->isTargetELF() &&
2872         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2873       OpFlags = X86II::MO_PLT;
2874     } else if (Subtarget->isPICStyleStubAny() &&
2875                (!Subtarget->getTargetTriple().isMacOSX() ||
2876                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2877       // PC-relative references to external symbols should go through $stub,
2878       // unless we're building with the leopard linker or later, which
2879       // automatically synthesizes these stubs.
2880       OpFlags = X86II::MO_DARWIN_STUB;
2881     }
2882
2883     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2884                                          OpFlags);
2885   }
2886
2887   // Returns a chain & a flag for retval copy to use.
2888   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2889   SmallVector<SDValue, 8> Ops;
2890
2891   if (!IsSibcall && isTailCall) {
2892     Chain = DAG.getCALLSEQ_END(Chain,
2893                                DAG.getIntPtrConstant(NumBytesToPop, true),
2894                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2895     InFlag = Chain.getValue(1);
2896   }
2897
2898   Ops.push_back(Chain);
2899   Ops.push_back(Callee);
2900
2901   if (isTailCall)
2902     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2903
2904   // Add argument registers to the end of the list so that they are known live
2905   // into the call.
2906   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2907     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2908                                   RegsToPass[i].second.getValueType()));
2909
2910   // Add a register mask operand representing the call-preserved registers.
2911   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2912   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2913   assert(Mask && "Missing call preserved mask for calling convention");
2914   Ops.push_back(DAG.getRegisterMask(Mask));
2915
2916   if (InFlag.getNode())
2917     Ops.push_back(InFlag);
2918
2919   if (isTailCall) {
2920     // We used to do:
2921     //// If this is the first return lowered for this function, add the regs
2922     //// to the liveout set for the function.
2923     // This isn't right, although it's probably harmless on x86; liveouts
2924     // should be computed from returns not tail calls.  Consider a void
2925     // function making a tail call to a function returning int.
2926     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2927   }
2928
2929   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2930   InFlag = Chain.getValue(1);
2931
2932   // Create the CALLSEQ_END node.
2933   unsigned NumBytesForCalleeToPop;
2934   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2935                        getTargetMachine().Options.GuaranteedTailCallOpt))
2936     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2937   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2938            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2939            SR == StackStructReturn)
2940     // If this is a call to a struct-return function, the callee
2941     // pops the hidden struct pointer, so we have to push it back.
2942     // This is common for Darwin/X86, Linux & Mingw32 targets.
2943     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2944     NumBytesForCalleeToPop = 4;
2945   else
2946     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2947
2948   // Returns a flag for retval copy to use.
2949   if (!IsSibcall) {
2950     Chain = DAG.getCALLSEQ_END(Chain,
2951                                DAG.getIntPtrConstant(NumBytesToPop, true),
2952                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2953                                                      true),
2954                                InFlag, dl);
2955     InFlag = Chain.getValue(1);
2956   }
2957
2958   // Handle result values, copying them out of physregs into vregs that we
2959   // return.
2960   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2961                          Ins, dl, DAG, InVals);
2962 }
2963
2964 //===----------------------------------------------------------------------===//
2965 //                Fast Calling Convention (tail call) implementation
2966 //===----------------------------------------------------------------------===//
2967
2968 //  Like std call, callee cleans arguments, convention except that ECX is
2969 //  reserved for storing the tail called function address. Only 2 registers are
2970 //  free for argument passing (inreg). Tail call optimization is performed
2971 //  provided:
2972 //                * tailcallopt is enabled
2973 //                * caller/callee are fastcc
2974 //  On X86_64 architecture with GOT-style position independent code only local
2975 //  (within module) calls are supported at the moment.
2976 //  To keep the stack aligned according to platform abi the function
2977 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2978 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2979 //  If a tail called function callee has more arguments than the caller the
2980 //  caller needs to make sure that there is room to move the RETADDR to. This is
2981 //  achieved by reserving an area the size of the argument delta right after the
2982 //  original REtADDR, but before the saved framepointer or the spilled registers
2983 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2984 //  stack layout:
2985 //    arg1
2986 //    arg2
2987 //    RETADDR
2988 //    [ new RETADDR
2989 //      move area ]
2990 //    (possible EBP)
2991 //    ESI
2992 //    EDI
2993 //    local1 ..
2994
2995 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2996 /// for a 16 byte align requirement.
2997 unsigned
2998 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2999                                                SelectionDAG& DAG) const {
3000   MachineFunction &MF = DAG.getMachineFunction();
3001   const TargetMachine &TM = MF.getTarget();
3002   const X86RegisterInfo *RegInfo =
3003     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3004   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3005   unsigned StackAlignment = TFI.getStackAlignment();
3006   uint64_t AlignMask = StackAlignment - 1;
3007   int64_t Offset = StackSize;
3008   unsigned SlotSize = RegInfo->getSlotSize();
3009   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3010     // Number smaller than 12 so just add the difference.
3011     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3012   } else {
3013     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3014     Offset = ((~AlignMask) & Offset) + StackAlignment +
3015       (StackAlignment-SlotSize);
3016   }
3017   return Offset;
3018 }
3019
3020 /// MatchingStackOffset - Return true if the given stack call argument is
3021 /// already available in the same position (relatively) of the caller's
3022 /// incoming argument stack.
3023 static
3024 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3025                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3026                          const X86InstrInfo *TII) {
3027   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3028   int FI = INT_MAX;
3029   if (Arg.getOpcode() == ISD::CopyFromReg) {
3030     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3031     if (!TargetRegisterInfo::isVirtualRegister(VR))
3032       return false;
3033     MachineInstr *Def = MRI->getVRegDef(VR);
3034     if (!Def)
3035       return false;
3036     if (!Flags.isByVal()) {
3037       if (!TII->isLoadFromStackSlot(Def, FI))
3038         return false;
3039     } else {
3040       unsigned Opcode = Def->getOpcode();
3041       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3042           Def->getOperand(1).isFI()) {
3043         FI = Def->getOperand(1).getIndex();
3044         Bytes = Flags.getByValSize();
3045       } else
3046         return false;
3047     }
3048   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3049     if (Flags.isByVal())
3050       // ByVal argument is passed in as a pointer but it's now being
3051       // dereferenced. e.g.
3052       // define @foo(%struct.X* %A) {
3053       //   tail call @bar(%struct.X* byval %A)
3054       // }
3055       return false;
3056     SDValue Ptr = Ld->getBasePtr();
3057     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3058     if (!FINode)
3059       return false;
3060     FI = FINode->getIndex();
3061   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3062     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3063     FI = FINode->getIndex();
3064     Bytes = Flags.getByValSize();
3065   } else
3066     return false;
3067
3068   assert(FI != INT_MAX);
3069   if (!MFI->isFixedObjectIndex(FI))
3070     return false;
3071   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3072 }
3073
3074 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3075 /// for tail call optimization. Targets which want to do tail call
3076 /// optimization should implement this function.
3077 bool
3078 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3079                                                      CallingConv::ID CalleeCC,
3080                                                      bool isVarArg,
3081                                                      bool isCalleeStructRet,
3082                                                      bool isCallerStructRet,
3083                                                      Type *RetTy,
3084                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3085                                     const SmallVectorImpl<SDValue> &OutVals,
3086                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3087                                                      SelectionDAG &DAG) const {
3088   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3089     return false;
3090
3091   // If -tailcallopt is specified, make fastcc functions tail-callable.
3092   const MachineFunction &MF = DAG.getMachineFunction();
3093   const Function *CallerF = MF.getFunction();
3094
3095   // If the function return type is x86_fp80 and the callee return type is not,
3096   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3097   // perform a tailcall optimization here.
3098   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3099     return false;
3100
3101   CallingConv::ID CallerCC = CallerF->getCallingConv();
3102   bool CCMatch = CallerCC == CalleeCC;
3103   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3104   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3105
3106   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3107     if (IsTailCallConvention(CalleeCC) && CCMatch)
3108       return true;
3109     return false;
3110   }
3111
3112   // Look for obvious safe cases to perform tail call optimization that do not
3113   // require ABI changes. This is what gcc calls sibcall.
3114
3115   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3116   // emit a special epilogue.
3117   const X86RegisterInfo *RegInfo =
3118     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3119   if (RegInfo->needsStackRealignment(MF))
3120     return false;
3121
3122   // Also avoid sibcall optimization if either caller or callee uses struct
3123   // return semantics.
3124   if (isCalleeStructRet || isCallerStructRet)
3125     return false;
3126
3127   // An stdcall/thiscall caller is expected to clean up its arguments; the
3128   // callee isn't going to do that.
3129   // FIXME: this is more restrictive than needed. We could produce a tailcall
3130   // when the stack adjustment matches. For example, with a thiscall that takes
3131   // only one argument.
3132   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3133                    CallerCC == CallingConv::X86_ThisCall))
3134     return false;
3135
3136   // Do not sibcall optimize vararg calls unless all arguments are passed via
3137   // registers.
3138   if (isVarArg && !Outs.empty()) {
3139
3140     // Optimizing for varargs on Win64 is unlikely to be safe without
3141     // additional testing.
3142     if (IsCalleeWin64 || IsCallerWin64)
3143       return false;
3144
3145     SmallVector<CCValAssign, 16> ArgLocs;
3146     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3147                    getTargetMachine(), ArgLocs, *DAG.getContext());
3148
3149     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3150     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3151       if (!ArgLocs[i].isRegLoc())
3152         return false;
3153   }
3154
3155   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3156   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3157   // this into a sibcall.
3158   bool Unused = false;
3159   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3160     if (!Ins[i].Used) {
3161       Unused = true;
3162       break;
3163     }
3164   }
3165   if (Unused) {
3166     SmallVector<CCValAssign, 16> RVLocs;
3167     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3168                    getTargetMachine(), RVLocs, *DAG.getContext());
3169     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3170     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3171       CCValAssign &VA = RVLocs[i];
3172       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3173         return false;
3174     }
3175   }
3176
3177   // If the calling conventions do not match, then we'd better make sure the
3178   // results are returned in the same way as what the caller expects.
3179   if (!CCMatch) {
3180     SmallVector<CCValAssign, 16> RVLocs1;
3181     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3182                     getTargetMachine(), RVLocs1, *DAG.getContext());
3183     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3184
3185     SmallVector<CCValAssign, 16> RVLocs2;
3186     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3187                     getTargetMachine(), RVLocs2, *DAG.getContext());
3188     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3189
3190     if (RVLocs1.size() != RVLocs2.size())
3191       return false;
3192     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3193       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3194         return false;
3195       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3196         return false;
3197       if (RVLocs1[i].isRegLoc()) {
3198         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3199           return false;
3200       } else {
3201         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3202           return false;
3203       }
3204     }
3205   }
3206
3207   // If the callee takes no arguments then go on to check the results of the
3208   // call.
3209   if (!Outs.empty()) {
3210     // Check if stack adjustment is needed. For now, do not do this if any
3211     // argument is passed on the stack.
3212     SmallVector<CCValAssign, 16> ArgLocs;
3213     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3214                    getTargetMachine(), ArgLocs, *DAG.getContext());
3215
3216     // Allocate shadow area for Win64
3217     if (IsCalleeWin64)
3218       CCInfo.AllocateStack(32, 8);
3219
3220     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3221     if (CCInfo.getNextStackOffset()) {
3222       MachineFunction &MF = DAG.getMachineFunction();
3223       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3224         return false;
3225
3226       // Check if the arguments are already laid out in the right way as
3227       // the caller's fixed stack objects.
3228       MachineFrameInfo *MFI = MF.getFrameInfo();
3229       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3230       const X86InstrInfo *TII =
3231         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3232       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3233         CCValAssign &VA = ArgLocs[i];
3234         SDValue Arg = OutVals[i];
3235         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3236         if (VA.getLocInfo() == CCValAssign::Indirect)
3237           return false;
3238         if (!VA.isRegLoc()) {
3239           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3240                                    MFI, MRI, TII))
3241             return false;
3242         }
3243       }
3244     }
3245
3246     // If the tailcall address may be in a register, then make sure it's
3247     // possible to register allocate for it. In 32-bit, the call address can
3248     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3249     // callee-saved registers are restored. These happen to be the same
3250     // registers used to pass 'inreg' arguments so watch out for those.
3251     if (!Subtarget->is64Bit() &&
3252         ((!isa<GlobalAddressSDNode>(Callee) &&
3253           !isa<ExternalSymbolSDNode>(Callee)) ||
3254          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3255       unsigned NumInRegs = 0;
3256       // In PIC we need an extra register to formulate the address computation
3257       // for the callee.
3258       unsigned MaxInRegs =
3259           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3260
3261       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3262         CCValAssign &VA = ArgLocs[i];
3263         if (!VA.isRegLoc())
3264           continue;
3265         unsigned Reg = VA.getLocReg();
3266         switch (Reg) {
3267         default: break;
3268         case X86::EAX: case X86::EDX: case X86::ECX:
3269           if (++NumInRegs == MaxInRegs)
3270             return false;
3271           break;
3272         }
3273       }
3274     }
3275   }
3276
3277   return true;
3278 }
3279
3280 FastISel *
3281 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3282                                   const TargetLibraryInfo *libInfo) const {
3283   return X86::createFastISel(funcInfo, libInfo);
3284 }
3285
3286 //===----------------------------------------------------------------------===//
3287 //                           Other Lowering Hooks
3288 //===----------------------------------------------------------------------===//
3289
3290 static bool MayFoldLoad(SDValue Op) {
3291   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3292 }
3293
3294 static bool MayFoldIntoStore(SDValue Op) {
3295   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3296 }
3297
3298 static bool isTargetShuffle(unsigned Opcode) {
3299   switch(Opcode) {
3300   default: return false;
3301   case X86ISD::PSHUFD:
3302   case X86ISD::PSHUFHW:
3303   case X86ISD::PSHUFLW:
3304   case X86ISD::SHUFP:
3305   case X86ISD::PALIGNR:
3306   case X86ISD::MOVLHPS:
3307   case X86ISD::MOVLHPD:
3308   case X86ISD::MOVHLPS:
3309   case X86ISD::MOVLPS:
3310   case X86ISD::MOVLPD:
3311   case X86ISD::MOVSHDUP:
3312   case X86ISD::MOVSLDUP:
3313   case X86ISD::MOVDDUP:
3314   case X86ISD::MOVSS:
3315   case X86ISD::MOVSD:
3316   case X86ISD::UNPCKL:
3317   case X86ISD::UNPCKH:
3318   case X86ISD::VPERMILP:
3319   case X86ISD::VPERM2X128:
3320   case X86ISD::VPERMI:
3321     return true;
3322   }
3323 }
3324
3325 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3326                                     SDValue V1, SelectionDAG &DAG) {
3327   switch(Opc) {
3328   default: llvm_unreachable("Unknown x86 shuffle node");
3329   case X86ISD::MOVSHDUP:
3330   case X86ISD::MOVSLDUP:
3331   case X86ISD::MOVDDUP:
3332     return DAG.getNode(Opc, dl, VT, V1);
3333   }
3334 }
3335
3336 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3337                                     SDValue V1, unsigned TargetMask,
3338                                     SelectionDAG &DAG) {
3339   switch(Opc) {
3340   default: llvm_unreachable("Unknown x86 shuffle node");
3341   case X86ISD::PSHUFD:
3342   case X86ISD::PSHUFHW:
3343   case X86ISD::PSHUFLW:
3344   case X86ISD::VPERMILP:
3345   case X86ISD::VPERMI:
3346     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3347   }
3348 }
3349
3350 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3351                                     SDValue V1, SDValue V2, unsigned TargetMask,
3352                                     SelectionDAG &DAG) {
3353   switch(Opc) {
3354   default: llvm_unreachable("Unknown x86 shuffle node");
3355   case X86ISD::PALIGNR:
3356   case X86ISD::SHUFP:
3357   case X86ISD::VPERM2X128:
3358     return DAG.getNode(Opc, dl, VT, V1, V2,
3359                        DAG.getConstant(TargetMask, MVT::i8));
3360   }
3361 }
3362
3363 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3364                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3365   switch(Opc) {
3366   default: llvm_unreachable("Unknown x86 shuffle node");
3367   case X86ISD::MOVLHPS:
3368   case X86ISD::MOVLHPD:
3369   case X86ISD::MOVHLPS:
3370   case X86ISD::MOVLPS:
3371   case X86ISD::MOVLPD:
3372   case X86ISD::MOVSS:
3373   case X86ISD::MOVSD:
3374   case X86ISD::UNPCKL:
3375   case X86ISD::UNPCKH:
3376     return DAG.getNode(Opc, dl, VT, V1, V2);
3377   }
3378 }
3379
3380 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3381   MachineFunction &MF = DAG.getMachineFunction();
3382   const X86RegisterInfo *RegInfo =
3383     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3384   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3385   int ReturnAddrIndex = FuncInfo->getRAIndex();
3386
3387   if (ReturnAddrIndex == 0) {
3388     // Set up a frame object for the return address.
3389     unsigned SlotSize = RegInfo->getSlotSize();
3390     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3391                                                            -(int64_t)SlotSize,
3392                                                            false);
3393     FuncInfo->setRAIndex(ReturnAddrIndex);
3394   }
3395
3396   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3397 }
3398
3399 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3400                                        bool hasSymbolicDisplacement) {
3401   // Offset should fit into 32 bit immediate field.
3402   if (!isInt<32>(Offset))
3403     return false;
3404
3405   // If we don't have a symbolic displacement - we don't have any extra
3406   // restrictions.
3407   if (!hasSymbolicDisplacement)
3408     return true;
3409
3410   // FIXME: Some tweaks might be needed for medium code model.
3411   if (M != CodeModel::Small && M != CodeModel::Kernel)
3412     return false;
3413
3414   // For small code model we assume that latest object is 16MB before end of 31
3415   // bits boundary. We may also accept pretty large negative constants knowing
3416   // that all objects are in the positive half of address space.
3417   if (M == CodeModel::Small && Offset < 16*1024*1024)
3418     return true;
3419
3420   // For kernel code model we know that all object resist in the negative half
3421   // of 32bits address space. We may not accept negative offsets, since they may
3422   // be just off and we may accept pretty large positive ones.
3423   if (M == CodeModel::Kernel && Offset > 0)
3424     return true;
3425
3426   return false;
3427 }
3428
3429 /// isCalleePop - Determines whether the callee is required to pop its
3430 /// own arguments. Callee pop is necessary to support tail calls.
3431 bool X86::isCalleePop(CallingConv::ID CallingConv,
3432                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3433   if (IsVarArg)
3434     return false;
3435
3436   switch (CallingConv) {
3437   default:
3438     return false;
3439   case CallingConv::X86_StdCall:
3440     return !is64Bit;
3441   case CallingConv::X86_FastCall:
3442     return !is64Bit;
3443   case CallingConv::X86_ThisCall:
3444     return !is64Bit;
3445   case CallingConv::Fast:
3446     return TailCallOpt;
3447   case CallingConv::GHC:
3448     return TailCallOpt;
3449   case CallingConv::HiPE:
3450     return TailCallOpt;
3451   }
3452 }
3453
3454 /// \brief Return true if the condition is an unsigned comparison operation.
3455 static bool isX86CCUnsigned(unsigned X86CC) {
3456   switch (X86CC) {
3457   default: llvm_unreachable("Invalid integer condition!");
3458   case X86::COND_E:     return true;
3459   case X86::COND_G:     return false;
3460   case X86::COND_GE:    return false;
3461   case X86::COND_L:     return false;
3462   case X86::COND_LE:    return false;
3463   case X86::COND_NE:    return true;
3464   case X86::COND_B:     return true;
3465   case X86::COND_A:     return true;
3466   case X86::COND_BE:    return true;
3467   case X86::COND_AE:    return true;
3468   }
3469   llvm_unreachable("covered switch fell through?!");
3470 }
3471
3472 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3473 /// specific condition code, returning the condition code and the LHS/RHS of the
3474 /// comparison to make.
3475 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3476                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3477   if (!isFP) {
3478     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3479       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3480         // X > -1   -> X == 0, jump !sign.
3481         RHS = DAG.getConstant(0, RHS.getValueType());
3482         return X86::COND_NS;
3483       }
3484       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3485         // X < 0   -> X == 0, jump on sign.
3486         return X86::COND_S;
3487       }
3488       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3489         // X < 1   -> X <= 0
3490         RHS = DAG.getConstant(0, RHS.getValueType());
3491         return X86::COND_LE;
3492       }
3493     }
3494
3495     switch (SetCCOpcode) {
3496     default: llvm_unreachable("Invalid integer condition!");
3497     case ISD::SETEQ:  return X86::COND_E;
3498     case ISD::SETGT:  return X86::COND_G;
3499     case ISD::SETGE:  return X86::COND_GE;
3500     case ISD::SETLT:  return X86::COND_L;
3501     case ISD::SETLE:  return X86::COND_LE;
3502     case ISD::SETNE:  return X86::COND_NE;
3503     case ISD::SETULT: return X86::COND_B;
3504     case ISD::SETUGT: return X86::COND_A;
3505     case ISD::SETULE: return X86::COND_BE;
3506     case ISD::SETUGE: return X86::COND_AE;
3507     }
3508   }
3509
3510   // First determine if it is required or is profitable to flip the operands.
3511
3512   // If LHS is a foldable load, but RHS is not, flip the condition.
3513   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3514       !ISD::isNON_EXTLoad(RHS.getNode())) {
3515     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3516     std::swap(LHS, RHS);
3517   }
3518
3519   switch (SetCCOpcode) {
3520   default: break;
3521   case ISD::SETOLT:
3522   case ISD::SETOLE:
3523   case ISD::SETUGT:
3524   case ISD::SETUGE:
3525     std::swap(LHS, RHS);
3526     break;
3527   }
3528
3529   // On a floating point condition, the flags are set as follows:
3530   // ZF  PF  CF   op
3531   //  0 | 0 | 0 | X > Y
3532   //  0 | 0 | 1 | X < Y
3533   //  1 | 0 | 0 | X == Y
3534   //  1 | 1 | 1 | unordered
3535   switch (SetCCOpcode) {
3536   default: llvm_unreachable("Condcode should be pre-legalized away");
3537   case ISD::SETUEQ:
3538   case ISD::SETEQ:   return X86::COND_E;
3539   case ISD::SETOLT:              // flipped
3540   case ISD::SETOGT:
3541   case ISD::SETGT:   return X86::COND_A;
3542   case ISD::SETOLE:              // flipped
3543   case ISD::SETOGE:
3544   case ISD::SETGE:   return X86::COND_AE;
3545   case ISD::SETUGT:              // flipped
3546   case ISD::SETULT:
3547   case ISD::SETLT:   return X86::COND_B;
3548   case ISD::SETUGE:              // flipped
3549   case ISD::SETULE:
3550   case ISD::SETLE:   return X86::COND_BE;
3551   case ISD::SETONE:
3552   case ISD::SETNE:   return X86::COND_NE;
3553   case ISD::SETUO:   return X86::COND_P;
3554   case ISD::SETO:    return X86::COND_NP;
3555   case ISD::SETOEQ:
3556   case ISD::SETUNE:  return X86::COND_INVALID;
3557   }
3558 }
3559
3560 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3561 /// code. Current x86 isa includes the following FP cmov instructions:
3562 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3563 static bool hasFPCMov(unsigned X86CC) {
3564   switch (X86CC) {
3565   default:
3566     return false;
3567   case X86::COND_B:
3568   case X86::COND_BE:
3569   case X86::COND_E:
3570   case X86::COND_P:
3571   case X86::COND_A:
3572   case X86::COND_AE:
3573   case X86::COND_NE:
3574   case X86::COND_NP:
3575     return true;
3576   }
3577 }
3578
3579 /// isFPImmLegal - Returns true if the target can instruction select the
3580 /// specified FP immediate natively. If false, the legalizer will
3581 /// materialize the FP immediate as a load from a constant pool.
3582 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3583   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3584     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3585       return true;
3586   }
3587   return false;
3588 }
3589
3590 /// \brief Returns true if it is beneficial to convert a load of a constant
3591 /// to just the constant itself.
3592 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3593                                                           Type *Ty) const {
3594   assert(Ty->isIntegerTy());
3595
3596   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3597   if (BitSize == 0 || BitSize > 64)
3598     return false;
3599   return true;
3600 }
3601
3602 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3603 /// the specified range (L, H].
3604 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3605   return (Val < 0) || (Val >= Low && Val < Hi);
3606 }
3607
3608 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3609 /// specified value.
3610 static bool isUndefOrEqual(int Val, int CmpVal) {
3611   return (Val < 0 || Val == CmpVal);
3612 }
3613
3614 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3615 /// from position Pos and ending in Pos+Size, falls within the specified
3616 /// sequential range (L, L+Pos]. or is undef.
3617 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3618                                        unsigned Pos, unsigned Size, int Low) {
3619   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3620     if (!isUndefOrEqual(Mask[i], Low))
3621       return false;
3622   return true;
3623 }
3624
3625 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3626 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3627 /// the second operand.
3628 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3629   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3630     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3631   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3632     return (Mask[0] < 2 && Mask[1] < 2);
3633   return false;
3634 }
3635
3636 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3637 /// is suitable for input to PSHUFHW.
3638 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3639   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3640     return false;
3641
3642   // Lower quadword copied in order or undef.
3643   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3644     return false;
3645
3646   // Upper quadword shuffled.
3647   for (unsigned i = 4; i != 8; ++i)
3648     if (!isUndefOrInRange(Mask[i], 4, 8))
3649       return false;
3650
3651   if (VT == MVT::v16i16) {
3652     // Lower quadword copied in order or undef.
3653     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3654       return false;
3655
3656     // Upper quadword shuffled.
3657     for (unsigned i = 12; i != 16; ++i)
3658       if (!isUndefOrInRange(Mask[i], 12, 16))
3659         return false;
3660   }
3661
3662   return true;
3663 }
3664
3665 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3666 /// is suitable for input to PSHUFLW.
3667 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3668   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3669     return false;
3670
3671   // Upper quadword copied in order.
3672   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3673     return false;
3674
3675   // Lower quadword shuffled.
3676   for (unsigned i = 0; i != 4; ++i)
3677     if (!isUndefOrInRange(Mask[i], 0, 4))
3678       return false;
3679
3680   if (VT == MVT::v16i16) {
3681     // Upper quadword copied in order.
3682     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3683       return false;
3684
3685     // Lower quadword shuffled.
3686     for (unsigned i = 8; i != 12; ++i)
3687       if (!isUndefOrInRange(Mask[i], 8, 12))
3688         return false;
3689   }
3690
3691   return true;
3692 }
3693
3694 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3695 /// is suitable for input to PALIGNR.
3696 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3697                           const X86Subtarget *Subtarget) {
3698   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3699       (VT.is256BitVector() && !Subtarget->hasInt256()))
3700     return false;
3701
3702   unsigned NumElts = VT.getVectorNumElements();
3703   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3704   unsigned NumLaneElts = NumElts/NumLanes;
3705
3706   // Do not handle 64-bit element shuffles with palignr.
3707   if (NumLaneElts == 2)
3708     return false;
3709
3710   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3711     unsigned i;
3712     for (i = 0; i != NumLaneElts; ++i) {
3713       if (Mask[i+l] >= 0)
3714         break;
3715     }
3716
3717     // Lane is all undef, go to next lane
3718     if (i == NumLaneElts)
3719       continue;
3720
3721     int Start = Mask[i+l];
3722
3723     // Make sure its in this lane in one of the sources
3724     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3725         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3726       return false;
3727
3728     // If not lane 0, then we must match lane 0
3729     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3730       return false;
3731
3732     // Correct second source to be contiguous with first source
3733     if (Start >= (int)NumElts)
3734       Start -= NumElts - NumLaneElts;
3735
3736     // Make sure we're shifting in the right direction.
3737     if (Start <= (int)(i+l))
3738       return false;
3739
3740     Start -= i;
3741
3742     // Check the rest of the elements to see if they are consecutive.
3743     for (++i; i != NumLaneElts; ++i) {
3744       int Idx = Mask[i+l];
3745
3746       // Make sure its in this lane
3747       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3748           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3749         return false;
3750
3751       // If not lane 0, then we must match lane 0
3752       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3753         return false;
3754
3755       if (Idx >= (int)NumElts)
3756         Idx -= NumElts - NumLaneElts;
3757
3758       if (!isUndefOrEqual(Idx, Start+i))
3759         return false;
3760
3761     }
3762   }
3763
3764   return true;
3765 }
3766
3767 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3768 /// the two vector operands have swapped position.
3769 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3770                                      unsigned NumElems) {
3771   for (unsigned i = 0; i != NumElems; ++i) {
3772     int idx = Mask[i];
3773     if (idx < 0)
3774       continue;
3775     else if (idx < (int)NumElems)
3776       Mask[i] = idx + NumElems;
3777     else
3778       Mask[i] = idx - NumElems;
3779   }
3780 }
3781
3782 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3783 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3784 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3785 /// reverse of what x86 shuffles want.
3786 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3787
3788   unsigned NumElems = VT.getVectorNumElements();
3789   unsigned NumLanes = VT.getSizeInBits()/128;
3790   unsigned NumLaneElems = NumElems/NumLanes;
3791
3792   if (NumLaneElems != 2 && NumLaneElems != 4)
3793     return false;
3794
3795   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3796   bool symetricMaskRequired =
3797     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3798
3799   // VSHUFPSY divides the resulting vector into 4 chunks.
3800   // The sources are also splitted into 4 chunks, and each destination
3801   // chunk must come from a different source chunk.
3802   //
3803   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3804   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3805   //
3806   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3807   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3808   //
3809   // VSHUFPDY divides the resulting vector into 4 chunks.
3810   // The sources are also splitted into 4 chunks, and each destination
3811   // chunk must come from a different source chunk.
3812   //
3813   //  SRC1 =>      X3       X2       X1       X0
3814   //  SRC2 =>      Y3       Y2       Y1       Y0
3815   //
3816   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3817   //
3818   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3819   unsigned HalfLaneElems = NumLaneElems/2;
3820   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3821     for (unsigned i = 0; i != NumLaneElems; ++i) {
3822       int Idx = Mask[i+l];
3823       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3824       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3825         return false;
3826       // For VSHUFPSY, the mask of the second half must be the same as the
3827       // first but with the appropriate offsets. This works in the same way as
3828       // VPERMILPS works with masks.
3829       if (!symetricMaskRequired || Idx < 0)
3830         continue;
3831       if (MaskVal[i] < 0) {
3832         MaskVal[i] = Idx - l;
3833         continue;
3834       }
3835       if ((signed)(Idx - l) != MaskVal[i])
3836         return false;
3837     }
3838   }
3839
3840   return true;
3841 }
3842
3843 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3844 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3845 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3846   if (!VT.is128BitVector())
3847     return false;
3848
3849   unsigned NumElems = VT.getVectorNumElements();
3850
3851   if (NumElems != 4)
3852     return false;
3853
3854   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3855   return isUndefOrEqual(Mask[0], 6) &&
3856          isUndefOrEqual(Mask[1], 7) &&
3857          isUndefOrEqual(Mask[2], 2) &&
3858          isUndefOrEqual(Mask[3], 3);
3859 }
3860
3861 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3862 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3863 /// <2, 3, 2, 3>
3864 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3865   if (!VT.is128BitVector())
3866     return false;
3867
3868   unsigned NumElems = VT.getVectorNumElements();
3869
3870   if (NumElems != 4)
3871     return false;
3872
3873   return isUndefOrEqual(Mask[0], 2) &&
3874          isUndefOrEqual(Mask[1], 3) &&
3875          isUndefOrEqual(Mask[2], 2) &&
3876          isUndefOrEqual(Mask[3], 3);
3877 }
3878
3879 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3880 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3881 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3882   if (!VT.is128BitVector())
3883     return false;
3884
3885   unsigned NumElems = VT.getVectorNumElements();
3886
3887   if (NumElems != 2 && NumElems != 4)
3888     return false;
3889
3890   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3891     if (!isUndefOrEqual(Mask[i], i + NumElems))
3892       return false;
3893
3894   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3895     if (!isUndefOrEqual(Mask[i], i))
3896       return false;
3897
3898   return true;
3899 }
3900
3901 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3902 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3903 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3904   if (!VT.is128BitVector())
3905     return false;
3906
3907   unsigned NumElems = VT.getVectorNumElements();
3908
3909   if (NumElems != 2 && NumElems != 4)
3910     return false;
3911
3912   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3913     if (!isUndefOrEqual(Mask[i], i))
3914       return false;
3915
3916   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3917     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3918       return false;
3919
3920   return true;
3921 }
3922
3923 //
3924 // Some special combinations that can be optimized.
3925 //
3926 static
3927 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3928                                SelectionDAG &DAG) {
3929   MVT VT = SVOp->getSimpleValueType(0);
3930   SDLoc dl(SVOp);
3931
3932   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3933     return SDValue();
3934
3935   ArrayRef<int> Mask = SVOp->getMask();
3936
3937   // These are the special masks that may be optimized.
3938   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3939   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3940   bool MatchEvenMask = true;
3941   bool MatchOddMask  = true;
3942   for (int i=0; i<8; ++i) {
3943     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3944       MatchEvenMask = false;
3945     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3946       MatchOddMask = false;
3947   }
3948
3949   if (!MatchEvenMask && !MatchOddMask)
3950     return SDValue();
3951
3952   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3953
3954   SDValue Op0 = SVOp->getOperand(0);
3955   SDValue Op1 = SVOp->getOperand(1);
3956
3957   if (MatchEvenMask) {
3958     // Shift the second operand right to 32 bits.
3959     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3960     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3961   } else {
3962     // Shift the first operand left to 32 bits.
3963     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3964     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3965   }
3966   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3967   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3968 }
3969
3970 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3971 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3972 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3973                          bool HasInt256, bool V2IsSplat = false) {
3974
3975   assert(VT.getSizeInBits() >= 128 &&
3976          "Unsupported vector type for unpckl");
3977
3978   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3979   unsigned NumLanes;
3980   unsigned NumOf256BitLanes;
3981   unsigned NumElts = VT.getVectorNumElements();
3982   if (VT.is256BitVector()) {
3983     if (NumElts != 4 && NumElts != 8 &&
3984         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3985     return false;
3986     NumLanes = 2;
3987     NumOf256BitLanes = 1;
3988   } else if (VT.is512BitVector()) {
3989     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3990            "Unsupported vector type for unpckh");
3991     NumLanes = 2;
3992     NumOf256BitLanes = 2;
3993   } else {
3994     NumLanes = 1;
3995     NumOf256BitLanes = 1;
3996   }
3997
3998   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3999   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4000
4001   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4002     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4003       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4004         int BitI  = Mask[l256*NumEltsInStride+l+i];
4005         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4006         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4007           return false;
4008         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4009           return false;
4010         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4011           return false;
4012       }
4013     }
4014   }
4015   return true;
4016 }
4017
4018 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4019 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4020 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4021                          bool HasInt256, bool V2IsSplat = false) {
4022   assert(VT.getSizeInBits() >= 128 &&
4023          "Unsupported vector type for unpckh");
4024
4025   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4026   unsigned NumLanes;
4027   unsigned NumOf256BitLanes;
4028   unsigned NumElts = VT.getVectorNumElements();
4029   if (VT.is256BitVector()) {
4030     if (NumElts != 4 && NumElts != 8 &&
4031         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4032     return false;
4033     NumLanes = 2;
4034     NumOf256BitLanes = 1;
4035   } else if (VT.is512BitVector()) {
4036     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4037            "Unsupported vector type for unpckh");
4038     NumLanes = 2;
4039     NumOf256BitLanes = 2;
4040   } else {
4041     NumLanes = 1;
4042     NumOf256BitLanes = 1;
4043   }
4044
4045   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4046   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4047
4048   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4049     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4050       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4051         int BitI  = Mask[l256*NumEltsInStride+l+i];
4052         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4053         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4054           return false;
4055         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4056           return false;
4057         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4058           return false;
4059       }
4060     }
4061   }
4062   return true;
4063 }
4064
4065 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4066 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4067 /// <0, 0, 1, 1>
4068 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4069   unsigned NumElts = VT.getVectorNumElements();
4070   bool Is256BitVec = VT.is256BitVector();
4071
4072   if (VT.is512BitVector())
4073     return false;
4074   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4075          "Unsupported vector type for unpckh");
4076
4077   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4078       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4079     return false;
4080
4081   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4082   // FIXME: Need a better way to get rid of this, there's no latency difference
4083   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4084   // the former later. We should also remove the "_undef" special mask.
4085   if (NumElts == 4 && Is256BitVec)
4086     return false;
4087
4088   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4089   // independently on 128-bit lanes.
4090   unsigned NumLanes = VT.getSizeInBits()/128;
4091   unsigned NumLaneElts = NumElts/NumLanes;
4092
4093   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4094     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4095       int BitI  = Mask[l+i];
4096       int BitI1 = Mask[l+i+1];
4097
4098       if (!isUndefOrEqual(BitI, j))
4099         return false;
4100       if (!isUndefOrEqual(BitI1, j))
4101         return false;
4102     }
4103   }
4104
4105   return true;
4106 }
4107
4108 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4109 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4110 /// <2, 2, 3, 3>
4111 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4112   unsigned NumElts = VT.getVectorNumElements();
4113
4114   if (VT.is512BitVector())
4115     return false;
4116
4117   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4118          "Unsupported vector type for unpckh");
4119
4120   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4121       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4122     return false;
4123
4124   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4125   // independently on 128-bit lanes.
4126   unsigned NumLanes = VT.getSizeInBits()/128;
4127   unsigned NumLaneElts = NumElts/NumLanes;
4128
4129   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4130     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4131       int BitI  = Mask[l+i];
4132       int BitI1 = Mask[l+i+1];
4133       if (!isUndefOrEqual(BitI, j))
4134         return false;
4135       if (!isUndefOrEqual(BitI1, j))
4136         return false;
4137     }
4138   }
4139   return true;
4140 }
4141
4142 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4143 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4144 /// MOVSD, and MOVD, i.e. setting the lowest element.
4145 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4146   if (VT.getVectorElementType().getSizeInBits() < 32)
4147     return false;
4148   if (!VT.is128BitVector())
4149     return false;
4150
4151   unsigned NumElts = VT.getVectorNumElements();
4152
4153   if (!isUndefOrEqual(Mask[0], NumElts))
4154     return false;
4155
4156   for (unsigned i = 1; i != NumElts; ++i)
4157     if (!isUndefOrEqual(Mask[i], i))
4158       return false;
4159
4160   return true;
4161 }
4162
4163 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4164 /// as permutations between 128-bit chunks or halves. As an example: this
4165 /// shuffle bellow:
4166 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4167 /// The first half comes from the second half of V1 and the second half from the
4168 /// the second half of V2.
4169 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4170   if (!HasFp256 || !VT.is256BitVector())
4171     return false;
4172
4173   // The shuffle result is divided into half A and half B. In total the two
4174   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4175   // B must come from C, D, E or F.
4176   unsigned HalfSize = VT.getVectorNumElements()/2;
4177   bool MatchA = false, MatchB = false;
4178
4179   // Check if A comes from one of C, D, E, F.
4180   for (unsigned Half = 0; Half != 4; ++Half) {
4181     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4182       MatchA = true;
4183       break;
4184     }
4185   }
4186
4187   // Check if B comes from one of C, D, E, F.
4188   for (unsigned Half = 0; Half != 4; ++Half) {
4189     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4190       MatchB = true;
4191       break;
4192     }
4193   }
4194
4195   return MatchA && MatchB;
4196 }
4197
4198 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4199 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4200 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4201   MVT VT = SVOp->getSimpleValueType(0);
4202
4203   unsigned HalfSize = VT.getVectorNumElements()/2;
4204
4205   unsigned FstHalf = 0, SndHalf = 0;
4206   for (unsigned i = 0; i < HalfSize; ++i) {
4207     if (SVOp->getMaskElt(i) > 0) {
4208       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4209       break;
4210     }
4211   }
4212   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4213     if (SVOp->getMaskElt(i) > 0) {
4214       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4215       break;
4216     }
4217   }
4218
4219   return (FstHalf | (SndHalf << 4));
4220 }
4221
4222 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4223 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4224   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4225   if (EltSize < 32)
4226     return false;
4227
4228   unsigned NumElts = VT.getVectorNumElements();
4229   Imm8 = 0;
4230   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4231     for (unsigned i = 0; i != NumElts; ++i) {
4232       if (Mask[i] < 0)
4233         continue;
4234       Imm8 |= Mask[i] << (i*2);
4235     }
4236     return true;
4237   }
4238
4239   unsigned LaneSize = 4;
4240   SmallVector<int, 4> MaskVal(LaneSize, -1);
4241
4242   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4243     for (unsigned i = 0; i != LaneSize; ++i) {
4244       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4245         return false;
4246       if (Mask[i+l] < 0)
4247         continue;
4248       if (MaskVal[i] < 0) {
4249         MaskVal[i] = Mask[i+l] - l;
4250         Imm8 |= MaskVal[i] << (i*2);
4251         continue;
4252       }
4253       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4254         return false;
4255     }
4256   }
4257   return true;
4258 }
4259
4260 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4261 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4262 /// Note that VPERMIL mask matching is different depending whether theunderlying
4263 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4264 /// to the same elements of the low, but to the higher half of the source.
4265 /// In VPERMILPD the two lanes could be shuffled independently of each other
4266 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4267 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4268   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4269   if (VT.getSizeInBits() < 256 || EltSize < 32)
4270     return false;
4271   bool symetricMaskRequired = (EltSize == 32);
4272   unsigned NumElts = VT.getVectorNumElements();
4273
4274   unsigned NumLanes = VT.getSizeInBits()/128;
4275   unsigned LaneSize = NumElts/NumLanes;
4276   // 2 or 4 elements in one lane
4277
4278   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4279   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4280     for (unsigned i = 0; i != LaneSize; ++i) {
4281       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4282         return false;
4283       if (symetricMaskRequired) {
4284         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4285           ExpectedMaskVal[i] = Mask[i+l] - l;
4286           continue;
4287         }
4288         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4289           return false;
4290       }
4291     }
4292   }
4293   return true;
4294 }
4295
4296 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4297 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4298 /// element of vector 2 and the other elements to come from vector 1 in order.
4299 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4300                                bool V2IsSplat = false, bool V2IsUndef = false) {
4301   if (!VT.is128BitVector())
4302     return false;
4303
4304   unsigned NumOps = VT.getVectorNumElements();
4305   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4306     return false;
4307
4308   if (!isUndefOrEqual(Mask[0], 0))
4309     return false;
4310
4311   for (unsigned i = 1; i != NumOps; ++i)
4312     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4313           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4314           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4315       return false;
4316
4317   return true;
4318 }
4319
4320 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4321 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4322 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4323 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4324                            const X86Subtarget *Subtarget) {
4325   if (!Subtarget->hasSSE3())
4326     return false;
4327
4328   unsigned NumElems = VT.getVectorNumElements();
4329
4330   if ((VT.is128BitVector() && NumElems != 4) ||
4331       (VT.is256BitVector() && NumElems != 8) ||
4332       (VT.is512BitVector() && NumElems != 16))
4333     return false;
4334
4335   // "i+1" is the value the indexed mask element must have
4336   for (unsigned i = 0; i != NumElems; i += 2)
4337     if (!isUndefOrEqual(Mask[i], i+1) ||
4338         !isUndefOrEqual(Mask[i+1], i+1))
4339       return false;
4340
4341   return true;
4342 }
4343
4344 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4345 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4346 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4347 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4348                            const X86Subtarget *Subtarget) {
4349   if (!Subtarget->hasSSE3())
4350     return false;
4351
4352   unsigned NumElems = VT.getVectorNumElements();
4353
4354   if ((VT.is128BitVector() && NumElems != 4) ||
4355       (VT.is256BitVector() && NumElems != 8) ||
4356       (VT.is512BitVector() && NumElems != 16))
4357     return false;
4358
4359   // "i" is the value the indexed mask element must have
4360   for (unsigned i = 0; i != NumElems; i += 2)
4361     if (!isUndefOrEqual(Mask[i], i) ||
4362         !isUndefOrEqual(Mask[i+1], i))
4363       return false;
4364
4365   return true;
4366 }
4367
4368 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4369 /// specifies a shuffle of elements that is suitable for input to 256-bit
4370 /// version of MOVDDUP.
4371 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4372   if (!HasFp256 || !VT.is256BitVector())
4373     return false;
4374
4375   unsigned NumElts = VT.getVectorNumElements();
4376   if (NumElts != 4)
4377     return false;
4378
4379   for (unsigned i = 0; i != NumElts/2; ++i)
4380     if (!isUndefOrEqual(Mask[i], 0))
4381       return false;
4382   for (unsigned i = NumElts/2; i != NumElts; ++i)
4383     if (!isUndefOrEqual(Mask[i], NumElts/2))
4384       return false;
4385   return true;
4386 }
4387
4388 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4389 /// specifies a shuffle of elements that is suitable for input to 128-bit
4390 /// version of MOVDDUP.
4391 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4392   if (!VT.is128BitVector())
4393     return false;
4394
4395   unsigned e = VT.getVectorNumElements() / 2;
4396   for (unsigned i = 0; i != e; ++i)
4397     if (!isUndefOrEqual(Mask[i], i))
4398       return false;
4399   for (unsigned i = 0; i != e; ++i)
4400     if (!isUndefOrEqual(Mask[e+i], i))
4401       return false;
4402   return true;
4403 }
4404
4405 /// isVEXTRACTIndex - Return true if the specified
4406 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4407 /// suitable for instruction that extract 128 or 256 bit vectors
4408 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4409   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4410   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4411     return false;
4412
4413   // The index should be aligned on a vecWidth-bit boundary.
4414   uint64_t Index =
4415     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4416
4417   MVT VT = N->getSimpleValueType(0);
4418   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4419   bool Result = (Index * ElSize) % vecWidth == 0;
4420
4421   return Result;
4422 }
4423
4424 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4425 /// operand specifies a subvector insert that is suitable for input to
4426 /// insertion of 128 or 256-bit subvectors
4427 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4428   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4429   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4430     return false;
4431   // The index should be aligned on a vecWidth-bit boundary.
4432   uint64_t Index =
4433     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4434
4435   MVT VT = N->getSimpleValueType(0);
4436   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4437   bool Result = (Index * ElSize) % vecWidth == 0;
4438
4439   return Result;
4440 }
4441
4442 bool X86::isVINSERT128Index(SDNode *N) {
4443   return isVINSERTIndex(N, 128);
4444 }
4445
4446 bool X86::isVINSERT256Index(SDNode *N) {
4447   return isVINSERTIndex(N, 256);
4448 }
4449
4450 bool X86::isVEXTRACT128Index(SDNode *N) {
4451   return isVEXTRACTIndex(N, 128);
4452 }
4453
4454 bool X86::isVEXTRACT256Index(SDNode *N) {
4455   return isVEXTRACTIndex(N, 256);
4456 }
4457
4458 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4459 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4460 /// Handles 128-bit and 256-bit.
4461 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4462   MVT VT = N->getSimpleValueType(0);
4463
4464   assert((VT.getSizeInBits() >= 128) &&
4465          "Unsupported vector type for PSHUF/SHUFP");
4466
4467   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4468   // independently on 128-bit lanes.
4469   unsigned NumElts = VT.getVectorNumElements();
4470   unsigned NumLanes = VT.getSizeInBits()/128;
4471   unsigned NumLaneElts = NumElts/NumLanes;
4472
4473   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4474          "Only supports 2, 4 or 8 elements per lane");
4475
4476   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4477   unsigned Mask = 0;
4478   for (unsigned i = 0; i != NumElts; ++i) {
4479     int Elt = N->getMaskElt(i);
4480     if (Elt < 0) continue;
4481     Elt &= NumLaneElts - 1;
4482     unsigned ShAmt = (i << Shift) % 8;
4483     Mask |= Elt << ShAmt;
4484   }
4485
4486   return Mask;
4487 }
4488
4489 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4490 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4491 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4492   MVT VT = N->getSimpleValueType(0);
4493
4494   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4495          "Unsupported vector type for PSHUFHW");
4496
4497   unsigned NumElts = VT.getVectorNumElements();
4498
4499   unsigned Mask = 0;
4500   for (unsigned l = 0; l != NumElts; l += 8) {
4501     // 8 nodes per lane, but we only care about the last 4.
4502     for (unsigned i = 0; i < 4; ++i) {
4503       int Elt = N->getMaskElt(l+i+4);
4504       if (Elt < 0) continue;
4505       Elt &= 0x3; // only 2-bits.
4506       Mask |= Elt << (i * 2);
4507     }
4508   }
4509
4510   return Mask;
4511 }
4512
4513 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4514 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4515 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4516   MVT VT = N->getSimpleValueType(0);
4517
4518   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4519          "Unsupported vector type for PSHUFHW");
4520
4521   unsigned NumElts = VT.getVectorNumElements();
4522
4523   unsigned Mask = 0;
4524   for (unsigned l = 0; l != NumElts; l += 8) {
4525     // 8 nodes per lane, but we only care about the first 4.
4526     for (unsigned i = 0; i < 4; ++i) {
4527       int Elt = N->getMaskElt(l+i);
4528       if (Elt < 0) continue;
4529       Elt &= 0x3; // only 2-bits
4530       Mask |= Elt << (i * 2);
4531     }
4532   }
4533
4534   return Mask;
4535 }
4536
4537 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4538 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4539 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4540   MVT VT = SVOp->getSimpleValueType(0);
4541   unsigned EltSize = VT.is512BitVector() ? 1 :
4542     VT.getVectorElementType().getSizeInBits() >> 3;
4543
4544   unsigned NumElts = VT.getVectorNumElements();
4545   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4546   unsigned NumLaneElts = NumElts/NumLanes;
4547
4548   int Val = 0;
4549   unsigned i;
4550   for (i = 0; i != NumElts; ++i) {
4551     Val = SVOp->getMaskElt(i);
4552     if (Val >= 0)
4553       break;
4554   }
4555   if (Val >= (int)NumElts)
4556     Val -= NumElts - NumLaneElts;
4557
4558   assert(Val - i > 0 && "PALIGNR imm should be positive");
4559   return (Val - i) * EltSize;
4560 }
4561
4562 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4563   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4564   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4565     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4566
4567   uint64_t Index =
4568     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4569
4570   MVT VecVT = N->getOperand(0).getSimpleValueType();
4571   MVT ElVT = VecVT.getVectorElementType();
4572
4573   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4574   return Index / NumElemsPerChunk;
4575 }
4576
4577 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4578   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4579   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4580     llvm_unreachable("Illegal insert subvector for VINSERT");
4581
4582   uint64_t Index =
4583     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4584
4585   MVT VecVT = N->getSimpleValueType(0);
4586   MVT ElVT = VecVT.getVectorElementType();
4587
4588   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4589   return Index / NumElemsPerChunk;
4590 }
4591
4592 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4593 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4594 /// and VINSERTI128 instructions.
4595 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4596   return getExtractVEXTRACTImmediate(N, 128);
4597 }
4598
4599 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4600 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4601 /// and VINSERTI64x4 instructions.
4602 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4603   return getExtractVEXTRACTImmediate(N, 256);
4604 }
4605
4606 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4607 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4608 /// and VINSERTI128 instructions.
4609 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4610   return getInsertVINSERTImmediate(N, 128);
4611 }
4612
4613 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4614 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4615 /// and VINSERTI64x4 instructions.
4616 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4617   return getInsertVINSERTImmediate(N, 256);
4618 }
4619
4620 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4621 /// constant +0.0.
4622 bool X86::isZeroNode(SDValue Elt) {
4623   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4624     return CN->isNullValue();
4625   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4626     return CFP->getValueAPF().isPosZero();
4627   return false;
4628 }
4629
4630 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4631 /// their permute mask.
4632 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4633                                     SelectionDAG &DAG) {
4634   MVT VT = SVOp->getSimpleValueType(0);
4635   unsigned NumElems = VT.getVectorNumElements();
4636   SmallVector<int, 8> MaskVec;
4637
4638   for (unsigned i = 0; i != NumElems; ++i) {
4639     int Idx = SVOp->getMaskElt(i);
4640     if (Idx >= 0) {
4641       if (Idx < (int)NumElems)
4642         Idx += NumElems;
4643       else
4644         Idx -= NumElems;
4645     }
4646     MaskVec.push_back(Idx);
4647   }
4648   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4649                               SVOp->getOperand(0), &MaskVec[0]);
4650 }
4651
4652 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4653 /// match movhlps. The lower half elements should come from upper half of
4654 /// V1 (and in order), and the upper half elements should come from the upper
4655 /// half of V2 (and in order).
4656 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4657   if (!VT.is128BitVector())
4658     return false;
4659   if (VT.getVectorNumElements() != 4)
4660     return false;
4661   for (unsigned i = 0, e = 2; i != e; ++i)
4662     if (!isUndefOrEqual(Mask[i], i+2))
4663       return false;
4664   for (unsigned i = 2; i != 4; ++i)
4665     if (!isUndefOrEqual(Mask[i], i+4))
4666       return false;
4667   return true;
4668 }
4669
4670 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4671 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4672 /// required.
4673 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4674   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4675     return false;
4676   N = N->getOperand(0).getNode();
4677   if (!ISD::isNON_EXTLoad(N))
4678     return false;
4679   if (LD)
4680     *LD = cast<LoadSDNode>(N);
4681   return true;
4682 }
4683
4684 // Test whether the given value is a vector value which will be legalized
4685 // into a load.
4686 static bool WillBeConstantPoolLoad(SDNode *N) {
4687   if (N->getOpcode() != ISD::BUILD_VECTOR)
4688     return false;
4689
4690   // Check for any non-constant elements.
4691   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4692     switch (N->getOperand(i).getNode()->getOpcode()) {
4693     case ISD::UNDEF:
4694     case ISD::ConstantFP:
4695     case ISD::Constant:
4696       break;
4697     default:
4698       return false;
4699     }
4700
4701   // Vectors of all-zeros and all-ones are materialized with special
4702   // instructions rather than being loaded.
4703   return !ISD::isBuildVectorAllZeros(N) &&
4704          !ISD::isBuildVectorAllOnes(N);
4705 }
4706
4707 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4708 /// match movlp{s|d}. The lower half elements should come from lower half of
4709 /// V1 (and in order), and the upper half elements should come from the upper
4710 /// half of V2 (and in order). And since V1 will become the source of the
4711 /// MOVLP, it must be either a vector load or a scalar load to vector.
4712 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4713                                ArrayRef<int> Mask, MVT VT) {
4714   if (!VT.is128BitVector())
4715     return false;
4716
4717   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4718     return false;
4719   // Is V2 is a vector load, don't do this transformation. We will try to use
4720   // load folding shufps op.
4721   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4722     return false;
4723
4724   unsigned NumElems = VT.getVectorNumElements();
4725
4726   if (NumElems != 2 && NumElems != 4)
4727     return false;
4728   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4729     if (!isUndefOrEqual(Mask[i], i))
4730       return false;
4731   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4732     if (!isUndefOrEqual(Mask[i], i+NumElems))
4733       return false;
4734   return true;
4735 }
4736
4737 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4738 /// all the same.
4739 static bool isSplatVector(SDNode *N) {
4740   if (N->getOpcode() != ISD::BUILD_VECTOR)
4741     return false;
4742
4743   SDValue SplatValue = N->getOperand(0);
4744   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4745     if (N->getOperand(i) != SplatValue)
4746       return false;
4747   return true;
4748 }
4749
4750 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4751 /// to an zero vector.
4752 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4753 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4754   SDValue V1 = N->getOperand(0);
4755   SDValue V2 = N->getOperand(1);
4756   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4757   for (unsigned i = 0; i != NumElems; ++i) {
4758     int Idx = N->getMaskElt(i);
4759     if (Idx >= (int)NumElems) {
4760       unsigned Opc = V2.getOpcode();
4761       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4762         continue;
4763       if (Opc != ISD::BUILD_VECTOR ||
4764           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4765         return false;
4766     } else if (Idx >= 0) {
4767       unsigned Opc = V1.getOpcode();
4768       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4769         continue;
4770       if (Opc != ISD::BUILD_VECTOR ||
4771           !X86::isZeroNode(V1.getOperand(Idx)))
4772         return false;
4773     }
4774   }
4775   return true;
4776 }
4777
4778 /// getZeroVector - Returns a vector of specified type with all zero elements.
4779 ///
4780 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4781                              SelectionDAG &DAG, SDLoc dl) {
4782   assert(VT.isVector() && "Expected a vector type");
4783
4784   // Always build SSE zero vectors as <4 x i32> bitcasted
4785   // to their dest type. This ensures they get CSE'd.
4786   SDValue Vec;
4787   if (VT.is128BitVector()) {  // SSE
4788     if (Subtarget->hasSSE2()) {  // SSE2
4789       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4790       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4791     } else { // SSE1
4792       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4793       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4794     }
4795   } else if (VT.is256BitVector()) { // AVX
4796     if (Subtarget->hasInt256()) { // AVX2
4797       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4798       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4799       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4800                         array_lengthof(Ops));
4801     } else {
4802       // 256-bit logic and arithmetic instructions in AVX are all
4803       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4804       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4805       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4806       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4807                         array_lengthof(Ops));
4808     }
4809   } else if (VT.is512BitVector()) { // AVX-512
4810       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4811       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4812                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4813       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4814   } else
4815     llvm_unreachable("Unexpected vector type");
4816
4817   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4818 }
4819
4820 /// getOnesVector - Returns a vector of specified type with all bits set.
4821 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4822 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4823 /// Then bitcast to their original type, ensuring they get CSE'd.
4824 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4825                              SDLoc dl) {
4826   assert(VT.isVector() && "Expected a vector type");
4827
4828   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4829   SDValue Vec;
4830   if (VT.is256BitVector()) {
4831     if (HasInt256) { // AVX2
4832       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4833       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4834                         array_lengthof(Ops));
4835     } else { // AVX
4836       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4837       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4838     }
4839   } else if (VT.is128BitVector()) {
4840     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4841   } else
4842     llvm_unreachable("Unexpected vector type");
4843
4844   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4845 }
4846
4847 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4848 /// that point to V2 points to its first element.
4849 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4850   for (unsigned i = 0; i != NumElems; ++i) {
4851     if (Mask[i] > (int)NumElems) {
4852       Mask[i] = NumElems;
4853     }
4854   }
4855 }
4856
4857 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4858 /// operation of specified width.
4859 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4860                        SDValue V2) {
4861   unsigned NumElems = VT.getVectorNumElements();
4862   SmallVector<int, 8> Mask;
4863   Mask.push_back(NumElems);
4864   for (unsigned i = 1; i != NumElems; ++i)
4865     Mask.push_back(i);
4866   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4867 }
4868
4869 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4870 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4871                           SDValue V2) {
4872   unsigned NumElems = VT.getVectorNumElements();
4873   SmallVector<int, 8> Mask;
4874   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4875     Mask.push_back(i);
4876     Mask.push_back(i + NumElems);
4877   }
4878   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4879 }
4880
4881 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4882 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4883                           SDValue V2) {
4884   unsigned NumElems = VT.getVectorNumElements();
4885   SmallVector<int, 8> Mask;
4886   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4887     Mask.push_back(i + Half);
4888     Mask.push_back(i + NumElems + Half);
4889   }
4890   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4891 }
4892
4893 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4894 // a generic shuffle instruction because the target has no such instructions.
4895 // Generate shuffles which repeat i16 and i8 several times until they can be
4896 // represented by v4f32 and then be manipulated by target suported shuffles.
4897 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4898   MVT VT = V.getSimpleValueType();
4899   int NumElems = VT.getVectorNumElements();
4900   SDLoc dl(V);
4901
4902   while (NumElems > 4) {
4903     if (EltNo < NumElems/2) {
4904       V = getUnpackl(DAG, dl, VT, V, V);
4905     } else {
4906       V = getUnpackh(DAG, dl, VT, V, V);
4907       EltNo -= NumElems/2;
4908     }
4909     NumElems >>= 1;
4910   }
4911   return V;
4912 }
4913
4914 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4915 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4916   MVT VT = V.getSimpleValueType();
4917   SDLoc dl(V);
4918
4919   if (VT.is128BitVector()) {
4920     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4921     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4922     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4923                              &SplatMask[0]);
4924   } else if (VT.is256BitVector()) {
4925     // To use VPERMILPS to splat scalars, the second half of indicies must
4926     // refer to the higher part, which is a duplication of the lower one,
4927     // because VPERMILPS can only handle in-lane permutations.
4928     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4929                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4930
4931     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4932     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4933                              &SplatMask[0]);
4934   } else
4935     llvm_unreachable("Vector size not supported");
4936
4937   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4938 }
4939
4940 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4941 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4942   MVT SrcVT = SV->getSimpleValueType(0);
4943   SDValue V1 = SV->getOperand(0);
4944   SDLoc dl(SV);
4945
4946   int EltNo = SV->getSplatIndex();
4947   int NumElems = SrcVT.getVectorNumElements();
4948   bool Is256BitVec = SrcVT.is256BitVector();
4949
4950   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4951          "Unknown how to promote splat for type");
4952
4953   // Extract the 128-bit part containing the splat element and update
4954   // the splat element index when it refers to the higher register.
4955   if (Is256BitVec) {
4956     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4957     if (EltNo >= NumElems/2)
4958       EltNo -= NumElems/2;
4959   }
4960
4961   // All i16 and i8 vector types can't be used directly by a generic shuffle
4962   // instruction because the target has no such instruction. Generate shuffles
4963   // which repeat i16 and i8 several times until they fit in i32, and then can
4964   // be manipulated by target suported shuffles.
4965   MVT EltVT = SrcVT.getVectorElementType();
4966   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4967     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4968
4969   // Recreate the 256-bit vector and place the same 128-bit vector
4970   // into the low and high part. This is necessary because we want
4971   // to use VPERM* to shuffle the vectors
4972   if (Is256BitVec) {
4973     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4974   }
4975
4976   return getLegalSplat(DAG, V1, EltNo);
4977 }
4978
4979 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4980 /// vector of zero or undef vector.  This produces a shuffle where the low
4981 /// element of V2 is swizzled into the zero/undef vector, landing at element
4982 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4983 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4984                                            bool IsZero,
4985                                            const X86Subtarget *Subtarget,
4986                                            SelectionDAG &DAG) {
4987   MVT VT = V2.getSimpleValueType();
4988   SDValue V1 = IsZero
4989     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4990   unsigned NumElems = VT.getVectorNumElements();
4991   SmallVector<int, 16> MaskVec;
4992   for (unsigned i = 0; i != NumElems; ++i)
4993     // If this is the insertion idx, put the low elt of V2 here.
4994     MaskVec.push_back(i == Idx ? NumElems : i);
4995   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4996 }
4997
4998 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4999 /// target specific opcode. Returns true if the Mask could be calculated.
5000 /// Sets IsUnary to true if only uses one source.
5001 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5002                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5003   unsigned NumElems = VT.getVectorNumElements();
5004   SDValue ImmN;
5005
5006   IsUnary = false;
5007   switch(N->getOpcode()) {
5008   case X86ISD::SHUFP:
5009     ImmN = N->getOperand(N->getNumOperands()-1);
5010     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5011     break;
5012   case X86ISD::UNPCKH:
5013     DecodeUNPCKHMask(VT, Mask);
5014     break;
5015   case X86ISD::UNPCKL:
5016     DecodeUNPCKLMask(VT, Mask);
5017     break;
5018   case X86ISD::MOVHLPS:
5019     DecodeMOVHLPSMask(NumElems, Mask);
5020     break;
5021   case X86ISD::MOVLHPS:
5022     DecodeMOVLHPSMask(NumElems, Mask);
5023     break;
5024   case X86ISD::PALIGNR:
5025     ImmN = N->getOperand(N->getNumOperands()-1);
5026     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5027     break;
5028   case X86ISD::PSHUFD:
5029   case X86ISD::VPERMILP:
5030     ImmN = N->getOperand(N->getNumOperands()-1);
5031     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5032     IsUnary = true;
5033     break;
5034   case X86ISD::PSHUFHW:
5035     ImmN = N->getOperand(N->getNumOperands()-1);
5036     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5037     IsUnary = true;
5038     break;
5039   case X86ISD::PSHUFLW:
5040     ImmN = N->getOperand(N->getNumOperands()-1);
5041     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5042     IsUnary = true;
5043     break;
5044   case X86ISD::VPERMI:
5045     ImmN = N->getOperand(N->getNumOperands()-1);
5046     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5047     IsUnary = true;
5048     break;
5049   case X86ISD::MOVSS:
5050   case X86ISD::MOVSD: {
5051     // The index 0 always comes from the first element of the second source,
5052     // this is why MOVSS and MOVSD are used in the first place. The other
5053     // elements come from the other positions of the first source vector
5054     Mask.push_back(NumElems);
5055     for (unsigned i = 1; i != NumElems; ++i) {
5056       Mask.push_back(i);
5057     }
5058     break;
5059   }
5060   case X86ISD::VPERM2X128:
5061     ImmN = N->getOperand(N->getNumOperands()-1);
5062     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5063     if (Mask.empty()) return false;
5064     break;
5065   case X86ISD::MOVDDUP:
5066   case X86ISD::MOVLHPD:
5067   case X86ISD::MOVLPD:
5068   case X86ISD::MOVLPS:
5069   case X86ISD::MOVSHDUP:
5070   case X86ISD::MOVSLDUP:
5071     // Not yet implemented
5072     return false;
5073   default: llvm_unreachable("unknown target shuffle node");
5074   }
5075
5076   return true;
5077 }
5078
5079 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5080 /// element of the result of the vector shuffle.
5081 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5082                                    unsigned Depth) {
5083   if (Depth == 6)
5084     return SDValue();  // Limit search depth.
5085
5086   SDValue V = SDValue(N, 0);
5087   EVT VT = V.getValueType();
5088   unsigned Opcode = V.getOpcode();
5089
5090   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5091   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5092     int Elt = SV->getMaskElt(Index);
5093
5094     if (Elt < 0)
5095       return DAG.getUNDEF(VT.getVectorElementType());
5096
5097     unsigned NumElems = VT.getVectorNumElements();
5098     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5099                                          : SV->getOperand(1);
5100     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5101   }
5102
5103   // Recurse into target specific vector shuffles to find scalars.
5104   if (isTargetShuffle(Opcode)) {
5105     MVT ShufVT = V.getSimpleValueType();
5106     unsigned NumElems = ShufVT.getVectorNumElements();
5107     SmallVector<int, 16> ShuffleMask;
5108     bool IsUnary;
5109
5110     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5111       return SDValue();
5112
5113     int Elt = ShuffleMask[Index];
5114     if (Elt < 0)
5115       return DAG.getUNDEF(ShufVT.getVectorElementType());
5116
5117     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5118                                          : N->getOperand(1);
5119     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5120                                Depth+1);
5121   }
5122
5123   // Actual nodes that may contain scalar elements
5124   if (Opcode == ISD::BITCAST) {
5125     V = V.getOperand(0);
5126     EVT SrcVT = V.getValueType();
5127     unsigned NumElems = VT.getVectorNumElements();
5128
5129     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5130       return SDValue();
5131   }
5132
5133   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5134     return (Index == 0) ? V.getOperand(0)
5135                         : DAG.getUNDEF(VT.getVectorElementType());
5136
5137   if (V.getOpcode() == ISD::BUILD_VECTOR)
5138     return V.getOperand(Index);
5139
5140   return SDValue();
5141 }
5142
5143 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5144 /// shuffle operation which come from a consecutively from a zero. The
5145 /// search can start in two different directions, from left or right.
5146 /// We count undefs as zeros until PreferredNum is reached.
5147 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5148                                          unsigned NumElems, bool ZerosFromLeft,
5149                                          SelectionDAG &DAG,
5150                                          unsigned PreferredNum = -1U) {
5151   unsigned NumZeros = 0;
5152   for (unsigned i = 0; i != NumElems; ++i) {
5153     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5154     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5155     if (!Elt.getNode())
5156       break;
5157
5158     if (X86::isZeroNode(Elt))
5159       ++NumZeros;
5160     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5161       NumZeros = std::min(NumZeros + 1, PreferredNum);
5162     else
5163       break;
5164   }
5165
5166   return NumZeros;
5167 }
5168
5169 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5170 /// correspond consecutively to elements from one of the vector operands,
5171 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5172 static
5173 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5174                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5175                               unsigned NumElems, unsigned &OpNum) {
5176   bool SeenV1 = false;
5177   bool SeenV2 = false;
5178
5179   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5180     int Idx = SVOp->getMaskElt(i);
5181     // Ignore undef indicies
5182     if (Idx < 0)
5183       continue;
5184
5185     if (Idx < (int)NumElems)
5186       SeenV1 = true;
5187     else
5188       SeenV2 = true;
5189
5190     // Only accept consecutive elements from the same vector
5191     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5192       return false;
5193   }
5194
5195   OpNum = SeenV1 ? 0 : 1;
5196   return true;
5197 }
5198
5199 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5200 /// logical left shift of a vector.
5201 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5202                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5203   unsigned NumElems =
5204     SVOp->getSimpleValueType(0).getVectorNumElements();
5205   unsigned NumZeros = getNumOfConsecutiveZeros(
5206       SVOp, NumElems, false /* check zeros from right */, DAG,
5207       SVOp->getMaskElt(0));
5208   unsigned OpSrc;
5209
5210   if (!NumZeros)
5211     return false;
5212
5213   // Considering the elements in the mask that are not consecutive zeros,
5214   // check if they consecutively come from only one of the source vectors.
5215   //
5216   //               V1 = {X, A, B, C}     0
5217   //                         \  \  \    /
5218   //   vector_shuffle V1, V2 <1, 2, 3, X>
5219   //
5220   if (!isShuffleMaskConsecutive(SVOp,
5221             0,                   // Mask Start Index
5222             NumElems-NumZeros,   // Mask End Index(exclusive)
5223             NumZeros,            // Where to start looking in the src vector
5224             NumElems,            // Number of elements in vector
5225             OpSrc))              // Which source operand ?
5226     return false;
5227
5228   isLeft = false;
5229   ShAmt = NumZeros;
5230   ShVal = SVOp->getOperand(OpSrc);
5231   return true;
5232 }
5233
5234 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5235 /// logical left shift of a vector.
5236 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5237                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5238   unsigned NumElems =
5239     SVOp->getSimpleValueType(0).getVectorNumElements();
5240   unsigned NumZeros = getNumOfConsecutiveZeros(
5241       SVOp, NumElems, true /* check zeros from left */, DAG,
5242       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5243   unsigned OpSrc;
5244
5245   if (!NumZeros)
5246     return false;
5247
5248   // Considering the elements in the mask that are not consecutive zeros,
5249   // check if they consecutively come from only one of the source vectors.
5250   //
5251   //                           0    { A, B, X, X } = V2
5252   //                          / \    /  /
5253   //   vector_shuffle V1, V2 <X, X, 4, 5>
5254   //
5255   if (!isShuffleMaskConsecutive(SVOp,
5256             NumZeros,     // Mask Start Index
5257             NumElems,     // Mask End Index(exclusive)
5258             0,            // Where to start looking in the src vector
5259             NumElems,     // Number of elements in vector
5260             OpSrc))       // Which source operand ?
5261     return false;
5262
5263   isLeft = true;
5264   ShAmt = NumZeros;
5265   ShVal = SVOp->getOperand(OpSrc);
5266   return true;
5267 }
5268
5269 /// isVectorShift - Returns true if the shuffle can be implemented as a
5270 /// logical left or right shift of a vector.
5271 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5272                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5273   // Although the logic below support any bitwidth size, there are no
5274   // shift instructions which handle more than 128-bit vectors.
5275   if (!SVOp->getSimpleValueType(0).is128BitVector())
5276     return false;
5277
5278   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5279       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5280     return true;
5281
5282   return false;
5283 }
5284
5285 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5286 ///
5287 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5288                                        unsigned NumNonZero, unsigned NumZero,
5289                                        SelectionDAG &DAG,
5290                                        const X86Subtarget* Subtarget,
5291                                        const TargetLowering &TLI) {
5292   if (NumNonZero > 8)
5293     return SDValue();
5294
5295   SDLoc dl(Op);
5296   SDValue V(0, 0);
5297   bool First = true;
5298   for (unsigned i = 0; i < 16; ++i) {
5299     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5300     if (ThisIsNonZero && First) {
5301       if (NumZero)
5302         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5303       else
5304         V = DAG.getUNDEF(MVT::v8i16);
5305       First = false;
5306     }
5307
5308     if ((i & 1) != 0) {
5309       SDValue ThisElt(0, 0), LastElt(0, 0);
5310       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5311       if (LastIsNonZero) {
5312         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5313                               MVT::i16, Op.getOperand(i-1));
5314       }
5315       if (ThisIsNonZero) {
5316         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5317         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5318                               ThisElt, DAG.getConstant(8, MVT::i8));
5319         if (LastIsNonZero)
5320           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5321       } else
5322         ThisElt = LastElt;
5323
5324       if (ThisElt.getNode())
5325         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5326                         DAG.getIntPtrConstant(i/2));
5327     }
5328   }
5329
5330   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5331 }
5332
5333 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5334 ///
5335 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5336                                      unsigned NumNonZero, unsigned NumZero,
5337                                      SelectionDAG &DAG,
5338                                      const X86Subtarget* Subtarget,
5339                                      const TargetLowering &TLI) {
5340   if (NumNonZero > 4)
5341     return SDValue();
5342
5343   SDLoc dl(Op);
5344   SDValue V(0, 0);
5345   bool First = true;
5346   for (unsigned i = 0; i < 8; ++i) {
5347     bool isNonZero = (NonZeros & (1 << i)) != 0;
5348     if (isNonZero) {
5349       if (First) {
5350         if (NumZero)
5351           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5352         else
5353           V = DAG.getUNDEF(MVT::v8i16);
5354         First = false;
5355       }
5356       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5357                       MVT::v8i16, V, Op.getOperand(i),
5358                       DAG.getIntPtrConstant(i));
5359     }
5360   }
5361
5362   return V;
5363 }
5364
5365 /// getVShift - Return a vector logical shift node.
5366 ///
5367 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5368                          unsigned NumBits, SelectionDAG &DAG,
5369                          const TargetLowering &TLI, SDLoc dl) {
5370   assert(VT.is128BitVector() && "Unknown type for VShift");
5371   EVT ShVT = MVT::v2i64;
5372   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5373   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5374   return DAG.getNode(ISD::BITCAST, dl, VT,
5375                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5376                              DAG.getConstant(NumBits,
5377                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5378 }
5379
5380 static SDValue
5381 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5382
5383   // Check if the scalar load can be widened into a vector load. And if
5384   // the address is "base + cst" see if the cst can be "absorbed" into
5385   // the shuffle mask.
5386   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5387     SDValue Ptr = LD->getBasePtr();
5388     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5389       return SDValue();
5390     EVT PVT = LD->getValueType(0);
5391     if (PVT != MVT::i32 && PVT != MVT::f32)
5392       return SDValue();
5393
5394     int FI = -1;
5395     int64_t Offset = 0;
5396     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5397       FI = FINode->getIndex();
5398       Offset = 0;
5399     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5400                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5401       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5402       Offset = Ptr.getConstantOperandVal(1);
5403       Ptr = Ptr.getOperand(0);
5404     } else {
5405       return SDValue();
5406     }
5407
5408     // FIXME: 256-bit vector instructions don't require a strict alignment,
5409     // improve this code to support it better.
5410     unsigned RequiredAlign = VT.getSizeInBits()/8;
5411     SDValue Chain = LD->getChain();
5412     // Make sure the stack object alignment is at least 16 or 32.
5413     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5414     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5415       if (MFI->isFixedObjectIndex(FI)) {
5416         // Can't change the alignment. FIXME: It's possible to compute
5417         // the exact stack offset and reference FI + adjust offset instead.
5418         // If someone *really* cares about this. That's the way to implement it.
5419         return SDValue();
5420       } else {
5421         MFI->setObjectAlignment(FI, RequiredAlign);
5422       }
5423     }
5424
5425     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5426     // Ptr + (Offset & ~15).
5427     if (Offset < 0)
5428       return SDValue();
5429     if ((Offset % RequiredAlign) & 3)
5430       return SDValue();
5431     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5432     if (StartOffset)
5433       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5434                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5435
5436     int EltNo = (Offset - StartOffset) >> 2;
5437     unsigned NumElems = VT.getVectorNumElements();
5438
5439     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5440     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5441                              LD->getPointerInfo().getWithOffset(StartOffset),
5442                              false, false, false, 0);
5443
5444     SmallVector<int, 8> Mask;
5445     for (unsigned i = 0; i != NumElems; ++i)
5446       Mask.push_back(EltNo);
5447
5448     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5449   }
5450
5451   return SDValue();
5452 }
5453
5454 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5455 /// vector of type 'VT', see if the elements can be replaced by a single large
5456 /// load which has the same value as a build_vector whose operands are 'elts'.
5457 ///
5458 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5459 ///
5460 /// FIXME: we'd also like to handle the case where the last elements are zero
5461 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5462 /// There's even a handy isZeroNode for that purpose.
5463 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5464                                         SDLoc &DL, SelectionDAG &DAG,
5465                                         bool isAfterLegalize) {
5466   EVT EltVT = VT.getVectorElementType();
5467   unsigned NumElems = Elts.size();
5468
5469   LoadSDNode *LDBase = NULL;
5470   unsigned LastLoadedElt = -1U;
5471
5472   // For each element in the initializer, see if we've found a load or an undef.
5473   // If we don't find an initial load element, or later load elements are
5474   // non-consecutive, bail out.
5475   for (unsigned i = 0; i < NumElems; ++i) {
5476     SDValue Elt = Elts[i];
5477
5478     if (!Elt.getNode() ||
5479         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5480       return SDValue();
5481     if (!LDBase) {
5482       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5483         return SDValue();
5484       LDBase = cast<LoadSDNode>(Elt.getNode());
5485       LastLoadedElt = i;
5486       continue;
5487     }
5488     if (Elt.getOpcode() == ISD::UNDEF)
5489       continue;
5490
5491     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5492     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5493       return SDValue();
5494     LastLoadedElt = i;
5495   }
5496
5497   // If we have found an entire vector of loads and undefs, then return a large
5498   // load of the entire vector width starting at the base pointer.  If we found
5499   // consecutive loads for the low half, generate a vzext_load node.
5500   if (LastLoadedElt == NumElems - 1) {
5501
5502     if (isAfterLegalize &&
5503         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5504       return SDValue();
5505
5506     SDValue NewLd = SDValue();
5507
5508     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5509       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5510                           LDBase->getPointerInfo(),
5511                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5512                           LDBase->isInvariant(), 0);
5513     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5514                         LDBase->getPointerInfo(),
5515                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5516                         LDBase->isInvariant(), LDBase->getAlignment());
5517
5518     if (LDBase->hasAnyUseOfValue(1)) {
5519       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5520                                      SDValue(LDBase, 1),
5521                                      SDValue(NewLd.getNode(), 1));
5522       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5523       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5524                              SDValue(NewLd.getNode(), 1));
5525     }
5526
5527     return NewLd;
5528   }
5529   if (NumElems == 4 && LastLoadedElt == 1 &&
5530       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5531     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5532     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5533     SDValue ResNode =
5534         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5535                                 array_lengthof(Ops), MVT::i64,
5536                                 LDBase->getPointerInfo(),
5537                                 LDBase->getAlignment(),
5538                                 false/*isVolatile*/, true/*ReadMem*/,
5539                                 false/*WriteMem*/);
5540
5541     // Make sure the newly-created LOAD is in the same position as LDBase in
5542     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5543     // update uses of LDBase's output chain to use the TokenFactor.
5544     if (LDBase->hasAnyUseOfValue(1)) {
5545       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5546                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5547       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5548       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5549                              SDValue(ResNode.getNode(), 1));
5550     }
5551
5552     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5553   }
5554   return SDValue();
5555 }
5556
5557 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5558 /// to generate a splat value for the following cases:
5559 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5560 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5561 /// a scalar load, or a constant.
5562 /// The VBROADCAST node is returned when a pattern is found,
5563 /// or SDValue() otherwise.
5564 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5565                                     SelectionDAG &DAG) {
5566   if (!Subtarget->hasFp256())
5567     return SDValue();
5568
5569   MVT VT = Op.getSimpleValueType();
5570   SDLoc dl(Op);
5571
5572   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5573          "Unsupported vector type for broadcast.");
5574
5575   SDValue Ld;
5576   bool ConstSplatVal;
5577
5578   switch (Op.getOpcode()) {
5579     default:
5580       // Unknown pattern found.
5581       return SDValue();
5582
5583     case ISD::BUILD_VECTOR: {
5584       // The BUILD_VECTOR node must be a splat.
5585       if (!isSplatVector(Op.getNode()))
5586         return SDValue();
5587
5588       Ld = Op.getOperand(0);
5589       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5590                      Ld.getOpcode() == ISD::ConstantFP);
5591
5592       // The suspected load node has several users. Make sure that all
5593       // of its users are from the BUILD_VECTOR node.
5594       // Constants may have multiple users.
5595       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5596         return SDValue();
5597       break;
5598     }
5599
5600     case ISD::VECTOR_SHUFFLE: {
5601       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5602
5603       // Shuffles must have a splat mask where the first element is
5604       // broadcasted.
5605       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5606         return SDValue();
5607
5608       SDValue Sc = Op.getOperand(0);
5609       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5610           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5611
5612         if (!Subtarget->hasInt256())
5613           return SDValue();
5614
5615         // Use the register form of the broadcast instruction available on AVX2.
5616         if (VT.getSizeInBits() >= 256)
5617           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5618         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5619       }
5620
5621       Ld = Sc.getOperand(0);
5622       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5623                        Ld.getOpcode() == ISD::ConstantFP);
5624
5625       // The scalar_to_vector node and the suspected
5626       // load node must have exactly one user.
5627       // Constants may have multiple users.
5628
5629       // AVX-512 has register version of the broadcast
5630       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5631         Ld.getValueType().getSizeInBits() >= 32;
5632       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5633           !hasRegVer))
5634         return SDValue();
5635       break;
5636     }
5637   }
5638
5639   bool IsGE256 = (VT.getSizeInBits() >= 256);
5640
5641   // Handle the broadcasting a single constant scalar from the constant pool
5642   // into a vector. On Sandybridge it is still better to load a constant vector
5643   // from the constant pool and not to broadcast it from a scalar.
5644   if (ConstSplatVal && Subtarget->hasInt256()) {
5645     EVT CVT = Ld.getValueType();
5646     assert(!CVT.isVector() && "Must not broadcast a vector type");
5647     unsigned ScalarSize = CVT.getSizeInBits();
5648
5649     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5650       const Constant *C = 0;
5651       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5652         C = CI->getConstantIntValue();
5653       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5654         C = CF->getConstantFPValue();
5655
5656       assert(C && "Invalid constant type");
5657
5658       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5659       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5660       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5661       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5662                        MachinePointerInfo::getConstantPool(),
5663                        false, false, false, Alignment);
5664
5665       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5666     }
5667   }
5668
5669   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5670   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5671
5672   // Handle AVX2 in-register broadcasts.
5673   if (!IsLoad && Subtarget->hasInt256() &&
5674       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5675     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5676
5677   // The scalar source must be a normal load.
5678   if (!IsLoad)
5679     return SDValue();
5680
5681   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5682     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5683
5684   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5685   // double since there is no vbroadcastsd xmm
5686   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5687     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5688       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5689   }
5690
5691   // Unsupported broadcast.
5692   return SDValue();
5693 }
5694
5695 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5696   MVT VT = Op.getSimpleValueType();
5697
5698   // Skip if insert_vec_elt is not supported.
5699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5700   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5701     return SDValue();
5702
5703   SDLoc DL(Op);
5704   unsigned NumElems = Op.getNumOperands();
5705
5706   SDValue VecIn1;
5707   SDValue VecIn2;
5708   SmallVector<unsigned, 4> InsertIndices;
5709   SmallVector<int, 8> Mask(NumElems, -1);
5710
5711   for (unsigned i = 0; i != NumElems; ++i) {
5712     unsigned Opc = Op.getOperand(i).getOpcode();
5713
5714     if (Opc == ISD::UNDEF)
5715       continue;
5716
5717     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5718       // Quit if more than 1 elements need inserting.
5719       if (InsertIndices.size() > 1)
5720         return SDValue();
5721
5722       InsertIndices.push_back(i);
5723       continue;
5724     }
5725
5726     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5727     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5728
5729     // Quit if extracted from vector of different type.
5730     if (ExtractedFromVec.getValueType() != VT)
5731       return SDValue();
5732
5733     // Quit if non-constant index.
5734     if (!isa<ConstantSDNode>(ExtIdx))
5735       return SDValue();
5736
5737     if (VecIn1.getNode() == 0)
5738       VecIn1 = ExtractedFromVec;
5739     else if (VecIn1 != ExtractedFromVec) {
5740       if (VecIn2.getNode() == 0)
5741         VecIn2 = ExtractedFromVec;
5742       else if (VecIn2 != ExtractedFromVec)
5743         // Quit if more than 2 vectors to shuffle
5744         return SDValue();
5745     }
5746
5747     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5748
5749     if (ExtractedFromVec == VecIn1)
5750       Mask[i] = Idx;
5751     else if (ExtractedFromVec == VecIn2)
5752       Mask[i] = Idx + NumElems;
5753   }
5754
5755   if (VecIn1.getNode() == 0)
5756     return SDValue();
5757
5758   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5759   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5760   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5761     unsigned Idx = InsertIndices[i];
5762     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5763                      DAG.getIntPtrConstant(Idx));
5764   }
5765
5766   return NV;
5767 }
5768
5769 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5770 SDValue
5771 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5772
5773   MVT VT = Op.getSimpleValueType();
5774   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5775          "Unexpected type in LowerBUILD_VECTORvXi1!");
5776
5777   SDLoc dl(Op);
5778   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5779     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5780     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5781                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5782     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5783                        Ops, VT.getVectorNumElements());
5784   }
5785
5786   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5787     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5788     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5789                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5790     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5791                        Ops, VT.getVectorNumElements());
5792   }
5793
5794   bool AllContants = true;
5795   uint64_t Immediate = 0;
5796   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5797     SDValue In = Op.getOperand(idx);
5798     if (In.getOpcode() == ISD::UNDEF)
5799       continue;
5800     if (!isa<ConstantSDNode>(In)) {
5801       AllContants = false;
5802       break;
5803     }
5804     if (cast<ConstantSDNode>(In)->getZExtValue())
5805       Immediate |= (1ULL << idx);
5806   }
5807
5808   if (AllContants) {
5809     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5810       DAG.getConstant(Immediate, MVT::i16));
5811     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5812                        DAG.getIntPtrConstant(0));
5813   }
5814
5815   // Splat vector (with undefs)
5816   SDValue In = Op.getOperand(0);
5817   for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5818     if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5819       llvm_unreachable("Unsupported predicate operation");
5820   }
5821
5822   SDValue EFLAGS, X86CC;
5823   if (In.getOpcode() == ISD::SETCC) {
5824     SDValue Op0 = In.getOperand(0);
5825     SDValue Op1 = In.getOperand(1);
5826     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5827     bool isFP = Op1.getValueType().isFloatingPoint();
5828     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5829
5830     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5831
5832     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5833     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5834     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5835   } else if (In.getOpcode() == X86ISD::SETCC) {
5836     X86CC = In.getOperand(0);
5837     EFLAGS = In.getOperand(1);
5838   } else {
5839     // The algorithm:
5840     //   Bit1 = In & 0x1
5841     //   if (Bit1 != 0)
5842     //     ZF = 0
5843     //   else
5844     //     ZF = 1
5845     //   if (ZF == 0)
5846     //     res = allOnes ### CMOVNE -1, %res
5847     //   else
5848     //     res = allZero
5849     MVT InVT = In.getSimpleValueType();
5850     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5851     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5852     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5853   }
5854
5855   if (VT == MVT::v16i1) {
5856     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5857     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5858     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5859           Cst0, Cst1, X86CC, EFLAGS);
5860     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5861   }
5862
5863   if (VT == MVT::v8i1) {
5864     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5865     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5866     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5867           Cst0, Cst1, X86CC, EFLAGS);
5868     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5869     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5870   }
5871   llvm_unreachable("Unsupported predicate operation");
5872 }
5873
5874 SDValue
5875 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5876   SDLoc dl(Op);
5877
5878   MVT VT = Op.getSimpleValueType();
5879   MVT ExtVT = VT.getVectorElementType();
5880   unsigned NumElems = Op.getNumOperands();
5881
5882   // Generate vectors for predicate vectors.
5883   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5884     return LowerBUILD_VECTORvXi1(Op, DAG);
5885
5886   // Vectors containing all zeros can be matched by pxor and xorps later
5887   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5888     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5889     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5890     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5891       return Op;
5892
5893     return getZeroVector(VT, Subtarget, DAG, dl);
5894   }
5895
5896   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5897   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5898   // vpcmpeqd on 256-bit vectors.
5899   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5900     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5901       return Op;
5902
5903     if (!VT.is512BitVector())
5904       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5905   }
5906
5907   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5908   if (Broadcast.getNode())
5909     return Broadcast;
5910
5911   unsigned EVTBits = ExtVT.getSizeInBits();
5912
5913   unsigned NumZero  = 0;
5914   unsigned NumNonZero = 0;
5915   unsigned NonZeros = 0;
5916   bool IsAllConstants = true;
5917   SmallSet<SDValue, 8> Values;
5918   for (unsigned i = 0; i < NumElems; ++i) {
5919     SDValue Elt = Op.getOperand(i);
5920     if (Elt.getOpcode() == ISD::UNDEF)
5921       continue;
5922     Values.insert(Elt);
5923     if (Elt.getOpcode() != ISD::Constant &&
5924         Elt.getOpcode() != ISD::ConstantFP)
5925       IsAllConstants = false;
5926     if (X86::isZeroNode(Elt))
5927       NumZero++;
5928     else {
5929       NonZeros |= (1 << i);
5930       NumNonZero++;
5931     }
5932   }
5933
5934   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5935   if (NumNonZero == 0)
5936     return DAG.getUNDEF(VT);
5937
5938   // Special case for single non-zero, non-undef, element.
5939   if (NumNonZero == 1) {
5940     unsigned Idx = countTrailingZeros(NonZeros);
5941     SDValue Item = Op.getOperand(Idx);
5942
5943     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5944     // the value are obviously zero, truncate the value to i32 and do the
5945     // insertion that way.  Only do this if the value is non-constant or if the
5946     // value is a constant being inserted into element 0.  It is cheaper to do
5947     // a constant pool load than it is to do a movd + shuffle.
5948     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5949         (!IsAllConstants || Idx == 0)) {
5950       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5951         // Handle SSE only.
5952         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5953         EVT VecVT = MVT::v4i32;
5954         unsigned VecElts = 4;
5955
5956         // Truncate the value (which may itself be a constant) to i32, and
5957         // convert it to a vector with movd (S2V+shuffle to zero extend).
5958         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5959         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5960         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5961
5962         // Now we have our 32-bit value zero extended in the low element of
5963         // a vector.  If Idx != 0, swizzle it into place.
5964         if (Idx != 0) {
5965           SmallVector<int, 4> Mask;
5966           Mask.push_back(Idx);
5967           for (unsigned i = 1; i != VecElts; ++i)
5968             Mask.push_back(i);
5969           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5970                                       &Mask[0]);
5971         }
5972         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5973       }
5974     }
5975
5976     // If we have a constant or non-constant insertion into the low element of
5977     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5978     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5979     // depending on what the source datatype is.
5980     if (Idx == 0) {
5981       if (NumZero == 0)
5982         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5983
5984       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5985           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5986         if (VT.is256BitVector() || VT.is512BitVector()) {
5987           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5988           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5989                              Item, DAG.getIntPtrConstant(0));
5990         }
5991         assert(VT.is128BitVector() && "Expected an SSE value type!");
5992         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5993         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5994         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5995       }
5996
5997       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5998         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5999         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6000         if (VT.is256BitVector()) {
6001           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6002           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6003         } else {
6004           assert(VT.is128BitVector() && "Expected an SSE value type!");
6005           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6006         }
6007         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6008       }
6009     }
6010
6011     // Is it a vector logical left shift?
6012     if (NumElems == 2 && Idx == 1 &&
6013         X86::isZeroNode(Op.getOperand(0)) &&
6014         !X86::isZeroNode(Op.getOperand(1))) {
6015       unsigned NumBits = VT.getSizeInBits();
6016       return getVShift(true, VT,
6017                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6018                                    VT, Op.getOperand(1)),
6019                        NumBits/2, DAG, *this, dl);
6020     }
6021
6022     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6023       return SDValue();
6024
6025     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6026     // is a non-constant being inserted into an element other than the low one,
6027     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6028     // movd/movss) to move this into the low element, then shuffle it into
6029     // place.
6030     if (EVTBits == 32) {
6031       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6032
6033       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6034       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6035       SmallVector<int, 8> MaskVec;
6036       for (unsigned i = 0; i != NumElems; ++i)
6037         MaskVec.push_back(i == Idx ? 0 : 1);
6038       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6039     }
6040   }
6041
6042   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6043   if (Values.size() == 1) {
6044     if (EVTBits == 32) {
6045       // Instead of a shuffle like this:
6046       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6047       // Check if it's possible to issue this instead.
6048       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6049       unsigned Idx = countTrailingZeros(NonZeros);
6050       SDValue Item = Op.getOperand(Idx);
6051       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6052         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6053     }
6054     return SDValue();
6055   }
6056
6057   // A vector full of immediates; various special cases are already
6058   // handled, so this is best done with a single constant-pool load.
6059   if (IsAllConstants)
6060     return SDValue();
6061
6062   // For AVX-length vectors, build the individual 128-bit pieces and use
6063   // shuffles to put them in place.
6064   if (VT.is256BitVector()) {
6065     SmallVector<SDValue, 32> V;
6066     for (unsigned i = 0; i != NumElems; ++i)
6067       V.push_back(Op.getOperand(i));
6068
6069     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6070
6071     // Build both the lower and upper subvector.
6072     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6073     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6074                                 NumElems/2);
6075
6076     // Recreate the wider vector with the lower and upper part.
6077     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6078   }
6079
6080   // Let legalizer expand 2-wide build_vectors.
6081   if (EVTBits == 64) {
6082     if (NumNonZero == 1) {
6083       // One half is zero or undef.
6084       unsigned Idx = countTrailingZeros(NonZeros);
6085       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6086                                  Op.getOperand(Idx));
6087       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6088     }
6089     return SDValue();
6090   }
6091
6092   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6093   if (EVTBits == 8 && NumElems == 16) {
6094     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6095                                         Subtarget, *this);
6096     if (V.getNode()) return V;
6097   }
6098
6099   if (EVTBits == 16 && NumElems == 8) {
6100     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6101                                       Subtarget, *this);
6102     if (V.getNode()) return V;
6103   }
6104
6105   // If element VT is == 32 bits, turn it into a number of shuffles.
6106   SmallVector<SDValue, 8> V(NumElems);
6107   if (NumElems == 4 && NumZero > 0) {
6108     for (unsigned i = 0; i < 4; ++i) {
6109       bool isZero = !(NonZeros & (1 << i));
6110       if (isZero)
6111         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6112       else
6113         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6114     }
6115
6116     for (unsigned i = 0; i < 2; ++i) {
6117       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6118         default: break;
6119         case 0:
6120           V[i] = V[i*2];  // Must be a zero vector.
6121           break;
6122         case 1:
6123           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6124           break;
6125         case 2:
6126           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6127           break;
6128         case 3:
6129           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6130           break;
6131       }
6132     }
6133
6134     bool Reverse1 = (NonZeros & 0x3) == 2;
6135     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6136     int MaskVec[] = {
6137       Reverse1 ? 1 : 0,
6138       Reverse1 ? 0 : 1,
6139       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6140       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6141     };
6142     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6143   }
6144
6145   if (Values.size() > 1 && VT.is128BitVector()) {
6146     // Check for a build vector of consecutive loads.
6147     for (unsigned i = 0; i < NumElems; ++i)
6148       V[i] = Op.getOperand(i);
6149
6150     // Check for elements which are consecutive loads.
6151     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6152     if (LD.getNode())
6153       return LD;
6154
6155     // Check for a build vector from mostly shuffle plus few inserting.
6156     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6157     if (Sh.getNode())
6158       return Sh;
6159
6160     // For SSE 4.1, use insertps to put the high elements into the low element.
6161     if (getSubtarget()->hasSSE41()) {
6162       SDValue Result;
6163       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6164         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6165       else
6166         Result = DAG.getUNDEF(VT);
6167
6168       for (unsigned i = 1; i < NumElems; ++i) {
6169         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6170         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6171                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6172       }
6173       return Result;
6174     }
6175
6176     // Otherwise, expand into a number of unpckl*, start by extending each of
6177     // our (non-undef) elements to the full vector width with the element in the
6178     // bottom slot of the vector (which generates no code for SSE).
6179     for (unsigned i = 0; i < NumElems; ++i) {
6180       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6181         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6182       else
6183         V[i] = DAG.getUNDEF(VT);
6184     }
6185
6186     // Next, we iteratively mix elements, e.g. for v4f32:
6187     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6188     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6189     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6190     unsigned EltStride = NumElems >> 1;
6191     while (EltStride != 0) {
6192       for (unsigned i = 0; i < EltStride; ++i) {
6193         // If V[i+EltStride] is undef and this is the first round of mixing,
6194         // then it is safe to just drop this shuffle: V[i] is already in the
6195         // right place, the one element (since it's the first round) being
6196         // inserted as undef can be dropped.  This isn't safe for successive
6197         // rounds because they will permute elements within both vectors.
6198         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6199             EltStride == NumElems/2)
6200           continue;
6201
6202         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6203       }
6204       EltStride >>= 1;
6205     }
6206     return V[0];
6207   }
6208   return SDValue();
6209 }
6210
6211 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6212 // to create 256-bit vectors from two other 128-bit ones.
6213 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6214   SDLoc dl(Op);
6215   MVT ResVT = Op.getSimpleValueType();
6216
6217   assert((ResVT.is256BitVector() ||
6218           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6219
6220   SDValue V1 = Op.getOperand(0);
6221   SDValue V2 = Op.getOperand(1);
6222   unsigned NumElems = ResVT.getVectorNumElements();
6223   if(ResVT.is256BitVector())
6224     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6225
6226   if (Op.getNumOperands() == 4) {
6227     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6228                                 ResVT.getVectorNumElements()/2);
6229     SDValue V3 = Op.getOperand(2);
6230     SDValue V4 = Op.getOperand(3);
6231     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6232       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6233   }
6234   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6235 }
6236
6237 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6238   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6239   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6240          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6241           Op.getNumOperands() == 4)));
6242
6243   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6244   // from two other 128-bit ones.
6245
6246   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6247   return LowerAVXCONCAT_VECTORS(Op, DAG);
6248 }
6249
6250 // Try to lower a shuffle node into a simple blend instruction.
6251 static SDValue
6252 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6253                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6254   SDValue V1 = SVOp->getOperand(0);
6255   SDValue V2 = SVOp->getOperand(1);
6256   SDLoc dl(SVOp);
6257   MVT VT = SVOp->getSimpleValueType(0);
6258   MVT EltVT = VT.getVectorElementType();
6259   unsigned NumElems = VT.getVectorNumElements();
6260
6261   // There is no blend with immediate in AVX-512.
6262   if (VT.is512BitVector())
6263     return SDValue();
6264
6265   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6266     return SDValue();
6267   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6268     return SDValue();
6269
6270   // Check the mask for BLEND and build the value.
6271   unsigned MaskValue = 0;
6272   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6273   unsigned NumLanes = (NumElems-1)/8 + 1;
6274   unsigned NumElemsInLane = NumElems / NumLanes;
6275
6276   // Blend for v16i16 should be symetric for the both lanes.
6277   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6278
6279     int SndLaneEltIdx = (NumLanes == 2) ?
6280       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6281     int EltIdx = SVOp->getMaskElt(i);
6282
6283     if ((EltIdx < 0 || EltIdx == (int)i) &&
6284         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6285       continue;
6286
6287     if (((unsigned)EltIdx == (i + NumElems)) &&
6288         (SndLaneEltIdx < 0 ||
6289          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6290       MaskValue |= (1<<i);
6291     else
6292       return SDValue();
6293   }
6294
6295   // Convert i32 vectors to floating point if it is not AVX2.
6296   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6297   MVT BlendVT = VT;
6298   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6299     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6300                                NumElems);
6301     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6302     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6303   }
6304
6305   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6306                             DAG.getConstant(MaskValue, MVT::i32));
6307   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6308 }
6309
6310 // v8i16 shuffles - Prefer shuffles in the following order:
6311 // 1. [all]   pshuflw, pshufhw, optional move
6312 // 2. [ssse3] 1 x pshufb
6313 // 3. [ssse3] 2 x pshufb + 1 x por
6314 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6315 static SDValue
6316 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6317                          SelectionDAG &DAG) {
6318   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6319   SDValue V1 = SVOp->getOperand(0);
6320   SDValue V2 = SVOp->getOperand(1);
6321   SDLoc dl(SVOp);
6322   SmallVector<int, 8> MaskVals;
6323
6324   // Determine if more than 1 of the words in each of the low and high quadwords
6325   // of the result come from the same quadword of one of the two inputs.  Undef
6326   // mask values count as coming from any quadword, for better codegen.
6327   unsigned LoQuad[] = { 0, 0, 0, 0 };
6328   unsigned HiQuad[] = { 0, 0, 0, 0 };
6329   std::bitset<4> InputQuads;
6330   for (unsigned i = 0; i < 8; ++i) {
6331     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6332     int EltIdx = SVOp->getMaskElt(i);
6333     MaskVals.push_back(EltIdx);
6334     if (EltIdx < 0) {
6335       ++Quad[0];
6336       ++Quad[1];
6337       ++Quad[2];
6338       ++Quad[3];
6339       continue;
6340     }
6341     ++Quad[EltIdx / 4];
6342     InputQuads.set(EltIdx / 4);
6343   }
6344
6345   int BestLoQuad = -1;
6346   unsigned MaxQuad = 1;
6347   for (unsigned i = 0; i < 4; ++i) {
6348     if (LoQuad[i] > MaxQuad) {
6349       BestLoQuad = i;
6350       MaxQuad = LoQuad[i];
6351     }
6352   }
6353
6354   int BestHiQuad = -1;
6355   MaxQuad = 1;
6356   for (unsigned i = 0; i < 4; ++i) {
6357     if (HiQuad[i] > MaxQuad) {
6358       BestHiQuad = i;
6359       MaxQuad = HiQuad[i];
6360     }
6361   }
6362
6363   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6364   // of the two input vectors, shuffle them into one input vector so only a
6365   // single pshufb instruction is necessary. If There are more than 2 input
6366   // quads, disable the next transformation since it does not help SSSE3.
6367   bool V1Used = InputQuads[0] || InputQuads[1];
6368   bool V2Used = InputQuads[2] || InputQuads[3];
6369   if (Subtarget->hasSSSE3()) {
6370     if (InputQuads.count() == 2 && V1Used && V2Used) {
6371       BestLoQuad = InputQuads[0] ? 0 : 1;
6372       BestHiQuad = InputQuads[2] ? 2 : 3;
6373     }
6374     if (InputQuads.count() > 2) {
6375       BestLoQuad = -1;
6376       BestHiQuad = -1;
6377     }
6378   }
6379
6380   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6381   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6382   // words from all 4 input quadwords.
6383   SDValue NewV;
6384   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6385     int MaskV[] = {
6386       BestLoQuad < 0 ? 0 : BestLoQuad,
6387       BestHiQuad < 0 ? 1 : BestHiQuad
6388     };
6389     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6390                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6391                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6392     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6393
6394     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6395     // source words for the shuffle, to aid later transformations.
6396     bool AllWordsInNewV = true;
6397     bool InOrder[2] = { true, true };
6398     for (unsigned i = 0; i != 8; ++i) {
6399       int idx = MaskVals[i];
6400       if (idx != (int)i)
6401         InOrder[i/4] = false;
6402       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6403         continue;
6404       AllWordsInNewV = false;
6405       break;
6406     }
6407
6408     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6409     if (AllWordsInNewV) {
6410       for (int i = 0; i != 8; ++i) {
6411         int idx = MaskVals[i];
6412         if (idx < 0)
6413           continue;
6414         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6415         if ((idx != i) && idx < 4)
6416           pshufhw = false;
6417         if ((idx != i) && idx > 3)
6418           pshuflw = false;
6419       }
6420       V1 = NewV;
6421       V2Used = false;
6422       BestLoQuad = 0;
6423       BestHiQuad = 1;
6424     }
6425
6426     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6427     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6428     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6429       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6430       unsigned TargetMask = 0;
6431       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6432                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6433       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6434       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6435                              getShufflePSHUFLWImmediate(SVOp);
6436       V1 = NewV.getOperand(0);
6437       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6438     }
6439   }
6440
6441   // Promote splats to a larger type which usually leads to more efficient code.
6442   // FIXME: Is this true if pshufb is available?
6443   if (SVOp->isSplat())
6444     return PromoteSplat(SVOp, DAG);
6445
6446   // If we have SSSE3, and all words of the result are from 1 input vector,
6447   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6448   // is present, fall back to case 4.
6449   if (Subtarget->hasSSSE3()) {
6450     SmallVector<SDValue,16> pshufbMask;
6451
6452     // If we have elements from both input vectors, set the high bit of the
6453     // shuffle mask element to zero out elements that come from V2 in the V1
6454     // mask, and elements that come from V1 in the V2 mask, so that the two
6455     // results can be OR'd together.
6456     bool TwoInputs = V1Used && V2Used;
6457     for (unsigned i = 0; i != 8; ++i) {
6458       int EltIdx = MaskVals[i] * 2;
6459       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6460       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6461       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6462       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6463     }
6464     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6465     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6466                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6467                                  MVT::v16i8, &pshufbMask[0], 16));
6468     if (!TwoInputs)
6469       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6470
6471     // Calculate the shuffle mask for the second input, shuffle it, and
6472     // OR it with the first shuffled input.
6473     pshufbMask.clear();
6474     for (unsigned i = 0; i != 8; ++i) {
6475       int EltIdx = MaskVals[i] * 2;
6476       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6477       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6478       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6479       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6480     }
6481     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6482     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6483                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6484                                  MVT::v16i8, &pshufbMask[0], 16));
6485     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6486     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6487   }
6488
6489   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6490   // and update MaskVals with new element order.
6491   std::bitset<8> InOrder;
6492   if (BestLoQuad >= 0) {
6493     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6494     for (int i = 0; i != 4; ++i) {
6495       int idx = MaskVals[i];
6496       if (idx < 0) {
6497         InOrder.set(i);
6498       } else if ((idx / 4) == BestLoQuad) {
6499         MaskV[i] = idx & 3;
6500         InOrder.set(i);
6501       }
6502     }
6503     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6504                                 &MaskV[0]);
6505
6506     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6507       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6508       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6509                                   NewV.getOperand(0),
6510                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6511     }
6512   }
6513
6514   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6515   // and update MaskVals with the new element order.
6516   if (BestHiQuad >= 0) {
6517     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6518     for (unsigned i = 4; i != 8; ++i) {
6519       int idx = MaskVals[i];
6520       if (idx < 0) {
6521         InOrder.set(i);
6522       } else if ((idx / 4) == BestHiQuad) {
6523         MaskV[i] = (idx & 3) + 4;
6524         InOrder.set(i);
6525       }
6526     }
6527     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6528                                 &MaskV[0]);
6529
6530     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6531       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6532       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6533                                   NewV.getOperand(0),
6534                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6535     }
6536   }
6537
6538   // In case BestHi & BestLo were both -1, which means each quadword has a word
6539   // from each of the four input quadwords, calculate the InOrder bitvector now
6540   // before falling through to the insert/extract cleanup.
6541   if (BestLoQuad == -1 && BestHiQuad == -1) {
6542     NewV = V1;
6543     for (int i = 0; i != 8; ++i)
6544       if (MaskVals[i] < 0 || MaskVals[i] == i)
6545         InOrder.set(i);
6546   }
6547
6548   // The other elements are put in the right place using pextrw and pinsrw.
6549   for (unsigned i = 0; i != 8; ++i) {
6550     if (InOrder[i])
6551       continue;
6552     int EltIdx = MaskVals[i];
6553     if (EltIdx < 0)
6554       continue;
6555     SDValue ExtOp = (EltIdx < 8) ?
6556       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6557                   DAG.getIntPtrConstant(EltIdx)) :
6558       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6559                   DAG.getIntPtrConstant(EltIdx - 8));
6560     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6561                        DAG.getIntPtrConstant(i));
6562   }
6563   return NewV;
6564 }
6565
6566 // v16i8 shuffles - Prefer shuffles in the following order:
6567 // 1. [ssse3] 1 x pshufb
6568 // 2. [ssse3] 2 x pshufb + 1 x por
6569 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6570 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6571                                         const X86Subtarget* Subtarget,
6572                                         SelectionDAG &DAG) {
6573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6574   SDValue V1 = SVOp->getOperand(0);
6575   SDValue V2 = SVOp->getOperand(1);
6576   SDLoc dl(SVOp);
6577   ArrayRef<int> MaskVals = SVOp->getMask();
6578
6579   // Promote splats to a larger type which usually leads to more efficient code.
6580   // FIXME: Is this true if pshufb is available?
6581   if (SVOp->isSplat())
6582     return PromoteSplat(SVOp, DAG);
6583
6584   // If we have SSSE3, case 1 is generated when all result bytes come from
6585   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6586   // present, fall back to case 3.
6587
6588   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6589   if (Subtarget->hasSSSE3()) {
6590     SmallVector<SDValue,16> pshufbMask;
6591
6592     // If all result elements are from one input vector, then only translate
6593     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6594     //
6595     // Otherwise, we have elements from both input vectors, and must zero out
6596     // elements that come from V2 in the first mask, and V1 in the second mask
6597     // so that we can OR them together.
6598     for (unsigned i = 0; i != 16; ++i) {
6599       int EltIdx = MaskVals[i];
6600       if (EltIdx < 0 || EltIdx >= 16)
6601         EltIdx = 0x80;
6602       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6603     }
6604     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6605                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6606                                  MVT::v16i8, &pshufbMask[0], 16));
6607
6608     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6609     // the 2nd operand if it's undefined or zero.
6610     if (V2.getOpcode() == ISD::UNDEF ||
6611         ISD::isBuildVectorAllZeros(V2.getNode()))
6612       return V1;
6613
6614     // Calculate the shuffle mask for the second input, shuffle it, and
6615     // OR it with the first shuffled input.
6616     pshufbMask.clear();
6617     for (unsigned i = 0; i != 16; ++i) {
6618       int EltIdx = MaskVals[i];
6619       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6620       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6621     }
6622     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6623                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6624                                  MVT::v16i8, &pshufbMask[0], 16));
6625     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6626   }
6627
6628   // No SSSE3 - Calculate in place words and then fix all out of place words
6629   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6630   // the 16 different words that comprise the two doublequadword input vectors.
6631   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6632   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6633   SDValue NewV = V1;
6634   for (int i = 0; i != 8; ++i) {
6635     int Elt0 = MaskVals[i*2];
6636     int Elt1 = MaskVals[i*2+1];
6637
6638     // This word of the result is all undef, skip it.
6639     if (Elt0 < 0 && Elt1 < 0)
6640       continue;
6641
6642     // This word of the result is already in the correct place, skip it.
6643     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6644       continue;
6645
6646     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6647     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6648     SDValue InsElt;
6649
6650     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6651     // using a single extract together, load it and store it.
6652     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6653       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6654                            DAG.getIntPtrConstant(Elt1 / 2));
6655       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6656                         DAG.getIntPtrConstant(i));
6657       continue;
6658     }
6659
6660     // If Elt1 is defined, extract it from the appropriate source.  If the
6661     // source byte is not also odd, shift the extracted word left 8 bits
6662     // otherwise clear the bottom 8 bits if we need to do an or.
6663     if (Elt1 >= 0) {
6664       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6665                            DAG.getIntPtrConstant(Elt1 / 2));
6666       if ((Elt1 & 1) == 0)
6667         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6668                              DAG.getConstant(8,
6669                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6670       else if (Elt0 >= 0)
6671         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6672                              DAG.getConstant(0xFF00, MVT::i16));
6673     }
6674     // If Elt0 is defined, extract it from the appropriate source.  If the
6675     // source byte is not also even, shift the extracted word right 8 bits. If
6676     // Elt1 was also defined, OR the extracted values together before
6677     // inserting them in the result.
6678     if (Elt0 >= 0) {
6679       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6680                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6681       if ((Elt0 & 1) != 0)
6682         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6683                               DAG.getConstant(8,
6684                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6685       else if (Elt1 >= 0)
6686         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6687                              DAG.getConstant(0x00FF, MVT::i16));
6688       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6689                          : InsElt0;
6690     }
6691     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6692                        DAG.getIntPtrConstant(i));
6693   }
6694   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6695 }
6696
6697 // v32i8 shuffles - Translate to VPSHUFB if possible.
6698 static
6699 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6700                                  const X86Subtarget *Subtarget,
6701                                  SelectionDAG &DAG) {
6702   MVT VT = SVOp->getSimpleValueType(0);
6703   SDValue V1 = SVOp->getOperand(0);
6704   SDValue V2 = SVOp->getOperand(1);
6705   SDLoc dl(SVOp);
6706   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6707
6708   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6709   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6710   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6711
6712   // VPSHUFB may be generated if
6713   // (1) one of input vector is undefined or zeroinitializer.
6714   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6715   // And (2) the mask indexes don't cross the 128-bit lane.
6716   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6717       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6718     return SDValue();
6719
6720   if (V1IsAllZero && !V2IsAllZero) {
6721     CommuteVectorShuffleMask(MaskVals, 32);
6722     V1 = V2;
6723   }
6724   SmallVector<SDValue, 32> pshufbMask;
6725   for (unsigned i = 0; i != 32; i++) {
6726     int EltIdx = MaskVals[i];
6727     if (EltIdx < 0 || EltIdx >= 32)
6728       EltIdx = 0x80;
6729     else {
6730       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6731         // Cross lane is not allowed.
6732         return SDValue();
6733       EltIdx &= 0xf;
6734     }
6735     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6736   }
6737   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6738                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6739                                   MVT::v32i8, &pshufbMask[0], 32));
6740 }
6741
6742 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6743 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6744 /// done when every pair / quad of shuffle mask elements point to elements in
6745 /// the right sequence. e.g.
6746 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6747 static
6748 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6749                                  SelectionDAG &DAG) {
6750   MVT VT = SVOp->getSimpleValueType(0);
6751   SDLoc dl(SVOp);
6752   unsigned NumElems = VT.getVectorNumElements();
6753   MVT NewVT;
6754   unsigned Scale;
6755   switch (VT.SimpleTy) {
6756   default: llvm_unreachable("Unexpected!");
6757   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6758   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6759   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6760   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6761   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6762   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6763   }
6764
6765   SmallVector<int, 8> MaskVec;
6766   for (unsigned i = 0; i != NumElems; i += Scale) {
6767     int StartIdx = -1;
6768     for (unsigned j = 0; j != Scale; ++j) {
6769       int EltIdx = SVOp->getMaskElt(i+j);
6770       if (EltIdx < 0)
6771         continue;
6772       if (StartIdx < 0)
6773         StartIdx = (EltIdx / Scale);
6774       if (EltIdx != (int)(StartIdx*Scale + j))
6775         return SDValue();
6776     }
6777     MaskVec.push_back(StartIdx);
6778   }
6779
6780   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6781   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6782   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6783 }
6784
6785 /// getVZextMovL - Return a zero-extending vector move low node.
6786 ///
6787 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6788                             SDValue SrcOp, SelectionDAG &DAG,
6789                             const X86Subtarget *Subtarget, SDLoc dl) {
6790   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6791     LoadSDNode *LD = NULL;
6792     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6793       LD = dyn_cast<LoadSDNode>(SrcOp);
6794     if (!LD) {
6795       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6796       // instead.
6797       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6798       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6799           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6800           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6801           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6802         // PR2108
6803         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6804         return DAG.getNode(ISD::BITCAST, dl, VT,
6805                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6806                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6807                                                    OpVT,
6808                                                    SrcOp.getOperand(0)
6809                                                           .getOperand(0))));
6810       }
6811     }
6812   }
6813
6814   return DAG.getNode(ISD::BITCAST, dl, VT,
6815                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6816                                  DAG.getNode(ISD::BITCAST, dl,
6817                                              OpVT, SrcOp)));
6818 }
6819
6820 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6821 /// which could not be matched by any known target speficic shuffle
6822 static SDValue
6823 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6824
6825   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6826   if (NewOp.getNode())
6827     return NewOp;
6828
6829   MVT VT = SVOp->getSimpleValueType(0);
6830
6831   unsigned NumElems = VT.getVectorNumElements();
6832   unsigned NumLaneElems = NumElems / 2;
6833
6834   SDLoc dl(SVOp);
6835   MVT EltVT = VT.getVectorElementType();
6836   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6837   SDValue Output[2];
6838
6839   SmallVector<int, 16> Mask;
6840   for (unsigned l = 0; l < 2; ++l) {
6841     // Build a shuffle mask for the output, discovering on the fly which
6842     // input vectors to use as shuffle operands (recorded in InputUsed).
6843     // If building a suitable shuffle vector proves too hard, then bail
6844     // out with UseBuildVector set.
6845     bool UseBuildVector = false;
6846     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6847     unsigned LaneStart = l * NumLaneElems;
6848     for (unsigned i = 0; i != NumLaneElems; ++i) {
6849       // The mask element.  This indexes into the input.
6850       int Idx = SVOp->getMaskElt(i+LaneStart);
6851       if (Idx < 0) {
6852         // the mask element does not index into any input vector.
6853         Mask.push_back(-1);
6854         continue;
6855       }
6856
6857       // The input vector this mask element indexes into.
6858       int Input = Idx / NumLaneElems;
6859
6860       // Turn the index into an offset from the start of the input vector.
6861       Idx -= Input * NumLaneElems;
6862
6863       // Find or create a shuffle vector operand to hold this input.
6864       unsigned OpNo;
6865       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6866         if (InputUsed[OpNo] == Input)
6867           // This input vector is already an operand.
6868           break;
6869         if (InputUsed[OpNo] < 0) {
6870           // Create a new operand for this input vector.
6871           InputUsed[OpNo] = Input;
6872           break;
6873         }
6874       }
6875
6876       if (OpNo >= array_lengthof(InputUsed)) {
6877         // More than two input vectors used!  Give up on trying to create a
6878         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6879         UseBuildVector = true;
6880         break;
6881       }
6882
6883       // Add the mask index for the new shuffle vector.
6884       Mask.push_back(Idx + OpNo * NumLaneElems);
6885     }
6886
6887     if (UseBuildVector) {
6888       SmallVector<SDValue, 16> SVOps;
6889       for (unsigned i = 0; i != NumLaneElems; ++i) {
6890         // The mask element.  This indexes into the input.
6891         int Idx = SVOp->getMaskElt(i+LaneStart);
6892         if (Idx < 0) {
6893           SVOps.push_back(DAG.getUNDEF(EltVT));
6894           continue;
6895         }
6896
6897         // The input vector this mask element indexes into.
6898         int Input = Idx / NumElems;
6899
6900         // Turn the index into an offset from the start of the input vector.
6901         Idx -= Input * NumElems;
6902
6903         // Extract the vector element by hand.
6904         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6905                                     SVOp->getOperand(Input),
6906                                     DAG.getIntPtrConstant(Idx)));
6907       }
6908
6909       // Construct the output using a BUILD_VECTOR.
6910       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6911                               SVOps.size());
6912     } else if (InputUsed[0] < 0) {
6913       // No input vectors were used! The result is undefined.
6914       Output[l] = DAG.getUNDEF(NVT);
6915     } else {
6916       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6917                                         (InputUsed[0] % 2) * NumLaneElems,
6918                                         DAG, dl);
6919       // If only one input was used, use an undefined vector for the other.
6920       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6921         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6922                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6923       // At least one input vector was used. Create a new shuffle vector.
6924       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6925     }
6926
6927     Mask.clear();
6928   }
6929
6930   // Concatenate the result back
6931   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6932 }
6933
6934 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6935 /// 4 elements, and match them with several different shuffle types.
6936 static SDValue
6937 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6938   SDValue V1 = SVOp->getOperand(0);
6939   SDValue V2 = SVOp->getOperand(1);
6940   SDLoc dl(SVOp);
6941   MVT VT = SVOp->getSimpleValueType(0);
6942
6943   assert(VT.is128BitVector() && "Unsupported vector size");
6944
6945   std::pair<int, int> Locs[4];
6946   int Mask1[] = { -1, -1, -1, -1 };
6947   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6948
6949   unsigned NumHi = 0;
6950   unsigned NumLo = 0;
6951   for (unsigned i = 0; i != 4; ++i) {
6952     int Idx = PermMask[i];
6953     if (Idx < 0) {
6954       Locs[i] = std::make_pair(-1, -1);
6955     } else {
6956       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6957       if (Idx < 4) {
6958         Locs[i] = std::make_pair(0, NumLo);
6959         Mask1[NumLo] = Idx;
6960         NumLo++;
6961       } else {
6962         Locs[i] = std::make_pair(1, NumHi);
6963         if (2+NumHi < 4)
6964           Mask1[2+NumHi] = Idx;
6965         NumHi++;
6966       }
6967     }
6968   }
6969
6970   if (NumLo <= 2 && NumHi <= 2) {
6971     // If no more than two elements come from either vector. This can be
6972     // implemented with two shuffles. First shuffle gather the elements.
6973     // The second shuffle, which takes the first shuffle as both of its
6974     // vector operands, put the elements into the right order.
6975     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6976
6977     int Mask2[] = { -1, -1, -1, -1 };
6978
6979     for (unsigned i = 0; i != 4; ++i)
6980       if (Locs[i].first != -1) {
6981         unsigned Idx = (i < 2) ? 0 : 4;
6982         Idx += Locs[i].first * 2 + Locs[i].second;
6983         Mask2[i] = Idx;
6984       }
6985
6986     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6987   }
6988
6989   if (NumLo == 3 || NumHi == 3) {
6990     // Otherwise, we must have three elements from one vector, call it X, and
6991     // one element from the other, call it Y.  First, use a shufps to build an
6992     // intermediate vector with the one element from Y and the element from X
6993     // that will be in the same half in the final destination (the indexes don't
6994     // matter). Then, use a shufps to build the final vector, taking the half
6995     // containing the element from Y from the intermediate, and the other half
6996     // from X.
6997     if (NumHi == 3) {
6998       // Normalize it so the 3 elements come from V1.
6999       CommuteVectorShuffleMask(PermMask, 4);
7000       std::swap(V1, V2);
7001     }
7002
7003     // Find the element from V2.
7004     unsigned HiIndex;
7005     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7006       int Val = PermMask[HiIndex];
7007       if (Val < 0)
7008         continue;
7009       if (Val >= 4)
7010         break;
7011     }
7012
7013     Mask1[0] = PermMask[HiIndex];
7014     Mask1[1] = -1;
7015     Mask1[2] = PermMask[HiIndex^1];
7016     Mask1[3] = -1;
7017     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7018
7019     if (HiIndex >= 2) {
7020       Mask1[0] = PermMask[0];
7021       Mask1[1] = PermMask[1];
7022       Mask1[2] = HiIndex & 1 ? 6 : 4;
7023       Mask1[3] = HiIndex & 1 ? 4 : 6;
7024       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7025     }
7026
7027     Mask1[0] = HiIndex & 1 ? 2 : 0;
7028     Mask1[1] = HiIndex & 1 ? 0 : 2;
7029     Mask1[2] = PermMask[2];
7030     Mask1[3] = PermMask[3];
7031     if (Mask1[2] >= 0)
7032       Mask1[2] += 4;
7033     if (Mask1[3] >= 0)
7034       Mask1[3] += 4;
7035     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7036   }
7037
7038   // Break it into (shuffle shuffle_hi, shuffle_lo).
7039   int LoMask[] = { -1, -1, -1, -1 };
7040   int HiMask[] = { -1, -1, -1, -1 };
7041
7042   int *MaskPtr = LoMask;
7043   unsigned MaskIdx = 0;
7044   unsigned LoIdx = 0;
7045   unsigned HiIdx = 2;
7046   for (unsigned i = 0; i != 4; ++i) {
7047     if (i == 2) {
7048       MaskPtr = HiMask;
7049       MaskIdx = 1;
7050       LoIdx = 0;
7051       HiIdx = 2;
7052     }
7053     int Idx = PermMask[i];
7054     if (Idx < 0) {
7055       Locs[i] = std::make_pair(-1, -1);
7056     } else if (Idx < 4) {
7057       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7058       MaskPtr[LoIdx] = Idx;
7059       LoIdx++;
7060     } else {
7061       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7062       MaskPtr[HiIdx] = Idx;
7063       HiIdx++;
7064     }
7065   }
7066
7067   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7068   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7069   int MaskOps[] = { -1, -1, -1, -1 };
7070   for (unsigned i = 0; i != 4; ++i)
7071     if (Locs[i].first != -1)
7072       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7073   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7074 }
7075
7076 static bool MayFoldVectorLoad(SDValue V) {
7077   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7078     V = V.getOperand(0);
7079
7080   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7081     V = V.getOperand(0);
7082   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7083       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7084     // BUILD_VECTOR (load), undef
7085     V = V.getOperand(0);
7086
7087   return MayFoldLoad(V);
7088 }
7089
7090 static
7091 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7092   MVT VT = Op.getSimpleValueType();
7093
7094   // Canonizalize to v2f64.
7095   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7096   return DAG.getNode(ISD::BITCAST, dl, VT,
7097                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7098                                           V1, DAG));
7099 }
7100
7101 static
7102 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7103                         bool HasSSE2) {
7104   SDValue V1 = Op.getOperand(0);
7105   SDValue V2 = Op.getOperand(1);
7106   MVT VT = Op.getSimpleValueType();
7107
7108   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7109
7110   if (HasSSE2 && VT == MVT::v2f64)
7111     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7112
7113   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7114   return DAG.getNode(ISD::BITCAST, dl, VT,
7115                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7116                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7117                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7118 }
7119
7120 static
7121 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7122   SDValue V1 = Op.getOperand(0);
7123   SDValue V2 = Op.getOperand(1);
7124   MVT VT = Op.getSimpleValueType();
7125
7126   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7127          "unsupported shuffle type");
7128
7129   if (V2.getOpcode() == ISD::UNDEF)
7130     V2 = V1;
7131
7132   // v4i32 or v4f32
7133   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7134 }
7135
7136 static
7137 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7138   SDValue V1 = Op.getOperand(0);
7139   SDValue V2 = Op.getOperand(1);
7140   MVT VT = Op.getSimpleValueType();
7141   unsigned NumElems = VT.getVectorNumElements();
7142
7143   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7144   // operand of these instructions is only memory, so check if there's a
7145   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7146   // same masks.
7147   bool CanFoldLoad = false;
7148
7149   // Trivial case, when V2 comes from a load.
7150   if (MayFoldVectorLoad(V2))
7151     CanFoldLoad = true;
7152
7153   // When V1 is a load, it can be folded later into a store in isel, example:
7154   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7155   //    turns into:
7156   //  (MOVLPSmr addr:$src1, VR128:$src2)
7157   // So, recognize this potential and also use MOVLPS or MOVLPD
7158   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7159     CanFoldLoad = true;
7160
7161   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7162   if (CanFoldLoad) {
7163     if (HasSSE2 && NumElems == 2)
7164       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7165
7166     if (NumElems == 4)
7167       // If we don't care about the second element, proceed to use movss.
7168       if (SVOp->getMaskElt(1) != -1)
7169         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7170   }
7171
7172   // movl and movlp will both match v2i64, but v2i64 is never matched by
7173   // movl earlier because we make it strict to avoid messing with the movlp load
7174   // folding logic (see the code above getMOVLP call). Match it here then,
7175   // this is horrible, but will stay like this until we move all shuffle
7176   // matching to x86 specific nodes. Note that for the 1st condition all
7177   // types are matched with movsd.
7178   if (HasSSE2) {
7179     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7180     // as to remove this logic from here, as much as possible
7181     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7182       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7183     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7184   }
7185
7186   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7187
7188   // Invert the operand order and use SHUFPS to match it.
7189   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7190                               getShuffleSHUFImmediate(SVOp), DAG);
7191 }
7192
7193 // Reduce a vector shuffle to zext.
7194 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7195                                     SelectionDAG &DAG) {
7196   // PMOVZX is only available from SSE41.
7197   if (!Subtarget->hasSSE41())
7198     return SDValue();
7199
7200   MVT VT = Op.getSimpleValueType();
7201
7202   // Only AVX2 support 256-bit vector integer extending.
7203   if (!Subtarget->hasInt256() && VT.is256BitVector())
7204     return SDValue();
7205
7206   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7207   SDLoc DL(Op);
7208   SDValue V1 = Op.getOperand(0);
7209   SDValue V2 = Op.getOperand(1);
7210   unsigned NumElems = VT.getVectorNumElements();
7211
7212   // Extending is an unary operation and the element type of the source vector
7213   // won't be equal to or larger than i64.
7214   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7215       VT.getVectorElementType() == MVT::i64)
7216     return SDValue();
7217
7218   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7219   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7220   while ((1U << Shift) < NumElems) {
7221     if (SVOp->getMaskElt(1U << Shift) == 1)
7222       break;
7223     Shift += 1;
7224     // The maximal ratio is 8, i.e. from i8 to i64.
7225     if (Shift > 3)
7226       return SDValue();
7227   }
7228
7229   // Check the shuffle mask.
7230   unsigned Mask = (1U << Shift) - 1;
7231   for (unsigned i = 0; i != NumElems; ++i) {
7232     int EltIdx = SVOp->getMaskElt(i);
7233     if ((i & Mask) != 0 && EltIdx != -1)
7234       return SDValue();
7235     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7236       return SDValue();
7237   }
7238
7239   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7240   MVT NeVT = MVT::getIntegerVT(NBits);
7241   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7242
7243   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7244     return SDValue();
7245
7246   // Simplify the operand as it's prepared to be fed into shuffle.
7247   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7248   if (V1.getOpcode() == ISD::BITCAST &&
7249       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7250       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7251       V1.getOperand(0).getOperand(0)
7252         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7253     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7254     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7255     ConstantSDNode *CIdx =
7256       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7257     // If it's foldable, i.e. normal load with single use, we will let code
7258     // selection to fold it. Otherwise, we will short the conversion sequence.
7259     if (CIdx && CIdx->getZExtValue() == 0 &&
7260         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7261       MVT FullVT = V.getSimpleValueType();
7262       MVT V1VT = V1.getSimpleValueType();
7263       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7264         // The "ext_vec_elt" node is wider than the result node.
7265         // In this case we should extract subvector from V.
7266         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7267         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7268         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7269                                         FullVT.getVectorNumElements()/Ratio);
7270         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7271                         DAG.getIntPtrConstant(0));
7272       }
7273       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7274     }
7275   }
7276
7277   return DAG.getNode(ISD::BITCAST, DL, VT,
7278                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7279 }
7280
7281 static SDValue
7282 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7283                        SelectionDAG &DAG) {
7284   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7285   MVT VT = Op.getSimpleValueType();
7286   SDLoc dl(Op);
7287   SDValue V1 = Op.getOperand(0);
7288   SDValue V2 = Op.getOperand(1);
7289
7290   if (isZeroShuffle(SVOp))
7291     return getZeroVector(VT, Subtarget, DAG, dl);
7292
7293   // Handle splat operations
7294   if (SVOp->isSplat()) {
7295     // Use vbroadcast whenever the splat comes from a foldable load
7296     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7297     if (Broadcast.getNode())
7298       return Broadcast;
7299   }
7300
7301   // Check integer expanding shuffles.
7302   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7303   if (NewOp.getNode())
7304     return NewOp;
7305
7306   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7307   // do it!
7308   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7309       VT == MVT::v16i16 || VT == MVT::v32i8) {
7310     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7311     if (NewOp.getNode())
7312       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7313   } else if ((VT == MVT::v4i32 ||
7314              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7315     // FIXME: Figure out a cleaner way to do this.
7316     // Try to make use of movq to zero out the top part.
7317     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7318       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7319       if (NewOp.getNode()) {
7320         MVT NewVT = NewOp.getSimpleValueType();
7321         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7322                                NewVT, true, false))
7323           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7324                               DAG, Subtarget, dl);
7325       }
7326     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7327       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7328       if (NewOp.getNode()) {
7329         MVT NewVT = NewOp.getSimpleValueType();
7330         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7331           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7332                               DAG, Subtarget, dl);
7333       }
7334     }
7335   }
7336   return SDValue();
7337 }
7338
7339 SDValue
7340 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7341   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7342   SDValue V1 = Op.getOperand(0);
7343   SDValue V2 = Op.getOperand(1);
7344   MVT VT = Op.getSimpleValueType();
7345   SDLoc dl(Op);
7346   unsigned NumElems = VT.getVectorNumElements();
7347   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7348   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7349   bool V1IsSplat = false;
7350   bool V2IsSplat = false;
7351   bool HasSSE2 = Subtarget->hasSSE2();
7352   bool HasFp256    = Subtarget->hasFp256();
7353   bool HasInt256   = Subtarget->hasInt256();
7354   MachineFunction &MF = DAG.getMachineFunction();
7355   bool OptForSize = MF.getFunction()->getAttributes().
7356     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7357
7358   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7359
7360   if (V1IsUndef && V2IsUndef)
7361     return DAG.getUNDEF(VT);
7362
7363   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7364
7365   // Vector shuffle lowering takes 3 steps:
7366   //
7367   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7368   //    narrowing and commutation of operands should be handled.
7369   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7370   //    shuffle nodes.
7371   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7372   //    so the shuffle can be broken into other shuffles and the legalizer can
7373   //    try the lowering again.
7374   //
7375   // The general idea is that no vector_shuffle operation should be left to
7376   // be matched during isel, all of them must be converted to a target specific
7377   // node here.
7378
7379   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7380   // narrowing and commutation of operands should be handled. The actual code
7381   // doesn't include all of those, work in progress...
7382   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7383   if (NewOp.getNode())
7384     return NewOp;
7385
7386   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7387
7388   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7389   // unpckh_undef). Only use pshufd if speed is more important than size.
7390   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7391     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7392   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7393     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7394
7395   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7396       V2IsUndef && MayFoldVectorLoad(V1))
7397     return getMOVDDup(Op, dl, V1, DAG);
7398
7399   if (isMOVHLPS_v_undef_Mask(M, VT))
7400     return getMOVHighToLow(Op, dl, DAG);
7401
7402   // Use to match splats
7403   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7404       (VT == MVT::v2f64 || VT == MVT::v2i64))
7405     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7406
7407   if (isPSHUFDMask(M, VT)) {
7408     // The actual implementation will match the mask in the if above and then
7409     // during isel it can match several different instructions, not only pshufd
7410     // as its name says, sad but true, emulate the behavior for now...
7411     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7412       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7413
7414     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7415
7416     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7417       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7418
7419     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7420       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7421                                   DAG);
7422
7423     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7424                                 TargetMask, DAG);
7425   }
7426
7427   if (isPALIGNRMask(M, VT, Subtarget))
7428     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7429                                 getShufflePALIGNRImmediate(SVOp),
7430                                 DAG);
7431
7432   // Check if this can be converted into a logical shift.
7433   bool isLeft = false;
7434   unsigned ShAmt = 0;
7435   SDValue ShVal;
7436   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7437   if (isShift && ShVal.hasOneUse()) {
7438     // If the shifted value has multiple uses, it may be cheaper to use
7439     // v_set0 + movlhps or movhlps, etc.
7440     MVT EltVT = VT.getVectorElementType();
7441     ShAmt *= EltVT.getSizeInBits();
7442     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7443   }
7444
7445   if (isMOVLMask(M, VT)) {
7446     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7447       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7448     if (!isMOVLPMask(M, VT)) {
7449       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7450         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7451
7452       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7453         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7454     }
7455   }
7456
7457   // FIXME: fold these into legal mask.
7458   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7459     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7460
7461   if (isMOVHLPSMask(M, VT))
7462     return getMOVHighToLow(Op, dl, DAG);
7463
7464   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7465     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7466
7467   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7468     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7469
7470   if (isMOVLPMask(M, VT))
7471     return getMOVLP(Op, dl, DAG, HasSSE2);
7472
7473   if (ShouldXformToMOVHLPS(M, VT) ||
7474       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7475     return CommuteVectorShuffle(SVOp, DAG);
7476
7477   if (isShift) {
7478     // No better options. Use a vshldq / vsrldq.
7479     MVT EltVT = VT.getVectorElementType();
7480     ShAmt *= EltVT.getSizeInBits();
7481     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7482   }
7483
7484   bool Commuted = false;
7485   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7486   // 1,1,1,1 -> v8i16 though.
7487   V1IsSplat = isSplatVector(V1.getNode());
7488   V2IsSplat = isSplatVector(V2.getNode());
7489
7490   // Canonicalize the splat or undef, if present, to be on the RHS.
7491   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7492     CommuteVectorShuffleMask(M, NumElems);
7493     std::swap(V1, V2);
7494     std::swap(V1IsSplat, V2IsSplat);
7495     Commuted = true;
7496   }
7497
7498   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7499     // Shuffling low element of v1 into undef, just return v1.
7500     if (V2IsUndef)
7501       return V1;
7502     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7503     // the instruction selector will not match, so get a canonical MOVL with
7504     // swapped operands to undo the commute.
7505     return getMOVL(DAG, dl, VT, V2, V1);
7506   }
7507
7508   if (isUNPCKLMask(M, VT, HasInt256))
7509     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7510
7511   if (isUNPCKHMask(M, VT, HasInt256))
7512     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7513
7514   if (V2IsSplat) {
7515     // Normalize mask so all entries that point to V2 points to its first
7516     // element then try to match unpck{h|l} again. If match, return a
7517     // new vector_shuffle with the corrected mask.p
7518     SmallVector<int, 8> NewMask(M.begin(), M.end());
7519     NormalizeMask(NewMask, NumElems);
7520     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7521       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7522     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7523       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7524   }
7525
7526   if (Commuted) {
7527     // Commute is back and try unpck* again.
7528     // FIXME: this seems wrong.
7529     CommuteVectorShuffleMask(M, NumElems);
7530     std::swap(V1, V2);
7531     std::swap(V1IsSplat, V2IsSplat);
7532     Commuted = false;
7533
7534     if (isUNPCKLMask(M, VT, HasInt256))
7535       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7536
7537     if (isUNPCKHMask(M, VT, HasInt256))
7538       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7539   }
7540
7541   // Normalize the node to match x86 shuffle ops if needed
7542   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7543     return CommuteVectorShuffle(SVOp, DAG);
7544
7545   // The checks below are all present in isShuffleMaskLegal, but they are
7546   // inlined here right now to enable us to directly emit target specific
7547   // nodes, and remove one by one until they don't return Op anymore.
7548
7549   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7550       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7551     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7552       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7553   }
7554
7555   if (isPSHUFHWMask(M, VT, HasInt256))
7556     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7557                                 getShufflePSHUFHWImmediate(SVOp),
7558                                 DAG);
7559
7560   if (isPSHUFLWMask(M, VT, HasInt256))
7561     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7562                                 getShufflePSHUFLWImmediate(SVOp),
7563                                 DAG);
7564
7565   if (isSHUFPMask(M, VT))
7566     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7567                                 getShuffleSHUFImmediate(SVOp), DAG);
7568
7569   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7570     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7571   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7572     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7573
7574   //===--------------------------------------------------------------------===//
7575   // Generate target specific nodes for 128 or 256-bit shuffles only
7576   // supported in the AVX instruction set.
7577   //
7578
7579   // Handle VMOVDDUPY permutations
7580   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7581     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7582
7583   // Handle VPERMILPS/D* permutations
7584   if (isVPERMILPMask(M, VT)) {
7585     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7586       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7587                                   getShuffleSHUFImmediate(SVOp), DAG);
7588     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7589                                 getShuffleSHUFImmediate(SVOp), DAG);
7590   }
7591
7592   // Handle VPERM2F128/VPERM2I128 permutations
7593   if (isVPERM2X128Mask(M, VT, HasFp256))
7594     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7595                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7596
7597   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7598   if (BlendOp.getNode())
7599     return BlendOp;
7600
7601   unsigned Imm8;
7602   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7603     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7604
7605   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7606       VT.is512BitVector()) {
7607     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7608     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7609     SmallVector<SDValue, 16> permclMask;
7610     for (unsigned i = 0; i != NumElems; ++i) {
7611       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7612     }
7613
7614     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7615                                 &permclMask[0], NumElems);
7616     if (V2IsUndef)
7617       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7618       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7619                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7620     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7621                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7622   }
7623
7624   //===--------------------------------------------------------------------===//
7625   // Since no target specific shuffle was selected for this generic one,
7626   // lower it into other known shuffles. FIXME: this isn't true yet, but
7627   // this is the plan.
7628   //
7629
7630   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7631   if (VT == MVT::v8i16) {
7632     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7633     if (NewOp.getNode())
7634       return NewOp;
7635   }
7636
7637   if (VT == MVT::v16i8) {
7638     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7639     if (NewOp.getNode())
7640       return NewOp;
7641   }
7642
7643   if (VT == MVT::v32i8) {
7644     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7645     if (NewOp.getNode())
7646       return NewOp;
7647   }
7648
7649   // Handle all 128-bit wide vectors with 4 elements, and match them with
7650   // several different shuffle types.
7651   if (NumElems == 4 && VT.is128BitVector())
7652     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7653
7654   // Handle general 256-bit shuffles
7655   if (VT.is256BitVector())
7656     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7657
7658   return SDValue();
7659 }
7660
7661 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7662   MVT VT = Op.getSimpleValueType();
7663   SDLoc dl(Op);
7664
7665   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7666     return SDValue();
7667
7668   if (VT.getSizeInBits() == 8) {
7669     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7670                                   Op.getOperand(0), Op.getOperand(1));
7671     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7672                                   DAG.getValueType(VT));
7673     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7674   }
7675
7676   if (VT.getSizeInBits() == 16) {
7677     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7678     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7679     if (Idx == 0)
7680       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7681                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7682                                      DAG.getNode(ISD::BITCAST, dl,
7683                                                  MVT::v4i32,
7684                                                  Op.getOperand(0)),
7685                                      Op.getOperand(1)));
7686     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7687                                   Op.getOperand(0), Op.getOperand(1));
7688     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7689                                   DAG.getValueType(VT));
7690     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7691   }
7692
7693   if (VT == MVT::f32) {
7694     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7695     // the result back to FR32 register. It's only worth matching if the
7696     // result has a single use which is a store or a bitcast to i32.  And in
7697     // the case of a store, it's not worth it if the index is a constant 0,
7698     // because a MOVSSmr can be used instead, which is smaller and faster.
7699     if (!Op.hasOneUse())
7700       return SDValue();
7701     SDNode *User = *Op.getNode()->use_begin();
7702     if ((User->getOpcode() != ISD::STORE ||
7703          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7704           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7705         (User->getOpcode() != ISD::BITCAST ||
7706          User->getValueType(0) != MVT::i32))
7707       return SDValue();
7708     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7709                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7710                                               Op.getOperand(0)),
7711                                               Op.getOperand(1));
7712     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7713   }
7714
7715   if (VT == MVT::i32 || VT == MVT::i64) {
7716     // ExtractPS/pextrq works with constant index.
7717     if (isa<ConstantSDNode>(Op.getOperand(1)))
7718       return Op;
7719   }
7720   return SDValue();
7721 }
7722
7723 /// Extract one bit from mask vector, like v16i1 or v8i1.
7724 /// AVX-512 feature.
7725 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) {
7726   SDValue Vec = Op.getOperand(0);
7727   SDLoc dl(Vec);
7728   MVT VecVT = Vec.getSimpleValueType();
7729   SDValue Idx = Op.getOperand(1);
7730   MVT EltVT = Op.getSimpleValueType();
7731
7732   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7733
7734   // variable index can't be handled in mask registers,
7735   // extend vector to VR512
7736   if (!isa<ConstantSDNode>(Idx)) {
7737     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7738     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7739     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7740                               ExtVT.getVectorElementType(), Ext, Idx);
7741     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7742   }
7743
7744   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7745   if (IdxVal) {
7746     unsigned MaxSift = VecVT.getSizeInBits() - 1;
7747     Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7748                       DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7749     Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7750                       DAG.getConstant(MaxSift, MVT::i8));
7751   }
7752   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i1, Vec,
7753                        DAG.getIntPtrConstant(0));
7754 }
7755
7756 SDValue
7757 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7758                                            SelectionDAG &DAG) const {
7759   SDLoc dl(Op);
7760   SDValue Vec = Op.getOperand(0);
7761   MVT VecVT = Vec.getSimpleValueType();
7762   SDValue Idx = Op.getOperand(1);
7763
7764   if (Op.getSimpleValueType() == MVT::i1)
7765     return ExtractBitFromMaskVector(Op, DAG);
7766
7767   if (!isa<ConstantSDNode>(Idx)) {
7768     if (VecVT.is512BitVector() ||
7769         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7770          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7771
7772       MVT MaskEltVT =
7773         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7774       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7775                                     MaskEltVT.getSizeInBits());
7776
7777       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7778       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7779                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7780                                 Idx, DAG.getConstant(0, getPointerTy()));
7781       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7782       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7783                         Perm, DAG.getConstant(0, getPointerTy()));
7784     }
7785     return SDValue();
7786   }
7787
7788   // If this is a 256-bit vector result, first extract the 128-bit vector and
7789   // then extract the element from the 128-bit vector.
7790   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7791
7792     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7793     // Get the 128-bit vector.
7794     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7795     MVT EltVT = VecVT.getVectorElementType();
7796
7797     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7798
7799     //if (IdxVal >= NumElems/2)
7800     //  IdxVal -= NumElems/2;
7801     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7802     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7803                        DAG.getConstant(IdxVal, MVT::i32));
7804   }
7805
7806   assert(VecVT.is128BitVector() && "Unexpected vector length");
7807
7808   if (Subtarget->hasSSE41()) {
7809     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7810     if (Res.getNode())
7811       return Res;
7812   }
7813
7814   MVT VT = Op.getSimpleValueType();
7815   // TODO: handle v16i8.
7816   if (VT.getSizeInBits() == 16) {
7817     SDValue Vec = Op.getOperand(0);
7818     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7819     if (Idx == 0)
7820       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7821                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7822                                      DAG.getNode(ISD::BITCAST, dl,
7823                                                  MVT::v4i32, Vec),
7824                                      Op.getOperand(1)));
7825     // Transform it so it match pextrw which produces a 32-bit result.
7826     MVT EltVT = MVT::i32;
7827     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7828                                   Op.getOperand(0), Op.getOperand(1));
7829     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7830                                   DAG.getValueType(VT));
7831     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7832   }
7833
7834   if (VT.getSizeInBits() == 32) {
7835     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7836     if (Idx == 0)
7837       return Op;
7838
7839     // SHUFPS the element to the lowest double word, then movss.
7840     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7841     MVT VVT = Op.getOperand(0).getSimpleValueType();
7842     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7843                                        DAG.getUNDEF(VVT), Mask);
7844     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7845                        DAG.getIntPtrConstant(0));
7846   }
7847
7848   if (VT.getSizeInBits() == 64) {
7849     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7850     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7851     //        to match extract_elt for f64.
7852     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7853     if (Idx == 0)
7854       return Op;
7855
7856     // UNPCKHPD the element to the lowest double word, then movsd.
7857     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7858     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7859     int Mask[2] = { 1, -1 };
7860     MVT VVT = Op.getOperand(0).getSimpleValueType();
7861     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7862                                        DAG.getUNDEF(VVT), Mask);
7863     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7864                        DAG.getIntPtrConstant(0));
7865   }
7866
7867   return SDValue();
7868 }
7869
7870 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7871   MVT VT = Op.getSimpleValueType();
7872   MVT EltVT = VT.getVectorElementType();
7873   SDLoc dl(Op);
7874
7875   SDValue N0 = Op.getOperand(0);
7876   SDValue N1 = Op.getOperand(1);
7877   SDValue N2 = Op.getOperand(2);
7878
7879   if (!VT.is128BitVector())
7880     return SDValue();
7881
7882   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7883       isa<ConstantSDNode>(N2)) {
7884     unsigned Opc;
7885     if (VT == MVT::v8i16)
7886       Opc = X86ISD::PINSRW;
7887     else if (VT == MVT::v16i8)
7888       Opc = X86ISD::PINSRB;
7889     else
7890       Opc = X86ISD::PINSRB;
7891
7892     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7893     // argument.
7894     if (N1.getValueType() != MVT::i32)
7895       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7896     if (N2.getValueType() != MVT::i32)
7897       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7898     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7899   }
7900
7901   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7902     // Bits [7:6] of the constant are the source select.  This will always be
7903     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7904     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7905     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7906     // Bits [5:4] of the constant are the destination select.  This is the
7907     //  value of the incoming immediate.
7908     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7909     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7910     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7911     // Create this as a scalar to vector..
7912     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7913     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7914   }
7915
7916   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7917     // PINSR* works with constant index.
7918     return Op;
7919   }
7920   return SDValue();
7921 }
7922
7923 SDValue
7924 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7925   MVT VT = Op.getSimpleValueType();
7926   MVT EltVT = VT.getVectorElementType();
7927
7928   SDLoc dl(Op);
7929   SDValue N0 = Op.getOperand(0);
7930   SDValue N1 = Op.getOperand(1);
7931   SDValue N2 = Op.getOperand(2);
7932
7933   // If this is a 256-bit vector result, first extract the 128-bit vector,
7934   // insert the element into the extracted half and then place it back.
7935   if (VT.is256BitVector() || VT.is512BitVector()) {
7936     if (!isa<ConstantSDNode>(N2))
7937       return SDValue();
7938
7939     // Get the desired 128-bit vector half.
7940     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7941     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7942
7943     // Insert the element into the desired half.
7944     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7945     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7946
7947     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7948                     DAG.getConstant(IdxIn128, MVT::i32));
7949
7950     // Insert the changed part back to the 256-bit vector
7951     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7952   }
7953
7954   if (Subtarget->hasSSE41())
7955     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7956
7957   if (EltVT == MVT::i8)
7958     return SDValue();
7959
7960   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7961     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7962     // as its second argument.
7963     if (N1.getValueType() != MVT::i32)
7964       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7965     if (N2.getValueType() != MVT::i32)
7966       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7967     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7968   }
7969   return SDValue();
7970 }
7971
7972 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7973   SDLoc dl(Op);
7974   MVT OpVT = Op.getSimpleValueType();
7975
7976   // If this is a 256-bit vector result, first insert into a 128-bit
7977   // vector and then insert into the 256-bit vector.
7978   if (!OpVT.is128BitVector()) {
7979     // Insert into a 128-bit vector.
7980     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7981     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7982                                  OpVT.getVectorNumElements() / SizeFactor);
7983
7984     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7985
7986     // Insert the 128-bit vector.
7987     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7988   }
7989
7990   if (OpVT == MVT::v1i64 &&
7991       Op.getOperand(0).getValueType() == MVT::i64)
7992     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7993
7994   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7995   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7996   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7997                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7998 }
7999
8000 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8001 // a simple subregister reference or explicit instructions to grab
8002 // upper bits of a vector.
8003 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8004                                       SelectionDAG &DAG) {
8005   SDLoc dl(Op);
8006   SDValue In =  Op.getOperand(0);
8007   SDValue Idx = Op.getOperand(1);
8008   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8009   MVT ResVT   = Op.getSimpleValueType();
8010   MVT InVT    = In.getSimpleValueType();
8011
8012   if (Subtarget->hasFp256()) {
8013     if (ResVT.is128BitVector() &&
8014         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8015         isa<ConstantSDNode>(Idx)) {
8016       return Extract128BitVector(In, IdxVal, DAG, dl);
8017     }
8018     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8019         isa<ConstantSDNode>(Idx)) {
8020       return Extract256BitVector(In, IdxVal, DAG, dl);
8021     }
8022   }
8023   return SDValue();
8024 }
8025
8026 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8027 // simple superregister reference or explicit instructions to insert
8028 // the upper bits of a vector.
8029 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8030                                      SelectionDAG &DAG) {
8031   if (Subtarget->hasFp256()) {
8032     SDLoc dl(Op.getNode());
8033     SDValue Vec = Op.getNode()->getOperand(0);
8034     SDValue SubVec = Op.getNode()->getOperand(1);
8035     SDValue Idx = Op.getNode()->getOperand(2);
8036
8037     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8038          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8039         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8040         isa<ConstantSDNode>(Idx)) {
8041       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8042       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8043     }
8044
8045     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8046         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8047         isa<ConstantSDNode>(Idx)) {
8048       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8049       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8050     }
8051   }
8052   return SDValue();
8053 }
8054
8055 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8056 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8057 // one of the above mentioned nodes. It has to be wrapped because otherwise
8058 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8059 // be used to form addressing mode. These wrapped nodes will be selected
8060 // into MOV32ri.
8061 SDValue
8062 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8063   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8064
8065   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8066   // global base reg.
8067   unsigned char OpFlag = 0;
8068   unsigned WrapperKind = X86ISD::Wrapper;
8069   CodeModel::Model M = getTargetMachine().getCodeModel();
8070
8071   if (Subtarget->isPICStyleRIPRel() &&
8072       (M == CodeModel::Small || M == CodeModel::Kernel))
8073     WrapperKind = X86ISD::WrapperRIP;
8074   else if (Subtarget->isPICStyleGOT())
8075     OpFlag = X86II::MO_GOTOFF;
8076   else if (Subtarget->isPICStyleStubPIC())
8077     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8078
8079   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8080                                              CP->getAlignment(),
8081                                              CP->getOffset(), OpFlag);
8082   SDLoc DL(CP);
8083   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8084   // With PIC, the address is actually $g + Offset.
8085   if (OpFlag) {
8086     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8087                          DAG.getNode(X86ISD::GlobalBaseReg,
8088                                      SDLoc(), getPointerTy()),
8089                          Result);
8090   }
8091
8092   return Result;
8093 }
8094
8095 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8096   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8097
8098   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8099   // global base reg.
8100   unsigned char OpFlag = 0;
8101   unsigned WrapperKind = X86ISD::Wrapper;
8102   CodeModel::Model M = getTargetMachine().getCodeModel();
8103
8104   if (Subtarget->isPICStyleRIPRel() &&
8105       (M == CodeModel::Small || M == CodeModel::Kernel))
8106     WrapperKind = X86ISD::WrapperRIP;
8107   else if (Subtarget->isPICStyleGOT())
8108     OpFlag = X86II::MO_GOTOFF;
8109   else if (Subtarget->isPICStyleStubPIC())
8110     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8111
8112   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8113                                           OpFlag);
8114   SDLoc DL(JT);
8115   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8116
8117   // With PIC, the address is actually $g + Offset.
8118   if (OpFlag)
8119     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8120                          DAG.getNode(X86ISD::GlobalBaseReg,
8121                                      SDLoc(), getPointerTy()),
8122                          Result);
8123
8124   return Result;
8125 }
8126
8127 SDValue
8128 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8129   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8130
8131   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8132   // global base reg.
8133   unsigned char OpFlag = 0;
8134   unsigned WrapperKind = X86ISD::Wrapper;
8135   CodeModel::Model M = getTargetMachine().getCodeModel();
8136
8137   if (Subtarget->isPICStyleRIPRel() &&
8138       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8139     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8140       OpFlag = X86II::MO_GOTPCREL;
8141     WrapperKind = X86ISD::WrapperRIP;
8142   } else if (Subtarget->isPICStyleGOT()) {
8143     OpFlag = X86II::MO_GOT;
8144   } else if (Subtarget->isPICStyleStubPIC()) {
8145     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8146   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8147     OpFlag = X86II::MO_DARWIN_NONLAZY;
8148   }
8149
8150   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8151
8152   SDLoc DL(Op);
8153   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8154
8155   // With PIC, the address is actually $g + Offset.
8156   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8157       !Subtarget->is64Bit()) {
8158     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8159                          DAG.getNode(X86ISD::GlobalBaseReg,
8160                                      SDLoc(), getPointerTy()),
8161                          Result);
8162   }
8163
8164   // For symbols that require a load from a stub to get the address, emit the
8165   // load.
8166   if (isGlobalStubReference(OpFlag))
8167     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8168                          MachinePointerInfo::getGOT(), false, false, false, 0);
8169
8170   return Result;
8171 }
8172
8173 SDValue
8174 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8175   // Create the TargetBlockAddressAddress node.
8176   unsigned char OpFlags =
8177     Subtarget->ClassifyBlockAddressReference();
8178   CodeModel::Model M = getTargetMachine().getCodeModel();
8179   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8180   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8181   SDLoc dl(Op);
8182   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8183                                              OpFlags);
8184
8185   if (Subtarget->isPICStyleRIPRel() &&
8186       (M == CodeModel::Small || M == CodeModel::Kernel))
8187     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8188   else
8189     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8190
8191   // With PIC, the address is actually $g + Offset.
8192   if (isGlobalRelativeToPICBase(OpFlags)) {
8193     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8194                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8195                          Result);
8196   }
8197
8198   return Result;
8199 }
8200
8201 SDValue
8202 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8203                                       int64_t Offset, SelectionDAG &DAG) const {
8204   // Create the TargetGlobalAddress node, folding in the constant
8205   // offset if it is legal.
8206   unsigned char OpFlags =
8207     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8208   CodeModel::Model M = getTargetMachine().getCodeModel();
8209   SDValue Result;
8210   if (OpFlags == X86II::MO_NO_FLAG &&
8211       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8212     // A direct static reference to a global.
8213     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8214     Offset = 0;
8215   } else {
8216     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8217   }
8218
8219   if (Subtarget->isPICStyleRIPRel() &&
8220       (M == CodeModel::Small || M == CodeModel::Kernel))
8221     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8222   else
8223     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8224
8225   // With PIC, the address is actually $g + Offset.
8226   if (isGlobalRelativeToPICBase(OpFlags)) {
8227     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8228                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8229                          Result);
8230   }
8231
8232   // For globals that require a load from a stub to get the address, emit the
8233   // load.
8234   if (isGlobalStubReference(OpFlags))
8235     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8236                          MachinePointerInfo::getGOT(), false, false, false, 0);
8237
8238   // If there was a non-zero offset that we didn't fold, create an explicit
8239   // addition for it.
8240   if (Offset != 0)
8241     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8242                          DAG.getConstant(Offset, getPointerTy()));
8243
8244   return Result;
8245 }
8246
8247 SDValue
8248 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8249   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8250   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8251   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8252 }
8253
8254 static SDValue
8255 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8256            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8257            unsigned char OperandFlags, bool LocalDynamic = false) {
8258   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8259   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8260   SDLoc dl(GA);
8261   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8262                                            GA->getValueType(0),
8263                                            GA->getOffset(),
8264                                            OperandFlags);
8265
8266   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8267                                            : X86ISD::TLSADDR;
8268
8269   if (InFlag) {
8270     SDValue Ops[] = { Chain,  TGA, *InFlag };
8271     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8272   } else {
8273     SDValue Ops[]  = { Chain, TGA };
8274     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8275   }
8276
8277   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8278   MFI->setAdjustsStack(true);
8279
8280   SDValue Flag = Chain.getValue(1);
8281   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8282 }
8283
8284 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8285 static SDValue
8286 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8287                                 const EVT PtrVT) {
8288   SDValue InFlag;
8289   SDLoc dl(GA);  // ? function entry point might be better
8290   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8291                                    DAG.getNode(X86ISD::GlobalBaseReg,
8292                                                SDLoc(), PtrVT), InFlag);
8293   InFlag = Chain.getValue(1);
8294
8295   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8296 }
8297
8298 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8299 static SDValue
8300 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8301                                 const EVT PtrVT) {
8302   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8303                     X86::RAX, X86II::MO_TLSGD);
8304 }
8305
8306 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8307                                            SelectionDAG &DAG,
8308                                            const EVT PtrVT,
8309                                            bool is64Bit) {
8310   SDLoc dl(GA);
8311
8312   // Get the start address of the TLS block for this module.
8313   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8314       .getInfo<X86MachineFunctionInfo>();
8315   MFI->incNumLocalDynamicTLSAccesses();
8316
8317   SDValue Base;
8318   if (is64Bit) {
8319     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8320                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8321   } else {
8322     SDValue InFlag;
8323     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8324         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8325     InFlag = Chain.getValue(1);
8326     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8327                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8328   }
8329
8330   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8331   // of Base.
8332
8333   // Build x@dtpoff.
8334   unsigned char OperandFlags = X86II::MO_DTPOFF;
8335   unsigned WrapperKind = X86ISD::Wrapper;
8336   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8337                                            GA->getValueType(0),
8338                                            GA->getOffset(), OperandFlags);
8339   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8340
8341   // Add x@dtpoff with the base.
8342   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8343 }
8344
8345 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8346 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8347                                    const EVT PtrVT, TLSModel::Model model,
8348                                    bool is64Bit, bool isPIC) {
8349   SDLoc dl(GA);
8350
8351   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8352   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8353                                                          is64Bit ? 257 : 256));
8354
8355   SDValue ThreadPointer =
8356       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8357                   MachinePointerInfo(Ptr), false, false, false, 0);
8358
8359   unsigned char OperandFlags = 0;
8360   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8361   // initialexec.
8362   unsigned WrapperKind = X86ISD::Wrapper;
8363   if (model == TLSModel::LocalExec) {
8364     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8365   } else if (model == TLSModel::InitialExec) {
8366     if (is64Bit) {
8367       OperandFlags = X86II::MO_GOTTPOFF;
8368       WrapperKind = X86ISD::WrapperRIP;
8369     } else {
8370       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8371     }
8372   } else {
8373     llvm_unreachable("Unexpected model");
8374   }
8375
8376   // emit "addl x@ntpoff,%eax" (local exec)
8377   // or "addl x@indntpoff,%eax" (initial exec)
8378   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8379   SDValue TGA =
8380       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8381                                  GA->getOffset(), OperandFlags);
8382   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8383
8384   if (model == TLSModel::InitialExec) {
8385     if (isPIC && !is64Bit) {
8386       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8387                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8388                            Offset);
8389     }
8390
8391     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8392                          MachinePointerInfo::getGOT(), false, false, false, 0);
8393   }
8394
8395   // The address of the thread local variable is the add of the thread
8396   // pointer with the offset of the variable.
8397   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8398 }
8399
8400 SDValue
8401 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8402
8403   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8404   const GlobalValue *GV = GA->getGlobal();
8405
8406   if (Subtarget->isTargetELF()) {
8407     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8408
8409     switch (model) {
8410       case TLSModel::GeneralDynamic:
8411         if (Subtarget->is64Bit())
8412           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8413         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8414       case TLSModel::LocalDynamic:
8415         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8416                                            Subtarget->is64Bit());
8417       case TLSModel::InitialExec:
8418       case TLSModel::LocalExec:
8419         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8420                                    Subtarget->is64Bit(),
8421                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8422     }
8423     llvm_unreachable("Unknown TLS model.");
8424   }
8425
8426   if (Subtarget->isTargetDarwin()) {
8427     // Darwin only has one model of TLS.  Lower to that.
8428     unsigned char OpFlag = 0;
8429     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8430                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8431
8432     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8433     // global base reg.
8434     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8435                   !Subtarget->is64Bit();
8436     if (PIC32)
8437       OpFlag = X86II::MO_TLVP_PIC_BASE;
8438     else
8439       OpFlag = X86II::MO_TLVP;
8440     SDLoc DL(Op);
8441     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8442                                                 GA->getValueType(0),
8443                                                 GA->getOffset(), OpFlag);
8444     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8445
8446     // With PIC32, the address is actually $g + Offset.
8447     if (PIC32)
8448       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8449                            DAG.getNode(X86ISD::GlobalBaseReg,
8450                                        SDLoc(), getPointerTy()),
8451                            Offset);
8452
8453     // Lowering the machine isd will make sure everything is in the right
8454     // location.
8455     SDValue Chain = DAG.getEntryNode();
8456     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8457     SDValue Args[] = { Chain, Offset };
8458     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8459
8460     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8461     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8462     MFI->setAdjustsStack(true);
8463
8464     // And our return value (tls address) is in the standard call return value
8465     // location.
8466     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8467     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8468                               Chain.getValue(1));
8469   }
8470
8471   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8472     // Just use the implicit TLS architecture
8473     // Need to generate someting similar to:
8474     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8475     //                                  ; from TEB
8476     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8477     //   mov     rcx, qword [rdx+rcx*8]
8478     //   mov     eax, .tls$:tlsvar
8479     //   [rax+rcx] contains the address
8480     // Windows 64bit: gs:0x58
8481     // Windows 32bit: fs:__tls_array
8482
8483     // If GV is an alias then use the aliasee for determining
8484     // thread-localness.
8485     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8486       GV = GA->resolveAliasedGlobal(false);
8487     SDLoc dl(GA);
8488     SDValue Chain = DAG.getEntryNode();
8489
8490     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8491     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8492     // use its literal value of 0x2C.
8493     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8494                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8495                                                              256)
8496                                         : Type::getInt32PtrTy(*DAG.getContext(),
8497                                                               257));
8498
8499     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8500       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8501         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8502
8503     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8504                                         MachinePointerInfo(Ptr),
8505                                         false, false, false, 0);
8506
8507     // Load the _tls_index variable
8508     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8509     if (Subtarget->is64Bit())
8510       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8511                            IDX, MachinePointerInfo(), MVT::i32,
8512                            false, false, 0);
8513     else
8514       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8515                         false, false, false, 0);
8516
8517     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8518                                     getPointerTy());
8519     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8520
8521     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8522     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8523                       false, false, false, 0);
8524
8525     // Get the offset of start of .tls section
8526     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8527                                              GA->getValueType(0),
8528                                              GA->getOffset(), X86II::MO_SECREL);
8529     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8530
8531     // The address of the thread local variable is the add of the thread
8532     // pointer with the offset of the variable.
8533     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8534   }
8535
8536   llvm_unreachable("TLS not implemented for this target.");
8537 }
8538
8539 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8540 /// and take a 2 x i32 value to shift plus a shift amount.
8541 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8542   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8543   MVT VT = Op.getSimpleValueType();
8544   unsigned VTBits = VT.getSizeInBits();
8545   SDLoc dl(Op);
8546   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8547   SDValue ShOpLo = Op.getOperand(0);
8548   SDValue ShOpHi = Op.getOperand(1);
8549   SDValue ShAmt  = Op.getOperand(2);
8550   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8551   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8552   // during isel.
8553   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8554                                   DAG.getConstant(VTBits - 1, MVT::i8));
8555   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8556                                      DAG.getConstant(VTBits - 1, MVT::i8))
8557                        : DAG.getConstant(0, VT);
8558
8559   SDValue Tmp2, Tmp3;
8560   if (Op.getOpcode() == ISD::SHL_PARTS) {
8561     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8562     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8563   } else {
8564     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8565     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8566   }
8567
8568   // If the shift amount is larger or equal than the width of a part we can't
8569   // rely on the results of shld/shrd. Insert a test and select the appropriate
8570   // values for large shift amounts.
8571   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8572                                 DAG.getConstant(VTBits, MVT::i8));
8573   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8574                              AndNode, DAG.getConstant(0, MVT::i8));
8575
8576   SDValue Hi, Lo;
8577   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8578   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8579   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8580
8581   if (Op.getOpcode() == ISD::SHL_PARTS) {
8582     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8583     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8584   } else {
8585     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8586     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8587   }
8588
8589   SDValue Ops[2] = { Lo, Hi };
8590   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8591 }
8592
8593 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8594                                            SelectionDAG &DAG) const {
8595   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8596
8597   if (SrcVT.isVector())
8598     return SDValue();
8599
8600   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8601          "Unknown SINT_TO_FP to lower!");
8602
8603   // These are really Legal; return the operand so the caller accepts it as
8604   // Legal.
8605   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8606     return Op;
8607   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8608       Subtarget->is64Bit()) {
8609     return Op;
8610   }
8611
8612   SDLoc dl(Op);
8613   unsigned Size = SrcVT.getSizeInBits()/8;
8614   MachineFunction &MF = DAG.getMachineFunction();
8615   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8616   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8617   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8618                                StackSlot,
8619                                MachinePointerInfo::getFixedStack(SSFI),
8620                                false, false, 0);
8621   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8622 }
8623
8624 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8625                                      SDValue StackSlot,
8626                                      SelectionDAG &DAG) const {
8627   // Build the FILD
8628   SDLoc DL(Op);
8629   SDVTList Tys;
8630   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8631   if (useSSE)
8632     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8633   else
8634     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8635
8636   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8637
8638   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8639   MachineMemOperand *MMO;
8640   if (FI) {
8641     int SSFI = FI->getIndex();
8642     MMO =
8643       DAG.getMachineFunction()
8644       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8645                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8646   } else {
8647     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8648     StackSlot = StackSlot.getOperand(1);
8649   }
8650   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8651   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8652                                            X86ISD::FILD, DL,
8653                                            Tys, Ops, array_lengthof(Ops),
8654                                            SrcVT, MMO);
8655
8656   if (useSSE) {
8657     Chain = Result.getValue(1);
8658     SDValue InFlag = Result.getValue(2);
8659
8660     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8661     // shouldn't be necessary except that RFP cannot be live across
8662     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8663     MachineFunction &MF = DAG.getMachineFunction();
8664     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8665     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8666     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8667     Tys = DAG.getVTList(MVT::Other);
8668     SDValue Ops[] = {
8669       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8670     };
8671     MachineMemOperand *MMO =
8672       DAG.getMachineFunction()
8673       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8674                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8675
8676     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8677                                     Ops, array_lengthof(Ops),
8678                                     Op.getValueType(), MMO);
8679     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8680                          MachinePointerInfo::getFixedStack(SSFI),
8681                          false, false, false, 0);
8682   }
8683
8684   return Result;
8685 }
8686
8687 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8688 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8689                                                SelectionDAG &DAG) const {
8690   // This algorithm is not obvious. Here it is what we're trying to output:
8691   /*
8692      movq       %rax,  %xmm0
8693      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8694      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8695      #ifdef __SSE3__
8696        haddpd   %xmm0, %xmm0
8697      #else
8698        pshufd   $0x4e, %xmm0, %xmm1
8699        addpd    %xmm1, %xmm0
8700      #endif
8701   */
8702
8703   SDLoc dl(Op);
8704   LLVMContext *Context = DAG.getContext();
8705
8706   // Build some magic constants.
8707   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8708   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8709   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8710
8711   SmallVector<Constant*,2> CV1;
8712   CV1.push_back(
8713     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8714                                       APInt(64, 0x4330000000000000ULL))));
8715   CV1.push_back(
8716     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8717                                       APInt(64, 0x4530000000000000ULL))));
8718   Constant *C1 = ConstantVector::get(CV1);
8719   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8720
8721   // Load the 64-bit value into an XMM register.
8722   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8723                             Op.getOperand(0));
8724   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8725                               MachinePointerInfo::getConstantPool(),
8726                               false, false, false, 16);
8727   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8728                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8729                               CLod0);
8730
8731   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8732                               MachinePointerInfo::getConstantPool(),
8733                               false, false, false, 16);
8734   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8735   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8736   SDValue Result;
8737
8738   if (Subtarget->hasSSE3()) {
8739     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8740     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8741   } else {
8742     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8743     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8744                                            S2F, 0x4E, DAG);
8745     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8746                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8747                          Sub);
8748   }
8749
8750   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8751                      DAG.getIntPtrConstant(0));
8752 }
8753
8754 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8755 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8756                                                SelectionDAG &DAG) const {
8757   SDLoc dl(Op);
8758   // FP constant to bias correct the final result.
8759   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8760                                    MVT::f64);
8761
8762   // Load the 32-bit value into an XMM register.
8763   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8764                              Op.getOperand(0));
8765
8766   // Zero out the upper parts of the register.
8767   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8768
8769   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8770                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8771                      DAG.getIntPtrConstant(0));
8772
8773   // Or the load with the bias.
8774   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8775                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8776                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8777                                                    MVT::v2f64, Load)),
8778                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8779                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8780                                                    MVT::v2f64, Bias)));
8781   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8782                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8783                    DAG.getIntPtrConstant(0));
8784
8785   // Subtract the bias.
8786   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8787
8788   // Handle final rounding.
8789   EVT DestVT = Op.getValueType();
8790
8791   if (DestVT.bitsLT(MVT::f64))
8792     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8793                        DAG.getIntPtrConstant(0));
8794   if (DestVT.bitsGT(MVT::f64))
8795     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8796
8797   // Handle final rounding.
8798   return Sub;
8799 }
8800
8801 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8802                                                SelectionDAG &DAG) const {
8803   SDValue N0 = Op.getOperand(0);
8804   MVT SVT = N0.getSimpleValueType();
8805   SDLoc dl(Op);
8806
8807   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8808           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8809          "Custom UINT_TO_FP is not supported!");
8810
8811   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8812   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8813                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8814 }
8815
8816 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8817                                            SelectionDAG &DAG) const {
8818   SDValue N0 = Op.getOperand(0);
8819   SDLoc dl(Op);
8820
8821   if (Op.getValueType().isVector())
8822     return lowerUINT_TO_FP_vec(Op, DAG);
8823
8824   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8825   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8826   // the optimization here.
8827   if (DAG.SignBitIsZero(N0))
8828     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8829
8830   MVT SrcVT = N0.getSimpleValueType();
8831   MVT DstVT = Op.getSimpleValueType();
8832   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8833     return LowerUINT_TO_FP_i64(Op, DAG);
8834   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8835     return LowerUINT_TO_FP_i32(Op, DAG);
8836   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8837     return SDValue();
8838
8839   // Make a 64-bit buffer, and use it to build an FILD.
8840   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8841   if (SrcVT == MVT::i32) {
8842     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8843     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8844                                      getPointerTy(), StackSlot, WordOff);
8845     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8846                                   StackSlot, MachinePointerInfo(),
8847                                   false, false, 0);
8848     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8849                                   OffsetSlot, MachinePointerInfo(),
8850                                   false, false, 0);
8851     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8852     return Fild;
8853   }
8854
8855   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8856   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8857                                StackSlot, MachinePointerInfo(),
8858                                false, false, 0);
8859   // For i64 source, we need to add the appropriate power of 2 if the input
8860   // was negative.  This is the same as the optimization in
8861   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8862   // we must be careful to do the computation in x87 extended precision, not
8863   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8864   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8865   MachineMemOperand *MMO =
8866     DAG.getMachineFunction()
8867     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8868                           MachineMemOperand::MOLoad, 8, 8);
8869
8870   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8871   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8872   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8873                                          array_lengthof(Ops), MVT::i64, MMO);
8874
8875   APInt FF(32, 0x5F800000ULL);
8876
8877   // Check whether the sign bit is set.
8878   SDValue SignSet = DAG.getSetCC(dl,
8879                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8880                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8881                                  ISD::SETLT);
8882
8883   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8884   SDValue FudgePtr = DAG.getConstantPool(
8885                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8886                                          getPointerTy());
8887
8888   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8889   SDValue Zero = DAG.getIntPtrConstant(0);
8890   SDValue Four = DAG.getIntPtrConstant(4);
8891   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8892                                Zero, Four);
8893   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8894
8895   // Load the value out, extending it from f32 to f80.
8896   // FIXME: Avoid the extend by constructing the right constant pool?
8897   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8898                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8899                                  MVT::f32, false, false, 4);
8900   // Extend everything to 80 bits to force it to be done on x87.
8901   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8902   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8903 }
8904
8905 std::pair<SDValue,SDValue>
8906 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8907                                     bool IsSigned, bool IsReplace) const {
8908   SDLoc DL(Op);
8909
8910   EVT DstTy = Op.getValueType();
8911
8912   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8913     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8914     DstTy = MVT::i64;
8915   }
8916
8917   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8918          DstTy.getSimpleVT() >= MVT::i16 &&
8919          "Unknown FP_TO_INT to lower!");
8920
8921   // These are really Legal.
8922   if (DstTy == MVT::i32 &&
8923       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8924     return std::make_pair(SDValue(), SDValue());
8925   if (Subtarget->is64Bit() &&
8926       DstTy == MVT::i64 &&
8927       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8928     return std::make_pair(SDValue(), SDValue());
8929
8930   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8931   // stack slot, or into the FTOL runtime function.
8932   MachineFunction &MF = DAG.getMachineFunction();
8933   unsigned MemSize = DstTy.getSizeInBits()/8;
8934   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8935   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8936
8937   unsigned Opc;
8938   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8939     Opc = X86ISD::WIN_FTOL;
8940   else
8941     switch (DstTy.getSimpleVT().SimpleTy) {
8942     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8943     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8944     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8945     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8946     }
8947
8948   SDValue Chain = DAG.getEntryNode();
8949   SDValue Value = Op.getOperand(0);
8950   EVT TheVT = Op.getOperand(0).getValueType();
8951   // FIXME This causes a redundant load/store if the SSE-class value is already
8952   // in memory, such as if it is on the callstack.
8953   if (isScalarFPTypeInSSEReg(TheVT)) {
8954     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8955     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8956                          MachinePointerInfo::getFixedStack(SSFI),
8957                          false, false, 0);
8958     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8959     SDValue Ops[] = {
8960       Chain, StackSlot, DAG.getValueType(TheVT)
8961     };
8962
8963     MachineMemOperand *MMO =
8964       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8965                               MachineMemOperand::MOLoad, MemSize, MemSize);
8966     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8967                                     array_lengthof(Ops), DstTy, MMO);
8968     Chain = Value.getValue(1);
8969     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8970     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8971   }
8972
8973   MachineMemOperand *MMO =
8974     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8975                             MachineMemOperand::MOStore, MemSize, MemSize);
8976
8977   if (Opc != X86ISD::WIN_FTOL) {
8978     // Build the FP_TO_INT*_IN_MEM
8979     SDValue Ops[] = { Chain, Value, StackSlot };
8980     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8981                                            Ops, array_lengthof(Ops), DstTy,
8982                                            MMO);
8983     return std::make_pair(FIST, StackSlot);
8984   } else {
8985     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8986       DAG.getVTList(MVT::Other, MVT::Glue),
8987       Chain, Value);
8988     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8989       MVT::i32, ftol.getValue(1));
8990     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8991       MVT::i32, eax.getValue(2));
8992     SDValue Ops[] = { eax, edx };
8993     SDValue pair = IsReplace
8994       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8995       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8996     return std::make_pair(pair, SDValue());
8997   }
8998 }
8999
9000 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9001                               const X86Subtarget *Subtarget) {
9002   MVT VT = Op->getSimpleValueType(0);
9003   SDValue In = Op->getOperand(0);
9004   MVT InVT = In.getSimpleValueType();
9005   SDLoc dl(Op);
9006
9007   // Optimize vectors in AVX mode:
9008   //
9009   //   v8i16 -> v8i32
9010   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9011   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9012   //   Concat upper and lower parts.
9013   //
9014   //   v4i32 -> v4i64
9015   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9016   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9017   //   Concat upper and lower parts.
9018   //
9019
9020   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9021       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9022       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9023     return SDValue();
9024
9025   if (Subtarget->hasInt256())
9026     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
9027
9028   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9029   SDValue Undef = DAG.getUNDEF(InVT);
9030   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9031   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9032   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9033
9034   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9035                              VT.getVectorNumElements()/2);
9036
9037   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9038   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9039
9040   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9041 }
9042
9043 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9044                                         SelectionDAG &DAG) {
9045   MVT VT = Op->getSimpleValueType(0);
9046   SDValue In = Op->getOperand(0);
9047   MVT InVT = In.getSimpleValueType();
9048   SDLoc DL(Op);
9049   unsigned int NumElts = VT.getVectorNumElements();
9050   if (NumElts != 8 && NumElts != 16)
9051     return SDValue();
9052
9053   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9054     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9055
9056   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9058   // Now we have only mask extension
9059   assert(InVT.getVectorElementType() == MVT::i1);
9060   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9061   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9062   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9063   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9064   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9065                            MachinePointerInfo::getConstantPool(),
9066                            false, false, false, Alignment);
9067
9068   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9069   if (VT.is512BitVector())
9070     return Brcst;
9071   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9072 }
9073
9074 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9075                                SelectionDAG &DAG) {
9076   if (Subtarget->hasFp256()) {
9077     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9078     if (Res.getNode())
9079       return Res;
9080   }
9081
9082   return SDValue();
9083 }
9084
9085 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9086                                 SelectionDAG &DAG) {
9087   SDLoc DL(Op);
9088   MVT VT = Op.getSimpleValueType();
9089   SDValue In = Op.getOperand(0);
9090   MVT SVT = In.getSimpleValueType();
9091
9092   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9093     return LowerZERO_EXTEND_AVX512(Op, DAG);
9094
9095   if (Subtarget->hasFp256()) {
9096     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9097     if (Res.getNode())
9098       return Res;
9099   }
9100
9101   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9102          VT.getVectorNumElements() != SVT.getVectorNumElements());
9103   return SDValue();
9104 }
9105
9106 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9107   SDLoc DL(Op);
9108   MVT VT = Op.getSimpleValueType();
9109   SDValue In = Op.getOperand(0);
9110   MVT InVT = In.getSimpleValueType();
9111
9112   if (VT == MVT::i1) {
9113     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9114            "Invalid scalar TRUNCATE operation");
9115     if (InVT == MVT::i32)
9116       return SDValue();
9117     if (InVT.getSizeInBits() == 64)
9118       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9119     else if (InVT.getSizeInBits() < 32)
9120       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9121     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9122   }
9123   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9124          "Invalid TRUNCATE operation");
9125
9126   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9127     if (VT.getVectorElementType().getSizeInBits() >=8)
9128       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9129
9130     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9131     unsigned NumElts = InVT.getVectorNumElements();
9132     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9133     if (InVT.getSizeInBits() < 512) {
9134       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9135       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9136       InVT = ExtVT;
9137     }
9138     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9139     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9140     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9141     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9142     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9143                            MachinePointerInfo::getConstantPool(),
9144                            false, false, false, Alignment);
9145     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9146     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9147     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9148   }
9149
9150   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9151     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9152     if (Subtarget->hasInt256()) {
9153       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9154       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9155       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9156                                 ShufMask);
9157       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9158                          DAG.getIntPtrConstant(0));
9159     }
9160
9161     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9162     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9163                                DAG.getIntPtrConstant(0));
9164     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9165                                DAG.getIntPtrConstant(2));
9166
9167     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9168     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9169
9170     // The PSHUFD mask:
9171     static const int ShufMask1[] = {0, 2, 0, 0};
9172     SDValue Undef = DAG.getUNDEF(VT);
9173     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9174     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9175
9176     // The MOVLHPS mask:
9177     static const int ShufMask2[] = {0, 1, 4, 5};
9178     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9179   }
9180
9181   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9182     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9183     if (Subtarget->hasInt256()) {
9184       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9185
9186       SmallVector<SDValue,32> pshufbMask;
9187       for (unsigned i = 0; i < 2; ++i) {
9188         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9189         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9190         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9191         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9192         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9193         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9194         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9195         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9196         for (unsigned j = 0; j < 8; ++j)
9197           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9198       }
9199       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9200                                &pshufbMask[0], 32);
9201       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9202       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9203
9204       static const int ShufMask[] = {0,  2,  -1,  -1};
9205       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9206                                 &ShufMask[0]);
9207       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9208                        DAG.getIntPtrConstant(0));
9209       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9210     }
9211
9212     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9213                                DAG.getIntPtrConstant(0));
9214
9215     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9216                                DAG.getIntPtrConstant(4));
9217
9218     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9219     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9220
9221     // The PSHUFB mask:
9222     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9223                                    -1, -1, -1, -1, -1, -1, -1, -1};
9224
9225     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9226     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9227     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9228
9229     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9230     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9231
9232     // The MOVLHPS Mask:
9233     static const int ShufMask2[] = {0, 1, 4, 5};
9234     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9235     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9236   }
9237
9238   // Handle truncation of V256 to V128 using shuffles.
9239   if (!VT.is128BitVector() || !InVT.is256BitVector())
9240     return SDValue();
9241
9242   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9243
9244   unsigned NumElems = VT.getVectorNumElements();
9245   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9246
9247   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9248   // Prepare truncation shuffle mask
9249   for (unsigned i = 0; i != NumElems; ++i)
9250     MaskVec[i] = i * 2;
9251   SDValue V = DAG.getVectorShuffle(NVT, DL,
9252                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9253                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9254   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9255                      DAG.getIntPtrConstant(0));
9256 }
9257
9258 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9259                                            SelectionDAG &DAG) const {
9260   MVT VT = Op.getSimpleValueType();
9261   if (VT.isVector()) {
9262     if (VT == MVT::v8i16)
9263       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9264                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9265                                      MVT::v8i32, Op.getOperand(0)));
9266     return SDValue();
9267   }
9268
9269   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9270     /*IsSigned=*/ true, /*IsReplace=*/ false);
9271   SDValue FIST = Vals.first, StackSlot = Vals.second;
9272   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9273   if (FIST.getNode() == 0) return Op;
9274
9275   if (StackSlot.getNode())
9276     // Load the result.
9277     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9278                        FIST, StackSlot, MachinePointerInfo(),
9279                        false, false, false, 0);
9280
9281   // The node is the result.
9282   return FIST;
9283 }
9284
9285 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9286                                            SelectionDAG &DAG) const {
9287   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9288     /*IsSigned=*/ false, /*IsReplace=*/ false);
9289   SDValue FIST = Vals.first, StackSlot = Vals.second;
9290   assert(FIST.getNode() && "Unexpected failure");
9291
9292   if (StackSlot.getNode())
9293     // Load the result.
9294     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9295                        FIST, StackSlot, MachinePointerInfo(),
9296                        false, false, false, 0);
9297
9298   // The node is the result.
9299   return FIST;
9300 }
9301
9302 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9303   SDLoc DL(Op);
9304   MVT VT = Op.getSimpleValueType();
9305   SDValue In = Op.getOperand(0);
9306   MVT SVT = In.getSimpleValueType();
9307
9308   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9309
9310   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9311                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9312                                  In, DAG.getUNDEF(SVT)));
9313 }
9314
9315 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9316   LLVMContext *Context = DAG.getContext();
9317   SDLoc dl(Op);
9318   MVT VT = Op.getSimpleValueType();
9319   MVT EltVT = VT;
9320   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9321   if (VT.isVector()) {
9322     EltVT = VT.getVectorElementType();
9323     NumElts = VT.getVectorNumElements();
9324   }
9325   Constant *C;
9326   if (EltVT == MVT::f64)
9327     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9328                                           APInt(64, ~(1ULL << 63))));
9329   else
9330     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9331                                           APInt(32, ~(1U << 31))));
9332   C = ConstantVector::getSplat(NumElts, C);
9333   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9334   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9335   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9336   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9337                              MachinePointerInfo::getConstantPool(),
9338                              false, false, false, Alignment);
9339   if (VT.isVector()) {
9340     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9341     return DAG.getNode(ISD::BITCAST, dl, VT,
9342                        DAG.getNode(ISD::AND, dl, ANDVT,
9343                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9344                                                Op.getOperand(0)),
9345                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9346   }
9347   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9348 }
9349
9350 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9351   LLVMContext *Context = DAG.getContext();
9352   SDLoc dl(Op);
9353   MVT VT = Op.getSimpleValueType();
9354   MVT EltVT = VT;
9355   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9356   if (VT.isVector()) {
9357     EltVT = VT.getVectorElementType();
9358     NumElts = VT.getVectorNumElements();
9359   }
9360   Constant *C;
9361   if (EltVT == MVT::f64)
9362     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9363                                           APInt(64, 1ULL << 63)));
9364   else
9365     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9366                                           APInt(32, 1U << 31)));
9367   C = ConstantVector::getSplat(NumElts, C);
9368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9369   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9370   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9371   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9372                              MachinePointerInfo::getConstantPool(),
9373                              false, false, false, Alignment);
9374   if (VT.isVector()) {
9375     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9376     return DAG.getNode(ISD::BITCAST, dl, VT,
9377                        DAG.getNode(ISD::XOR, dl, XORVT,
9378                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9379                                                Op.getOperand(0)),
9380                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9381   }
9382
9383   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9384 }
9385
9386 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9387   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9388   LLVMContext *Context = DAG.getContext();
9389   SDValue Op0 = Op.getOperand(0);
9390   SDValue Op1 = Op.getOperand(1);
9391   SDLoc dl(Op);
9392   MVT VT = Op.getSimpleValueType();
9393   MVT SrcVT = Op1.getSimpleValueType();
9394
9395   // If second operand is smaller, extend it first.
9396   if (SrcVT.bitsLT(VT)) {
9397     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9398     SrcVT = VT;
9399   }
9400   // And if it is bigger, shrink it first.
9401   if (SrcVT.bitsGT(VT)) {
9402     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9403     SrcVT = VT;
9404   }
9405
9406   // At this point the operands and the result should have the same
9407   // type, and that won't be f80 since that is not custom lowered.
9408
9409   // First get the sign bit of second operand.
9410   SmallVector<Constant*,4> CV;
9411   if (SrcVT == MVT::f64) {
9412     const fltSemantics &Sem = APFloat::IEEEdouble;
9413     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9414     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9415   } else {
9416     const fltSemantics &Sem = APFloat::IEEEsingle;
9417     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9418     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9419     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9420     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9421   }
9422   Constant *C = ConstantVector::get(CV);
9423   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9424   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9425                               MachinePointerInfo::getConstantPool(),
9426                               false, false, false, 16);
9427   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9428
9429   // Shift sign bit right or left if the two operands have different types.
9430   if (SrcVT.bitsGT(VT)) {
9431     // Op0 is MVT::f32, Op1 is MVT::f64.
9432     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9433     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9434                           DAG.getConstant(32, MVT::i32));
9435     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9436     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9437                           DAG.getIntPtrConstant(0));
9438   }
9439
9440   // Clear first operand sign bit.
9441   CV.clear();
9442   if (VT == MVT::f64) {
9443     const fltSemantics &Sem = APFloat::IEEEdouble;
9444     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9445                                                    APInt(64, ~(1ULL << 63)))));
9446     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9447   } else {
9448     const fltSemantics &Sem = APFloat::IEEEsingle;
9449     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9450                                                    APInt(32, ~(1U << 31)))));
9451     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9452     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9453     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9454   }
9455   C = ConstantVector::get(CV);
9456   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9457   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9458                               MachinePointerInfo::getConstantPool(),
9459                               false, false, false, 16);
9460   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9461
9462   // Or the value with the sign bit.
9463   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9464 }
9465
9466 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9467   SDValue N0 = Op.getOperand(0);
9468   SDLoc dl(Op);
9469   MVT VT = Op.getSimpleValueType();
9470
9471   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9472   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9473                                   DAG.getConstant(1, VT));
9474   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9475 }
9476
9477 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9478 //
9479 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9480                                       SelectionDAG &DAG) {
9481   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9482
9483   if (!Subtarget->hasSSE41())
9484     return SDValue();
9485
9486   if (!Op->hasOneUse())
9487     return SDValue();
9488
9489   SDNode *N = Op.getNode();
9490   SDLoc DL(N);
9491
9492   SmallVector<SDValue, 8> Opnds;
9493   DenseMap<SDValue, unsigned> VecInMap;
9494   EVT VT = MVT::Other;
9495
9496   // Recognize a special case where a vector is casted into wide integer to
9497   // test all 0s.
9498   Opnds.push_back(N->getOperand(0));
9499   Opnds.push_back(N->getOperand(1));
9500
9501   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9502     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9503     // BFS traverse all OR'd operands.
9504     if (I->getOpcode() == ISD::OR) {
9505       Opnds.push_back(I->getOperand(0));
9506       Opnds.push_back(I->getOperand(1));
9507       // Re-evaluate the number of nodes to be traversed.
9508       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9509       continue;
9510     }
9511
9512     // Quit if a non-EXTRACT_VECTOR_ELT
9513     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9514       return SDValue();
9515
9516     // Quit if without a constant index.
9517     SDValue Idx = I->getOperand(1);
9518     if (!isa<ConstantSDNode>(Idx))
9519       return SDValue();
9520
9521     SDValue ExtractedFromVec = I->getOperand(0);
9522     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9523     if (M == VecInMap.end()) {
9524       VT = ExtractedFromVec.getValueType();
9525       // Quit if not 128/256-bit vector.
9526       if (!VT.is128BitVector() && !VT.is256BitVector())
9527         return SDValue();
9528       // Quit if not the same type.
9529       if (VecInMap.begin() != VecInMap.end() &&
9530           VT != VecInMap.begin()->first.getValueType())
9531         return SDValue();
9532       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9533     }
9534     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9535   }
9536
9537   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9538          "Not extracted from 128-/256-bit vector.");
9539
9540   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9541   SmallVector<SDValue, 8> VecIns;
9542
9543   for (DenseMap<SDValue, unsigned>::const_iterator
9544         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9545     // Quit if not all elements are used.
9546     if (I->second != FullMask)
9547       return SDValue();
9548     VecIns.push_back(I->first);
9549   }
9550
9551   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9552
9553   // Cast all vectors into TestVT for PTEST.
9554   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9555     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9556
9557   // If more than one full vectors are evaluated, OR them first before PTEST.
9558   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9559     // Each iteration will OR 2 nodes and append the result until there is only
9560     // 1 node left, i.e. the final OR'd value of all vectors.
9561     SDValue LHS = VecIns[Slot];
9562     SDValue RHS = VecIns[Slot + 1];
9563     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9564   }
9565
9566   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9567                      VecIns.back(), VecIns.back());
9568 }
9569
9570 /// Emit nodes that will be selected as "test Op0,Op0", or something
9571 /// equivalent.
9572 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9573                                     SelectionDAG &DAG) const {
9574   SDLoc dl(Op);
9575
9576   if (Op.getValueType() == MVT::i1)
9577     // KORTEST instruction should be selected
9578     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9579                        DAG.getConstant(0, Op.getValueType()));
9580
9581   // CF and OF aren't always set the way we want. Determine which
9582   // of these we need.
9583   bool NeedCF = false;
9584   bool NeedOF = false;
9585   switch (X86CC) {
9586   default: break;
9587   case X86::COND_A: case X86::COND_AE:
9588   case X86::COND_B: case X86::COND_BE:
9589     NeedCF = true;
9590     break;
9591   case X86::COND_G: case X86::COND_GE:
9592   case X86::COND_L: case X86::COND_LE:
9593   case X86::COND_O: case X86::COND_NO:
9594     NeedOF = true;
9595     break;
9596   }
9597   // See if we can use the EFLAGS value from the operand instead of
9598   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9599   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9600   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9601     // Emit a CMP with 0, which is the TEST pattern.
9602     //if (Op.getValueType() == MVT::i1)
9603     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9604     //                     DAG.getConstant(0, MVT::i1));
9605     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9606                        DAG.getConstant(0, Op.getValueType()));
9607   }
9608   unsigned Opcode = 0;
9609   unsigned NumOperands = 0;
9610
9611   // Truncate operations may prevent the merge of the SETCC instruction
9612   // and the arithmetic instruction before it. Attempt to truncate the operands
9613   // of the arithmetic instruction and use a reduced bit-width instruction.
9614   bool NeedTruncation = false;
9615   SDValue ArithOp = Op;
9616   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9617     SDValue Arith = Op->getOperand(0);
9618     // Both the trunc and the arithmetic op need to have one user each.
9619     if (Arith->hasOneUse())
9620       switch (Arith.getOpcode()) {
9621         default: break;
9622         case ISD::ADD:
9623         case ISD::SUB:
9624         case ISD::AND:
9625         case ISD::OR:
9626         case ISD::XOR: {
9627           NeedTruncation = true;
9628           ArithOp = Arith;
9629         }
9630       }
9631   }
9632
9633   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9634   // which may be the result of a CAST.  We use the variable 'Op', which is the
9635   // non-casted variable when we check for possible users.
9636   switch (ArithOp.getOpcode()) {
9637   case ISD::ADD:
9638     // Due to an isel shortcoming, be conservative if this add is likely to be
9639     // selected as part of a load-modify-store instruction. When the root node
9640     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9641     // uses of other nodes in the match, such as the ADD in this case. This
9642     // leads to the ADD being left around and reselected, with the result being
9643     // two adds in the output.  Alas, even if none our users are stores, that
9644     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9645     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9646     // climbing the DAG back to the root, and it doesn't seem to be worth the
9647     // effort.
9648     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9649          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9650       if (UI->getOpcode() != ISD::CopyToReg &&
9651           UI->getOpcode() != ISD::SETCC &&
9652           UI->getOpcode() != ISD::STORE)
9653         goto default_case;
9654
9655     if (ConstantSDNode *C =
9656         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9657       // An add of one will be selected as an INC.
9658       if (C->getAPIntValue() == 1) {
9659         Opcode = X86ISD::INC;
9660         NumOperands = 1;
9661         break;
9662       }
9663
9664       // An add of negative one (subtract of one) will be selected as a DEC.
9665       if (C->getAPIntValue().isAllOnesValue()) {
9666         Opcode = X86ISD::DEC;
9667         NumOperands = 1;
9668         break;
9669       }
9670     }
9671
9672     // Otherwise use a regular EFLAGS-setting add.
9673     Opcode = X86ISD::ADD;
9674     NumOperands = 2;
9675     break;
9676   case ISD::AND: {
9677     // If the primary and result isn't used, don't bother using X86ISD::AND,
9678     // because a TEST instruction will be better.
9679     bool NonFlagUse = false;
9680     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9681            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9682       SDNode *User = *UI;
9683       unsigned UOpNo = UI.getOperandNo();
9684       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9685         // Look pass truncate.
9686         UOpNo = User->use_begin().getOperandNo();
9687         User = *User->use_begin();
9688       }
9689
9690       if (User->getOpcode() != ISD::BRCOND &&
9691           User->getOpcode() != ISD::SETCC &&
9692           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9693         NonFlagUse = true;
9694         break;
9695       }
9696     }
9697
9698     if (!NonFlagUse)
9699       break;
9700   }
9701     // FALL THROUGH
9702   case ISD::SUB:
9703   case ISD::OR:
9704   case ISD::XOR:
9705     // Due to the ISEL shortcoming noted above, be conservative if this op is
9706     // likely to be selected as part of a load-modify-store instruction.
9707     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9708            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9709       if (UI->getOpcode() == ISD::STORE)
9710         goto default_case;
9711
9712     // Otherwise use a regular EFLAGS-setting instruction.
9713     switch (ArithOp.getOpcode()) {
9714     default: llvm_unreachable("unexpected operator!");
9715     case ISD::SUB: Opcode = X86ISD::SUB; break;
9716     case ISD::XOR: Opcode = X86ISD::XOR; break;
9717     case ISD::AND: Opcode = X86ISD::AND; break;
9718     case ISD::OR: {
9719       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9720         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9721         if (EFLAGS.getNode())
9722           return EFLAGS;
9723       }
9724       Opcode = X86ISD::OR;
9725       break;
9726     }
9727     }
9728
9729     NumOperands = 2;
9730     break;
9731   case X86ISD::ADD:
9732   case X86ISD::SUB:
9733   case X86ISD::INC:
9734   case X86ISD::DEC:
9735   case X86ISD::OR:
9736   case X86ISD::XOR:
9737   case X86ISD::AND:
9738     return SDValue(Op.getNode(), 1);
9739   default:
9740   default_case:
9741     break;
9742   }
9743
9744   // If we found that truncation is beneficial, perform the truncation and
9745   // update 'Op'.
9746   if (NeedTruncation) {
9747     EVT VT = Op.getValueType();
9748     SDValue WideVal = Op->getOperand(0);
9749     EVT WideVT = WideVal.getValueType();
9750     unsigned ConvertedOp = 0;
9751     // Use a target machine opcode to prevent further DAGCombine
9752     // optimizations that may separate the arithmetic operations
9753     // from the setcc node.
9754     switch (WideVal.getOpcode()) {
9755       default: break;
9756       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9757       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9758       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9759       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9760       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9761     }
9762
9763     if (ConvertedOp) {
9764       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9765       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9766         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9767         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9768         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9769       }
9770     }
9771   }
9772
9773   if (Opcode == 0)
9774     // Emit a CMP with 0, which is the TEST pattern.
9775     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9776                        DAG.getConstant(0, Op.getValueType()));
9777
9778   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9779   SmallVector<SDValue, 4> Ops;
9780   for (unsigned i = 0; i != NumOperands; ++i)
9781     Ops.push_back(Op.getOperand(i));
9782
9783   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9784   DAG.ReplaceAllUsesWith(Op, New);
9785   return SDValue(New.getNode(), 1);
9786 }
9787
9788 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9789 /// equivalent.
9790 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9791                                    SelectionDAG &DAG) const {
9792   SDLoc dl(Op0);
9793   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9794     if (C->getAPIntValue() == 0)
9795       return EmitTest(Op0, X86CC, DAG);
9796
9797      if (Op0.getValueType() == MVT::i1) {
9798        // invert the value
9799       Op0 = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0,
9800                         DAG.getConstant(-1, MVT::i1));
9801       return EmitTest(Op0, X86CC, DAG);
9802      }
9803   }
9804  
9805   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9806        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9807     // Do the comparison at i32 if it's smaller. This avoids subregister
9808     // aliasing issues. Keep the smaller reference if we're optimizing for
9809     // size, however, as that'll allow better folding of memory operations.
9810     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9811         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9812              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9813       unsigned ExtendOp =
9814           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9815       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9816       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9817     }
9818     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9819     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9820     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9821                               Op0, Op1);
9822     return SDValue(Sub.getNode(), 1);
9823   }
9824   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9825 }
9826
9827 /// Convert a comparison if required by the subtarget.
9828 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9829                                                  SelectionDAG &DAG) const {
9830   // If the subtarget does not support the FUCOMI instruction, floating-point
9831   // comparisons have to be converted.
9832   if (Subtarget->hasCMov() ||
9833       Cmp.getOpcode() != X86ISD::CMP ||
9834       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9835       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9836     return Cmp;
9837
9838   // The instruction selector will select an FUCOM instruction instead of
9839   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9840   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9841   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9842   SDLoc dl(Cmp);
9843   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9844   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9845   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9846                             DAG.getConstant(8, MVT::i8));
9847   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9848   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9849 }
9850
9851 static bool isAllOnes(SDValue V) {
9852   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9853   return C && C->isAllOnesValue();
9854 }
9855
9856 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9857 /// if it's possible.
9858 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9859                                      SDLoc dl, SelectionDAG &DAG) const {
9860   SDValue Op0 = And.getOperand(0);
9861   SDValue Op1 = And.getOperand(1);
9862   if (Op0.getOpcode() == ISD::TRUNCATE)
9863     Op0 = Op0.getOperand(0);
9864   if (Op1.getOpcode() == ISD::TRUNCATE)
9865     Op1 = Op1.getOperand(0);
9866
9867   SDValue LHS, RHS;
9868   if (Op1.getOpcode() == ISD::SHL)
9869     std::swap(Op0, Op1);
9870   if (Op0.getOpcode() == ISD::SHL) {
9871     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9872       if (And00C->getZExtValue() == 1) {
9873         // If we looked past a truncate, check that it's only truncating away
9874         // known zeros.
9875         unsigned BitWidth = Op0.getValueSizeInBits();
9876         unsigned AndBitWidth = And.getValueSizeInBits();
9877         if (BitWidth > AndBitWidth) {
9878           APInt Zeros, Ones;
9879           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9880           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9881             return SDValue();
9882         }
9883         LHS = Op1;
9884         RHS = Op0.getOperand(1);
9885       }
9886   } else if (Op1.getOpcode() == ISD::Constant) {
9887     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9888     uint64_t AndRHSVal = AndRHS->getZExtValue();
9889     SDValue AndLHS = Op0;
9890
9891     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9892       LHS = AndLHS.getOperand(0);
9893       RHS = AndLHS.getOperand(1);
9894     }
9895
9896     // Use BT if the immediate can't be encoded in a TEST instruction.
9897     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9898       LHS = AndLHS;
9899       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9900     }
9901   }
9902
9903   if (LHS.getNode()) {
9904     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9905     // instruction.  Since the shift amount is in-range-or-undefined, we know
9906     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9907     // the encoding for the i16 version is larger than the i32 version.
9908     // Also promote i16 to i32 for performance / code size reason.
9909     if (LHS.getValueType() == MVT::i8 ||
9910         LHS.getValueType() == MVT::i16)
9911       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9912
9913     // If the operand types disagree, extend the shift amount to match.  Since
9914     // BT ignores high bits (like shifts) we can use anyextend.
9915     if (LHS.getValueType() != RHS.getValueType())
9916       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9917
9918     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9919     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9920     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9921                        DAG.getConstant(Cond, MVT::i8), BT);
9922   }
9923
9924   return SDValue();
9925 }
9926
9927 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9928 /// mask CMPs.
9929 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9930                               SDValue &Op1) {
9931   unsigned SSECC;
9932   bool Swap = false;
9933
9934   // SSE Condition code mapping:
9935   //  0 - EQ
9936   //  1 - LT
9937   //  2 - LE
9938   //  3 - UNORD
9939   //  4 - NEQ
9940   //  5 - NLT
9941   //  6 - NLE
9942   //  7 - ORD
9943   switch (SetCCOpcode) {
9944   default: llvm_unreachable("Unexpected SETCC condition");
9945   case ISD::SETOEQ:
9946   case ISD::SETEQ:  SSECC = 0; break;
9947   case ISD::SETOGT:
9948   case ISD::SETGT:  Swap = true; // Fallthrough
9949   case ISD::SETLT:
9950   case ISD::SETOLT: SSECC = 1; break;
9951   case ISD::SETOGE:
9952   case ISD::SETGE:  Swap = true; // Fallthrough
9953   case ISD::SETLE:
9954   case ISD::SETOLE: SSECC = 2; break;
9955   case ISD::SETUO:  SSECC = 3; break;
9956   case ISD::SETUNE:
9957   case ISD::SETNE:  SSECC = 4; break;
9958   case ISD::SETULE: Swap = true; // Fallthrough
9959   case ISD::SETUGE: SSECC = 5; break;
9960   case ISD::SETULT: Swap = true; // Fallthrough
9961   case ISD::SETUGT: SSECC = 6; break;
9962   case ISD::SETO:   SSECC = 7; break;
9963   case ISD::SETUEQ:
9964   case ISD::SETONE: SSECC = 8; break;
9965   }
9966   if (Swap)
9967     std::swap(Op0, Op1);
9968
9969   return SSECC;
9970 }
9971
9972 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9973 // ones, and then concatenate the result back.
9974 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9975   MVT VT = Op.getSimpleValueType();
9976
9977   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9978          "Unsupported value type for operation");
9979
9980   unsigned NumElems = VT.getVectorNumElements();
9981   SDLoc dl(Op);
9982   SDValue CC = Op.getOperand(2);
9983
9984   // Extract the LHS vectors
9985   SDValue LHS = Op.getOperand(0);
9986   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9987   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9988
9989   // Extract the RHS vectors
9990   SDValue RHS = Op.getOperand(1);
9991   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9992   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9993
9994   // Issue the operation on the smaller types and concatenate the result back
9995   MVT EltVT = VT.getVectorElementType();
9996   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9997   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9998                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9999                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10000 }
10001
10002 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
10003   SDValue Op0 = Op.getOperand(0);
10004   SDValue Op1 = Op.getOperand(1);
10005   SDValue CC = Op.getOperand(2);
10006   MVT VT = Op.getSimpleValueType();
10007
10008   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10009          Op.getValueType().getScalarType() == MVT::i1 &&
10010          "Cannot set masked compare for this operation");
10011
10012   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10013   SDLoc dl(Op);
10014
10015   bool Unsigned = false;
10016   unsigned SSECC;
10017   switch (SetCCOpcode) {
10018   default: llvm_unreachable("Unexpected SETCC condition");
10019   case ISD::SETNE:  SSECC = 4; break;
10020   case ISD::SETEQ:  SSECC = 0; break;
10021   case ISD::SETUGT: Unsigned = true;
10022   case ISD::SETGT:  SSECC = 6; break; // NLE
10023   case ISD::SETULT: Unsigned = true;
10024   case ISD::SETLT:  SSECC = 1; break;
10025   case ISD::SETUGE: Unsigned = true;
10026   case ISD::SETGE:  SSECC = 5; break; // NLT
10027   case ISD::SETULE: Unsigned = true;
10028   case ISD::SETLE:  SSECC = 2; break;
10029   }
10030   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10031   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10032                      DAG.getConstant(SSECC, MVT::i8));
10033
10034 }
10035
10036 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10037                            SelectionDAG &DAG) {
10038   SDValue Op0 = Op.getOperand(0);
10039   SDValue Op1 = Op.getOperand(1);
10040   SDValue CC = Op.getOperand(2);
10041   MVT VT = Op.getSimpleValueType();
10042   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10043   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10044   SDLoc dl(Op);
10045
10046   if (isFP) {
10047 #ifndef NDEBUG
10048     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10049     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10050 #endif
10051
10052     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10053     unsigned Opc = X86ISD::CMPP;
10054     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10055       assert(VT.getVectorNumElements() <= 16);
10056       Opc = X86ISD::CMPM;
10057     }
10058     // In the two special cases we can't handle, emit two comparisons.
10059     if (SSECC == 8) {
10060       unsigned CC0, CC1;
10061       unsigned CombineOpc;
10062       if (SetCCOpcode == ISD::SETUEQ) {
10063         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10064       } else {
10065         assert(SetCCOpcode == ISD::SETONE);
10066         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10067       }
10068
10069       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10070                                  DAG.getConstant(CC0, MVT::i8));
10071       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10072                                  DAG.getConstant(CC1, MVT::i8));
10073       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10074     }
10075     // Handle all other FP comparisons here.
10076     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10077                        DAG.getConstant(SSECC, MVT::i8));
10078   }
10079
10080   // Break 256-bit integer vector compare into smaller ones.
10081   if (VT.is256BitVector() && !Subtarget->hasInt256())
10082     return Lower256IntVSETCC(Op, DAG);
10083
10084   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10085   EVT OpVT = Op1.getValueType();
10086   if (Subtarget->hasAVX512()) {
10087     if (Op1.getValueType().is512BitVector() ||
10088         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10089       return LowerIntVSETCC_AVX512(Op, DAG);
10090
10091     // In AVX-512 architecture setcc returns mask with i1 elements,
10092     // But there is no compare instruction for i8 and i16 elements.
10093     // We are not talking about 512-bit operands in this case, these
10094     // types are illegal.
10095     if (MaskResult &&
10096         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10097          OpVT.getVectorElementType().getSizeInBits() >= 8))
10098       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10099                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10100   }
10101
10102   // We are handling one of the integer comparisons here.  Since SSE only has
10103   // GT and EQ comparisons for integer, swapping operands and multiple
10104   // operations may be required for some comparisons.
10105   unsigned Opc;
10106   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10107
10108   switch (SetCCOpcode) {
10109   default: llvm_unreachable("Unexpected SETCC condition");
10110   case ISD::SETNE:  Invert = true;
10111   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
10112   case ISD::SETLT:  Swap = true;
10113   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
10114   case ISD::SETGE:  Swap = true;
10115   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10116                     Invert = true; break;
10117   case ISD::SETULT: Swap = true;
10118   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10119                     FlipSigns = true; break;
10120   case ISD::SETUGE: Swap = true;
10121   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10122                     FlipSigns = true; Invert = true; break;
10123   }
10124
10125   // Special case: Use min/max operations for SETULE/SETUGE
10126   MVT VET = VT.getVectorElementType();
10127   bool hasMinMax =
10128        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10129     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10130
10131   if (hasMinMax) {
10132     switch (SetCCOpcode) {
10133     default: break;
10134     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10135     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10136     }
10137
10138     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10139   }
10140
10141   if (Swap)
10142     std::swap(Op0, Op1);
10143
10144   // Check that the operation in question is available (most are plain SSE2,
10145   // but PCMPGTQ and PCMPEQQ have different requirements).
10146   if (VT == MVT::v2i64) {
10147     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10148       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10149
10150       // First cast everything to the right type.
10151       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10152       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10153
10154       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10155       // bits of the inputs before performing those operations. The lower
10156       // compare is always unsigned.
10157       SDValue SB;
10158       if (FlipSigns) {
10159         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10160       } else {
10161         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10162         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10163         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10164                          Sign, Zero, Sign, Zero);
10165       }
10166       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10167       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10168
10169       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10170       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10171       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10172
10173       // Create masks for only the low parts/high parts of the 64 bit integers.
10174       static const int MaskHi[] = { 1, 1, 3, 3 };
10175       static const int MaskLo[] = { 0, 0, 2, 2 };
10176       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10177       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10178       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10179
10180       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10181       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10182
10183       if (Invert)
10184         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10185
10186       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10187     }
10188
10189     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10190       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10191       // pcmpeqd + pshufd + pand.
10192       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10193
10194       // First cast everything to the right type.
10195       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10196       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10197
10198       // Do the compare.
10199       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10200
10201       // Make sure the lower and upper halves are both all-ones.
10202       static const int Mask[] = { 1, 0, 3, 2 };
10203       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10204       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10205
10206       if (Invert)
10207         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10208
10209       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10210     }
10211   }
10212
10213   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10214   // bits of the inputs before performing those operations.
10215   if (FlipSigns) {
10216     EVT EltVT = VT.getVectorElementType();
10217     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10218     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10219     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10220   }
10221
10222   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10223
10224   // If the logical-not of the result is required, perform that now.
10225   if (Invert)
10226     Result = DAG.getNOT(dl, Result, VT);
10227
10228   if (MinMax)
10229     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10230
10231   return Result;
10232 }
10233
10234 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10235
10236   MVT VT = Op.getSimpleValueType();
10237
10238   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10239
10240   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10241          && "SetCC type must be 8-bit or 1-bit integer");
10242   SDValue Op0 = Op.getOperand(0);
10243   SDValue Op1 = Op.getOperand(1);
10244   SDLoc dl(Op);
10245   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10246
10247   // Optimize to BT if possible.
10248   // Lower (X & (1 << N)) == 0 to BT(X, N).
10249   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10250   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10251   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10252       Op1.getOpcode() == ISD::Constant &&
10253       cast<ConstantSDNode>(Op1)->isNullValue() &&
10254       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10255     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10256     if (NewSetCC.getNode())
10257       return NewSetCC;
10258   }
10259
10260   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10261   // these.
10262   if (Op1.getOpcode() == ISD::Constant &&
10263       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10264        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10265       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10266
10267     // If the input is a setcc, then reuse the input setcc or use a new one with
10268     // the inverted condition.
10269     if (Op0.getOpcode() == X86ISD::SETCC) {
10270       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10271       bool Invert = (CC == ISD::SETNE) ^
10272         cast<ConstantSDNode>(Op1)->isNullValue();
10273       if (!Invert)
10274         return Op0;
10275
10276       CCode = X86::GetOppositeBranchCondition(CCode);
10277       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10278                                   DAG.getConstant(CCode, MVT::i8),
10279                                   Op0.getOperand(1));
10280       if (VT == MVT::i1)
10281         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10282       return SetCC;
10283     }
10284   }
10285
10286   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10287   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10288   if (X86CC == X86::COND_INVALID)
10289     return SDValue();
10290
10291   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10292   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10293   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10294                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10295   if (VT == MVT::i1)
10296     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10297   return SetCC;
10298 }
10299
10300 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10301 static bool isX86LogicalCmp(SDValue Op) {
10302   unsigned Opc = Op.getNode()->getOpcode();
10303   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10304       Opc == X86ISD::SAHF)
10305     return true;
10306   if (Op.getResNo() == 1 &&
10307       (Opc == X86ISD::ADD ||
10308        Opc == X86ISD::SUB ||
10309        Opc == X86ISD::ADC ||
10310        Opc == X86ISD::SBB ||
10311        Opc == X86ISD::SMUL ||
10312        Opc == X86ISD::UMUL ||
10313        Opc == X86ISD::INC ||
10314        Opc == X86ISD::DEC ||
10315        Opc == X86ISD::OR ||
10316        Opc == X86ISD::XOR ||
10317        Opc == X86ISD::AND))
10318     return true;
10319
10320   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10321     return true;
10322
10323   return false;
10324 }
10325
10326 static bool isZero(SDValue V) {
10327   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10328   return C && C->isNullValue();
10329 }
10330
10331 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10332   if (V.getOpcode() != ISD::TRUNCATE)
10333     return false;
10334
10335   SDValue VOp0 = V.getOperand(0);
10336   unsigned InBits = VOp0.getValueSizeInBits();
10337   unsigned Bits = V.getValueSizeInBits();
10338   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10339 }
10340
10341 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10342   bool addTest = true;
10343   SDValue Cond  = Op.getOperand(0);
10344   SDValue Op1 = Op.getOperand(1);
10345   SDValue Op2 = Op.getOperand(2);
10346   SDLoc DL(Op);
10347   EVT VT = Op1.getValueType();
10348   SDValue CC;
10349
10350   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10351   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10352   // sequence later on.
10353   if (Cond.getOpcode() == ISD::SETCC &&
10354       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10355        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10356       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10357     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10358     int SSECC = translateX86FSETCC(
10359         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10360
10361     if (SSECC != 8) {
10362       if (Subtarget->hasAVX512()) {
10363         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10364                                   DAG.getConstant(SSECC, MVT::i8));
10365         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10366       }
10367       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10368                                 DAG.getConstant(SSECC, MVT::i8));
10369       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10370       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10371       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10372     }
10373   }
10374
10375   if (Cond.getOpcode() == ISD::SETCC) {
10376     SDValue NewCond = LowerSETCC(Cond, DAG);
10377     if (NewCond.getNode())
10378       Cond = NewCond;
10379   }
10380
10381   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10382   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10383   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10384   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10385   if (Cond.getOpcode() == X86ISD::SETCC &&
10386       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10387       isZero(Cond.getOperand(1).getOperand(1))) {
10388     SDValue Cmp = Cond.getOperand(1);
10389
10390     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10391
10392     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10393         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10394       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10395
10396       SDValue CmpOp0 = Cmp.getOperand(0);
10397       // Apply further optimizations for special cases
10398       // (select (x != 0), -1, 0) -> neg & sbb
10399       // (select (x == 0), 0, -1) -> neg & sbb
10400       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10401         if (YC->isNullValue() &&
10402             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10403           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10404           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10405                                     DAG.getConstant(0, CmpOp0.getValueType()),
10406                                     CmpOp0);
10407           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10408                                     DAG.getConstant(X86::COND_B, MVT::i8),
10409                                     SDValue(Neg.getNode(), 1));
10410           return Res;
10411         }
10412
10413       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10414                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10415       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10416
10417       SDValue Res =   // Res = 0 or -1.
10418         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10419                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10420
10421       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10422         Res = DAG.getNOT(DL, Res, Res.getValueType());
10423
10424       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10425       if (N2C == 0 || !N2C->isNullValue())
10426         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10427       return Res;
10428     }
10429   }
10430
10431   // Look past (and (setcc_carry (cmp ...)), 1).
10432   if (Cond.getOpcode() == ISD::AND &&
10433       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10434     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10435     if (C && C->getAPIntValue() == 1)
10436       Cond = Cond.getOperand(0);
10437   }
10438
10439   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10440   // setting operand in place of the X86ISD::SETCC.
10441   unsigned CondOpcode = Cond.getOpcode();
10442   if (CondOpcode == X86ISD::SETCC ||
10443       CondOpcode == X86ISD::SETCC_CARRY) {
10444     CC = Cond.getOperand(0);
10445
10446     SDValue Cmp = Cond.getOperand(1);
10447     unsigned Opc = Cmp.getOpcode();
10448     MVT VT = Op.getSimpleValueType();
10449
10450     bool IllegalFPCMov = false;
10451     if (VT.isFloatingPoint() && !VT.isVector() &&
10452         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10453       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10454
10455     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10456         Opc == X86ISD::BT) { // FIXME
10457       Cond = Cmp;
10458       addTest = false;
10459     }
10460   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10461              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10462              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10463               Cond.getOperand(0).getValueType() != MVT::i8)) {
10464     SDValue LHS = Cond.getOperand(0);
10465     SDValue RHS = Cond.getOperand(1);
10466     unsigned X86Opcode;
10467     unsigned X86Cond;
10468     SDVTList VTs;
10469     switch (CondOpcode) {
10470     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10471     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10472     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10473     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10474     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10475     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10476     default: llvm_unreachable("unexpected overflowing operator");
10477     }
10478     if (CondOpcode == ISD::UMULO)
10479       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10480                           MVT::i32);
10481     else
10482       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10483
10484     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10485
10486     if (CondOpcode == ISD::UMULO)
10487       Cond = X86Op.getValue(2);
10488     else
10489       Cond = X86Op.getValue(1);
10490
10491     CC = DAG.getConstant(X86Cond, MVT::i8);
10492     addTest = false;
10493   }
10494
10495   if (addTest) {
10496     // Look pass the truncate if the high bits are known zero.
10497     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10498         Cond = Cond.getOperand(0);
10499
10500     // We know the result of AND is compared against zero. Try to match
10501     // it to BT.
10502     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10503       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10504       if (NewSetCC.getNode()) {
10505         CC = NewSetCC.getOperand(0);
10506         Cond = NewSetCC.getOperand(1);
10507         addTest = false;
10508       }
10509     }
10510   }
10511
10512   if (addTest) {
10513     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10514     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10515   }
10516
10517   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10518   // a <  b ?  0 : -1 -> RES = setcc_carry
10519   // a >= b ? -1 :  0 -> RES = setcc_carry
10520   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10521   if (Cond.getOpcode() == X86ISD::SUB) {
10522     Cond = ConvertCmpIfNecessary(Cond, DAG);
10523     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10524
10525     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10526         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10527       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10528                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10529       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10530         return DAG.getNOT(DL, Res, Res.getValueType());
10531       return Res;
10532     }
10533   }
10534
10535   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10536   // widen the cmov and push the truncate through. This avoids introducing a new
10537   // branch during isel and doesn't add any extensions.
10538   if (Op.getValueType() == MVT::i8 &&
10539       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10540     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10541     if (T1.getValueType() == T2.getValueType() &&
10542         // Blacklist CopyFromReg to avoid partial register stalls.
10543         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10544       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10545       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10546       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10547     }
10548   }
10549
10550   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10551   // condition is true.
10552   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10553   SDValue Ops[] = { Op2, Op1, CC, Cond };
10554   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10555 }
10556
10557 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10558   MVT VT = Op->getSimpleValueType(0);
10559   SDValue In = Op->getOperand(0);
10560   MVT InVT = In.getSimpleValueType();
10561   SDLoc dl(Op);
10562
10563   unsigned int NumElts = VT.getVectorNumElements();
10564   if (NumElts != 8 && NumElts != 16)
10565     return SDValue();
10566
10567   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10568     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10569
10570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10571   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10572
10573   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10574   Constant *C = ConstantInt::get(*DAG.getContext(),
10575     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10576
10577   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10578   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10579   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10580                           MachinePointerInfo::getConstantPool(),
10581                           false, false, false, Alignment);
10582   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10583   if (VT.is512BitVector())
10584     return Brcst;
10585   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10586 }
10587
10588 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10589                                 SelectionDAG &DAG) {
10590   MVT VT = Op->getSimpleValueType(0);
10591   SDValue In = Op->getOperand(0);
10592   MVT InVT = In.getSimpleValueType();
10593   SDLoc dl(Op);
10594
10595   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10596     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10597
10598   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10599       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10600       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10601     return SDValue();
10602
10603   if (Subtarget->hasInt256())
10604     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10605
10606   // Optimize vectors in AVX mode
10607   // Sign extend  v8i16 to v8i32 and
10608   //              v4i32 to v4i64
10609   //
10610   // Divide input vector into two parts
10611   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10612   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10613   // concat the vectors to original VT
10614
10615   unsigned NumElems = InVT.getVectorNumElements();
10616   SDValue Undef = DAG.getUNDEF(InVT);
10617
10618   SmallVector<int,8> ShufMask1(NumElems, -1);
10619   for (unsigned i = 0; i != NumElems/2; ++i)
10620     ShufMask1[i] = i;
10621
10622   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10623
10624   SmallVector<int,8> ShufMask2(NumElems, -1);
10625   for (unsigned i = 0; i != NumElems/2; ++i)
10626     ShufMask2[i] = i + NumElems/2;
10627
10628   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10629
10630   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10631                                 VT.getVectorNumElements()/2);
10632
10633   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10634   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10635
10636   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10637 }
10638
10639 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10640 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10641 // from the AND / OR.
10642 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10643   Opc = Op.getOpcode();
10644   if (Opc != ISD::OR && Opc != ISD::AND)
10645     return false;
10646   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10647           Op.getOperand(0).hasOneUse() &&
10648           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10649           Op.getOperand(1).hasOneUse());
10650 }
10651
10652 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10653 // 1 and that the SETCC node has a single use.
10654 static bool isXor1OfSetCC(SDValue Op) {
10655   if (Op.getOpcode() != ISD::XOR)
10656     return false;
10657   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10658   if (N1C && N1C->getAPIntValue() == 1) {
10659     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10660       Op.getOperand(0).hasOneUse();
10661   }
10662   return false;
10663 }
10664
10665 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10666   bool addTest = true;
10667   SDValue Chain = Op.getOperand(0);
10668   SDValue Cond  = Op.getOperand(1);
10669   SDValue Dest  = Op.getOperand(2);
10670   SDLoc dl(Op);
10671   SDValue CC;
10672   bool Inverted = false;
10673
10674   if (Cond.getOpcode() == ISD::SETCC) {
10675     // Check for setcc([su]{add,sub,mul}o == 0).
10676     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10677         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10678         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10679         Cond.getOperand(0).getResNo() == 1 &&
10680         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10681          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10682          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10683          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10684          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10685          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10686       Inverted = true;
10687       Cond = Cond.getOperand(0);
10688     } else {
10689       SDValue NewCond = LowerSETCC(Cond, DAG);
10690       if (NewCond.getNode())
10691         Cond = NewCond;
10692     }
10693   }
10694 #if 0
10695   // FIXME: LowerXALUO doesn't handle these!!
10696   else if (Cond.getOpcode() == X86ISD::ADD  ||
10697            Cond.getOpcode() == X86ISD::SUB  ||
10698            Cond.getOpcode() == X86ISD::SMUL ||
10699            Cond.getOpcode() == X86ISD::UMUL)
10700     Cond = LowerXALUO(Cond, DAG);
10701 #endif
10702
10703   // Look pass (and (setcc_carry (cmp ...)), 1).
10704   if (Cond.getOpcode() == ISD::AND &&
10705       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10706     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10707     if (C && C->getAPIntValue() == 1)
10708       Cond = Cond.getOperand(0);
10709   }
10710
10711   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10712   // setting operand in place of the X86ISD::SETCC.
10713   unsigned CondOpcode = Cond.getOpcode();
10714   if (CondOpcode == X86ISD::SETCC ||
10715       CondOpcode == X86ISD::SETCC_CARRY) {
10716     CC = Cond.getOperand(0);
10717
10718     SDValue Cmp = Cond.getOperand(1);
10719     unsigned Opc = Cmp.getOpcode();
10720     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10721     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10722       Cond = Cmp;
10723       addTest = false;
10724     } else {
10725       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10726       default: break;
10727       case X86::COND_O:
10728       case X86::COND_B:
10729         // These can only come from an arithmetic instruction with overflow,
10730         // e.g. SADDO, UADDO.
10731         Cond = Cond.getNode()->getOperand(1);
10732         addTest = false;
10733         break;
10734       }
10735     }
10736   }
10737   CondOpcode = Cond.getOpcode();
10738   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10739       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10740       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10741        Cond.getOperand(0).getValueType() != MVT::i8)) {
10742     SDValue LHS = Cond.getOperand(0);
10743     SDValue RHS = Cond.getOperand(1);
10744     unsigned X86Opcode;
10745     unsigned X86Cond;
10746     SDVTList VTs;
10747     // Keep this in sync with LowerXALUO, otherwise we might create redundant
10748     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10749     // X86ISD::INC).
10750     switch (CondOpcode) {
10751     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10752     case ISD::SADDO:
10753       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10754         if (C->isOne()) {
10755           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10756           break;
10757         }
10758       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10759     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10760     case ISD::SSUBO:
10761       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10762         if (C->isOne()) {
10763           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10764           break;
10765         }
10766       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10767     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10768     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10769     default: llvm_unreachable("unexpected overflowing operator");
10770     }
10771     if (Inverted)
10772       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10773     if (CondOpcode == ISD::UMULO)
10774       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10775                           MVT::i32);
10776     else
10777       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10778
10779     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10780
10781     if (CondOpcode == ISD::UMULO)
10782       Cond = X86Op.getValue(2);
10783     else
10784       Cond = X86Op.getValue(1);
10785
10786     CC = DAG.getConstant(X86Cond, MVT::i8);
10787     addTest = false;
10788   } else {
10789     unsigned CondOpc;
10790     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10791       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10792       if (CondOpc == ISD::OR) {
10793         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10794         // two branches instead of an explicit OR instruction with a
10795         // separate test.
10796         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10797             isX86LogicalCmp(Cmp)) {
10798           CC = Cond.getOperand(0).getOperand(0);
10799           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10800                               Chain, Dest, CC, Cmp);
10801           CC = Cond.getOperand(1).getOperand(0);
10802           Cond = Cmp;
10803           addTest = false;
10804         }
10805       } else { // ISD::AND
10806         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10807         // two branches instead of an explicit AND instruction with a
10808         // separate test. However, we only do this if this block doesn't
10809         // have a fall-through edge, because this requires an explicit
10810         // jmp when the condition is false.
10811         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10812             isX86LogicalCmp(Cmp) &&
10813             Op.getNode()->hasOneUse()) {
10814           X86::CondCode CCode =
10815             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10816           CCode = X86::GetOppositeBranchCondition(CCode);
10817           CC = DAG.getConstant(CCode, MVT::i8);
10818           SDNode *User = *Op.getNode()->use_begin();
10819           // Look for an unconditional branch following this conditional branch.
10820           // We need this because we need to reverse the successors in order
10821           // to implement FCMP_OEQ.
10822           if (User->getOpcode() == ISD::BR) {
10823             SDValue FalseBB = User->getOperand(1);
10824             SDNode *NewBR =
10825               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10826             assert(NewBR == User);
10827             (void)NewBR;
10828             Dest = FalseBB;
10829
10830             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10831                                 Chain, Dest, CC, Cmp);
10832             X86::CondCode CCode =
10833               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10834             CCode = X86::GetOppositeBranchCondition(CCode);
10835             CC = DAG.getConstant(CCode, MVT::i8);
10836             Cond = Cmp;
10837             addTest = false;
10838           }
10839         }
10840       }
10841     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10842       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10843       // It should be transformed during dag combiner except when the condition
10844       // is set by a arithmetics with overflow node.
10845       X86::CondCode CCode =
10846         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10847       CCode = X86::GetOppositeBranchCondition(CCode);
10848       CC = DAG.getConstant(CCode, MVT::i8);
10849       Cond = Cond.getOperand(0).getOperand(1);
10850       addTest = false;
10851     } else if (Cond.getOpcode() == ISD::SETCC &&
10852                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10853       // For FCMP_OEQ, we can emit
10854       // two branches instead of an explicit AND instruction with a
10855       // separate test. However, we only do this if this block doesn't
10856       // have a fall-through edge, because this requires an explicit
10857       // jmp when the condition is false.
10858       if (Op.getNode()->hasOneUse()) {
10859         SDNode *User = *Op.getNode()->use_begin();
10860         // Look for an unconditional branch following this conditional branch.
10861         // We need this because we need to reverse the successors in order
10862         // to implement FCMP_OEQ.
10863         if (User->getOpcode() == ISD::BR) {
10864           SDValue FalseBB = User->getOperand(1);
10865           SDNode *NewBR =
10866             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10867           assert(NewBR == User);
10868           (void)NewBR;
10869           Dest = FalseBB;
10870
10871           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10872                                     Cond.getOperand(0), Cond.getOperand(1));
10873           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10874           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10875           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10876                               Chain, Dest, CC, Cmp);
10877           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10878           Cond = Cmp;
10879           addTest = false;
10880         }
10881       }
10882     } else if (Cond.getOpcode() == ISD::SETCC &&
10883                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10884       // For FCMP_UNE, we can emit
10885       // two branches instead of an explicit AND instruction with a
10886       // separate test. However, we only do this if this block doesn't
10887       // have a fall-through edge, because this requires an explicit
10888       // jmp when the condition is false.
10889       if (Op.getNode()->hasOneUse()) {
10890         SDNode *User = *Op.getNode()->use_begin();
10891         // Look for an unconditional branch following this conditional branch.
10892         // We need this because we need to reverse the successors in order
10893         // to implement FCMP_UNE.
10894         if (User->getOpcode() == ISD::BR) {
10895           SDValue FalseBB = User->getOperand(1);
10896           SDNode *NewBR =
10897             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10898           assert(NewBR == User);
10899           (void)NewBR;
10900
10901           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10902                                     Cond.getOperand(0), Cond.getOperand(1));
10903           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10904           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10905           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10906                               Chain, Dest, CC, Cmp);
10907           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10908           Cond = Cmp;
10909           addTest = false;
10910           Dest = FalseBB;
10911         }
10912       }
10913     }
10914   }
10915
10916   if (addTest) {
10917     // Look pass the truncate if the high bits are known zero.
10918     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10919         Cond = Cond.getOperand(0);
10920
10921     // We know the result of AND is compared against zero. Try to match
10922     // it to BT.
10923     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10924       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10925       if (NewSetCC.getNode()) {
10926         CC = NewSetCC.getOperand(0);
10927         Cond = NewSetCC.getOperand(1);
10928         addTest = false;
10929       }
10930     }
10931   }
10932
10933   if (addTest) {
10934     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10935     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10936   }
10937   Cond = ConvertCmpIfNecessary(Cond, DAG);
10938   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10939                      Chain, Dest, CC, Cond);
10940 }
10941
10942 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10943 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10944 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10945 // that the guard pages used by the OS virtual memory manager are allocated in
10946 // correct sequence.
10947 SDValue
10948 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10949                                            SelectionDAG &DAG) const {
10950   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10951           getTargetMachine().Options.EnableSegmentedStacks) &&
10952          "This should be used only on Windows targets or when segmented stacks "
10953          "are being used");
10954   assert(!Subtarget->isTargetMacho() && "Not implemented");
10955   SDLoc dl(Op);
10956
10957   // Get the inputs.
10958   SDValue Chain = Op.getOperand(0);
10959   SDValue Size  = Op.getOperand(1);
10960   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10961   EVT VT = Op.getNode()->getValueType(0);
10962
10963   bool Is64Bit = Subtarget->is64Bit();
10964   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10965
10966   if (getTargetMachine().Options.EnableSegmentedStacks) {
10967     MachineFunction &MF = DAG.getMachineFunction();
10968     MachineRegisterInfo &MRI = MF.getRegInfo();
10969
10970     if (Is64Bit) {
10971       // The 64 bit implementation of segmented stacks needs to clobber both r10
10972       // r11. This makes it impossible to use it along with nested parameters.
10973       const Function *F = MF.getFunction();
10974
10975       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10976            I != E; ++I)
10977         if (I->hasNestAttr())
10978           report_fatal_error("Cannot use segmented stacks with functions that "
10979                              "have nested arguments.");
10980     }
10981
10982     const TargetRegisterClass *AddrRegClass =
10983       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10984     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10985     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10986     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10987                                 DAG.getRegister(Vreg, SPTy));
10988     SDValue Ops1[2] = { Value, Chain };
10989     return DAG.getMergeValues(Ops1, 2, dl);
10990   } else {
10991     SDValue Flag;
10992     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10993
10994     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10995     Flag = Chain.getValue(1);
10996     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10997
10998     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10999
11000     const X86RegisterInfo *RegInfo =
11001       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11002     unsigned SPReg = RegInfo->getStackRegister();
11003     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11004     Chain = SP.getValue(1);
11005
11006     if (Align) {
11007       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11008                        DAG.getConstant(-(uint64_t)Align, VT));
11009       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11010     }
11011
11012     SDValue Ops1[2] = { SP, Chain };
11013     return DAG.getMergeValues(Ops1, 2, dl);
11014   }
11015 }
11016
11017 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11018   MachineFunction &MF = DAG.getMachineFunction();
11019   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11020
11021   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11022   SDLoc DL(Op);
11023
11024   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11025     // vastart just stores the address of the VarArgsFrameIndex slot into the
11026     // memory location argument.
11027     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11028                                    getPointerTy());
11029     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11030                         MachinePointerInfo(SV), false, false, 0);
11031   }
11032
11033   // __va_list_tag:
11034   //   gp_offset         (0 - 6 * 8)
11035   //   fp_offset         (48 - 48 + 8 * 16)
11036   //   overflow_arg_area (point to parameters coming in memory).
11037   //   reg_save_area
11038   SmallVector<SDValue, 8> MemOps;
11039   SDValue FIN = Op.getOperand(1);
11040   // Store gp_offset
11041   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11042                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11043                                                MVT::i32),
11044                                FIN, MachinePointerInfo(SV), false, false, 0);
11045   MemOps.push_back(Store);
11046
11047   // Store fp_offset
11048   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11049                     FIN, DAG.getIntPtrConstant(4));
11050   Store = DAG.getStore(Op.getOperand(0), DL,
11051                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11052                                        MVT::i32),
11053                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11054   MemOps.push_back(Store);
11055
11056   // Store ptr to overflow_arg_area
11057   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11058                     FIN, DAG.getIntPtrConstant(4));
11059   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11060                                     getPointerTy());
11061   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11062                        MachinePointerInfo(SV, 8),
11063                        false, false, 0);
11064   MemOps.push_back(Store);
11065
11066   // Store ptr to reg_save_area.
11067   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11068                     FIN, DAG.getIntPtrConstant(8));
11069   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11070                                     getPointerTy());
11071   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11072                        MachinePointerInfo(SV, 16), false, false, 0);
11073   MemOps.push_back(Store);
11074   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11075                      &MemOps[0], MemOps.size());
11076 }
11077
11078 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11079   assert(Subtarget->is64Bit() &&
11080          "LowerVAARG only handles 64-bit va_arg!");
11081   assert((Subtarget->isTargetLinux() ||
11082           Subtarget->isTargetDarwin()) &&
11083           "Unhandled target in LowerVAARG");
11084   assert(Op.getNode()->getNumOperands() == 4);
11085   SDValue Chain = Op.getOperand(0);
11086   SDValue SrcPtr = Op.getOperand(1);
11087   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11088   unsigned Align = Op.getConstantOperandVal(3);
11089   SDLoc dl(Op);
11090
11091   EVT ArgVT = Op.getNode()->getValueType(0);
11092   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11093   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11094   uint8_t ArgMode;
11095
11096   // Decide which area this value should be read from.
11097   // TODO: Implement the AMD64 ABI in its entirety. This simple
11098   // selection mechanism works only for the basic types.
11099   if (ArgVT == MVT::f80) {
11100     llvm_unreachable("va_arg for f80 not yet implemented");
11101   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11102     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11103   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11104     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11105   } else {
11106     llvm_unreachable("Unhandled argument type in LowerVAARG");
11107   }
11108
11109   if (ArgMode == 2) {
11110     // Sanity Check: Make sure using fp_offset makes sense.
11111     assert(!getTargetMachine().Options.UseSoftFloat &&
11112            !(DAG.getMachineFunction()
11113                 .getFunction()->getAttributes()
11114                 .hasAttribute(AttributeSet::FunctionIndex,
11115                               Attribute::NoImplicitFloat)) &&
11116            Subtarget->hasSSE1());
11117   }
11118
11119   // Insert VAARG_64 node into the DAG
11120   // VAARG_64 returns two values: Variable Argument Address, Chain
11121   SmallVector<SDValue, 11> InstOps;
11122   InstOps.push_back(Chain);
11123   InstOps.push_back(SrcPtr);
11124   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11125   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11126   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11127   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11128   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11129                                           VTs, &InstOps[0], InstOps.size(),
11130                                           MVT::i64,
11131                                           MachinePointerInfo(SV),
11132                                           /*Align=*/0,
11133                                           /*Volatile=*/false,
11134                                           /*ReadMem=*/true,
11135                                           /*WriteMem=*/true);
11136   Chain = VAARG.getValue(1);
11137
11138   // Load the next argument and return it
11139   return DAG.getLoad(ArgVT, dl,
11140                      Chain,
11141                      VAARG,
11142                      MachinePointerInfo(),
11143                      false, false, false, 0);
11144 }
11145
11146 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11147                            SelectionDAG &DAG) {
11148   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11149   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11150   SDValue Chain = Op.getOperand(0);
11151   SDValue DstPtr = Op.getOperand(1);
11152   SDValue SrcPtr = Op.getOperand(2);
11153   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11154   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11155   SDLoc DL(Op);
11156
11157   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11158                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11159                        false,
11160                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11161 }
11162
11163 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11164 // amount is a constant. Takes immediate version of shift as input.
11165 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11166                                           SDValue SrcOp, uint64_t ShiftAmt,
11167                                           SelectionDAG &DAG) {
11168   MVT ElementType = VT.getVectorElementType();
11169
11170   // Check for ShiftAmt >= element width
11171   if (ShiftAmt >= ElementType.getSizeInBits()) {
11172     if (Opc == X86ISD::VSRAI)
11173       ShiftAmt = ElementType.getSizeInBits() - 1;
11174     else
11175       return DAG.getConstant(0, VT);
11176   }
11177
11178   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11179          && "Unknown target vector shift-by-constant node");
11180
11181   // Fold this packed vector shift into a build vector if SrcOp is a
11182   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11183   if (VT == SrcOp.getSimpleValueType() &&
11184       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11185     SmallVector<SDValue, 8> Elts;
11186     unsigned NumElts = SrcOp->getNumOperands();
11187     ConstantSDNode *ND;
11188
11189     switch(Opc) {
11190     default: llvm_unreachable(0);
11191     case X86ISD::VSHLI:
11192       for (unsigned i=0; i!=NumElts; ++i) {
11193         SDValue CurrentOp = SrcOp->getOperand(i);
11194         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11195           Elts.push_back(CurrentOp);
11196           continue;
11197         }
11198         ND = cast<ConstantSDNode>(CurrentOp);
11199         const APInt &C = ND->getAPIntValue();
11200         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11201       }
11202       break;
11203     case X86ISD::VSRLI:
11204       for (unsigned i=0; i!=NumElts; ++i) {
11205         SDValue CurrentOp = SrcOp->getOperand(i);
11206         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11207           Elts.push_back(CurrentOp);
11208           continue;
11209         }
11210         ND = cast<ConstantSDNode>(CurrentOp);
11211         const APInt &C = ND->getAPIntValue();
11212         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11213       }
11214       break;
11215     case X86ISD::VSRAI:
11216       for (unsigned i=0; i!=NumElts; ++i) {
11217         SDValue CurrentOp = SrcOp->getOperand(i);
11218         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11219           Elts.push_back(CurrentOp);
11220           continue;
11221         }
11222         ND = cast<ConstantSDNode>(CurrentOp);
11223         const APInt &C = ND->getAPIntValue();
11224         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11225       }
11226       break;
11227     }
11228
11229     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11230   }
11231
11232   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11233 }
11234
11235 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11236 // may or may not be a constant. Takes immediate version of shift as input.
11237 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11238                                    SDValue SrcOp, SDValue ShAmt,
11239                                    SelectionDAG &DAG) {
11240   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11241
11242   // Catch shift-by-constant.
11243   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11244     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11245                                       CShAmt->getZExtValue(), DAG);
11246
11247   // Change opcode to non-immediate version
11248   switch (Opc) {
11249     default: llvm_unreachable("Unknown target vector shift node");
11250     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11251     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11252     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11253   }
11254
11255   // Need to build a vector containing shift amount
11256   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11257   SDValue ShOps[4];
11258   ShOps[0] = ShAmt;
11259   ShOps[1] = DAG.getConstant(0, MVT::i32);
11260   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11261   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11262
11263   // The return type has to be a 128-bit type with the same element
11264   // type as the input type.
11265   MVT EltVT = VT.getVectorElementType();
11266   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11267
11268   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11269   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11270 }
11271
11272 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11273   SDLoc dl(Op);
11274   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11275   switch (IntNo) {
11276   default: return SDValue();    // Don't custom lower most intrinsics.
11277   // Comparison intrinsics.
11278   case Intrinsic::x86_sse_comieq_ss:
11279   case Intrinsic::x86_sse_comilt_ss:
11280   case Intrinsic::x86_sse_comile_ss:
11281   case Intrinsic::x86_sse_comigt_ss:
11282   case Intrinsic::x86_sse_comige_ss:
11283   case Intrinsic::x86_sse_comineq_ss:
11284   case Intrinsic::x86_sse_ucomieq_ss:
11285   case Intrinsic::x86_sse_ucomilt_ss:
11286   case Intrinsic::x86_sse_ucomile_ss:
11287   case Intrinsic::x86_sse_ucomigt_ss:
11288   case Intrinsic::x86_sse_ucomige_ss:
11289   case Intrinsic::x86_sse_ucomineq_ss:
11290   case Intrinsic::x86_sse2_comieq_sd:
11291   case Intrinsic::x86_sse2_comilt_sd:
11292   case Intrinsic::x86_sse2_comile_sd:
11293   case Intrinsic::x86_sse2_comigt_sd:
11294   case Intrinsic::x86_sse2_comige_sd:
11295   case Intrinsic::x86_sse2_comineq_sd:
11296   case Intrinsic::x86_sse2_ucomieq_sd:
11297   case Intrinsic::x86_sse2_ucomilt_sd:
11298   case Intrinsic::x86_sse2_ucomile_sd:
11299   case Intrinsic::x86_sse2_ucomigt_sd:
11300   case Intrinsic::x86_sse2_ucomige_sd:
11301   case Intrinsic::x86_sse2_ucomineq_sd: {
11302     unsigned Opc;
11303     ISD::CondCode CC;
11304     switch (IntNo) {
11305     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11306     case Intrinsic::x86_sse_comieq_ss:
11307     case Intrinsic::x86_sse2_comieq_sd:
11308       Opc = X86ISD::COMI;
11309       CC = ISD::SETEQ;
11310       break;
11311     case Intrinsic::x86_sse_comilt_ss:
11312     case Intrinsic::x86_sse2_comilt_sd:
11313       Opc = X86ISD::COMI;
11314       CC = ISD::SETLT;
11315       break;
11316     case Intrinsic::x86_sse_comile_ss:
11317     case Intrinsic::x86_sse2_comile_sd:
11318       Opc = X86ISD::COMI;
11319       CC = ISD::SETLE;
11320       break;
11321     case Intrinsic::x86_sse_comigt_ss:
11322     case Intrinsic::x86_sse2_comigt_sd:
11323       Opc = X86ISD::COMI;
11324       CC = ISD::SETGT;
11325       break;
11326     case Intrinsic::x86_sse_comige_ss:
11327     case Intrinsic::x86_sse2_comige_sd:
11328       Opc = X86ISD::COMI;
11329       CC = ISD::SETGE;
11330       break;
11331     case Intrinsic::x86_sse_comineq_ss:
11332     case Intrinsic::x86_sse2_comineq_sd:
11333       Opc = X86ISD::COMI;
11334       CC = ISD::SETNE;
11335       break;
11336     case Intrinsic::x86_sse_ucomieq_ss:
11337     case Intrinsic::x86_sse2_ucomieq_sd:
11338       Opc = X86ISD::UCOMI;
11339       CC = ISD::SETEQ;
11340       break;
11341     case Intrinsic::x86_sse_ucomilt_ss:
11342     case Intrinsic::x86_sse2_ucomilt_sd:
11343       Opc = X86ISD::UCOMI;
11344       CC = ISD::SETLT;
11345       break;
11346     case Intrinsic::x86_sse_ucomile_ss:
11347     case Intrinsic::x86_sse2_ucomile_sd:
11348       Opc = X86ISD::UCOMI;
11349       CC = ISD::SETLE;
11350       break;
11351     case Intrinsic::x86_sse_ucomigt_ss:
11352     case Intrinsic::x86_sse2_ucomigt_sd:
11353       Opc = X86ISD::UCOMI;
11354       CC = ISD::SETGT;
11355       break;
11356     case Intrinsic::x86_sse_ucomige_ss:
11357     case Intrinsic::x86_sse2_ucomige_sd:
11358       Opc = X86ISD::UCOMI;
11359       CC = ISD::SETGE;
11360       break;
11361     case Intrinsic::x86_sse_ucomineq_ss:
11362     case Intrinsic::x86_sse2_ucomineq_sd:
11363       Opc = X86ISD::UCOMI;
11364       CC = ISD::SETNE;
11365       break;
11366     }
11367
11368     SDValue LHS = Op.getOperand(1);
11369     SDValue RHS = Op.getOperand(2);
11370     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11371     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11372     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11373     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11374                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11375     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11376   }
11377
11378   // Arithmetic intrinsics.
11379   case Intrinsic::x86_sse2_pmulu_dq:
11380   case Intrinsic::x86_avx2_pmulu_dq:
11381     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11382                        Op.getOperand(1), Op.getOperand(2));
11383
11384   // SSE2/AVX2 sub with unsigned saturation intrinsics
11385   case Intrinsic::x86_sse2_psubus_b:
11386   case Intrinsic::x86_sse2_psubus_w:
11387   case Intrinsic::x86_avx2_psubus_b:
11388   case Intrinsic::x86_avx2_psubus_w:
11389     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11390                        Op.getOperand(1), Op.getOperand(2));
11391
11392   // SSE3/AVX horizontal add/sub intrinsics
11393   case Intrinsic::x86_sse3_hadd_ps:
11394   case Intrinsic::x86_sse3_hadd_pd:
11395   case Intrinsic::x86_avx_hadd_ps_256:
11396   case Intrinsic::x86_avx_hadd_pd_256:
11397   case Intrinsic::x86_sse3_hsub_ps:
11398   case Intrinsic::x86_sse3_hsub_pd:
11399   case Intrinsic::x86_avx_hsub_ps_256:
11400   case Intrinsic::x86_avx_hsub_pd_256:
11401   case Intrinsic::x86_ssse3_phadd_w_128:
11402   case Intrinsic::x86_ssse3_phadd_d_128:
11403   case Intrinsic::x86_avx2_phadd_w:
11404   case Intrinsic::x86_avx2_phadd_d:
11405   case Intrinsic::x86_ssse3_phsub_w_128:
11406   case Intrinsic::x86_ssse3_phsub_d_128:
11407   case Intrinsic::x86_avx2_phsub_w:
11408   case Intrinsic::x86_avx2_phsub_d: {
11409     unsigned Opcode;
11410     switch (IntNo) {
11411     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11412     case Intrinsic::x86_sse3_hadd_ps:
11413     case Intrinsic::x86_sse3_hadd_pd:
11414     case Intrinsic::x86_avx_hadd_ps_256:
11415     case Intrinsic::x86_avx_hadd_pd_256:
11416       Opcode = X86ISD::FHADD;
11417       break;
11418     case Intrinsic::x86_sse3_hsub_ps:
11419     case Intrinsic::x86_sse3_hsub_pd:
11420     case Intrinsic::x86_avx_hsub_ps_256:
11421     case Intrinsic::x86_avx_hsub_pd_256:
11422       Opcode = X86ISD::FHSUB;
11423       break;
11424     case Intrinsic::x86_ssse3_phadd_w_128:
11425     case Intrinsic::x86_ssse3_phadd_d_128:
11426     case Intrinsic::x86_avx2_phadd_w:
11427     case Intrinsic::x86_avx2_phadd_d:
11428       Opcode = X86ISD::HADD;
11429       break;
11430     case Intrinsic::x86_ssse3_phsub_w_128:
11431     case Intrinsic::x86_ssse3_phsub_d_128:
11432     case Intrinsic::x86_avx2_phsub_w:
11433     case Intrinsic::x86_avx2_phsub_d:
11434       Opcode = X86ISD::HSUB;
11435       break;
11436     }
11437     return DAG.getNode(Opcode, dl, Op.getValueType(),
11438                        Op.getOperand(1), Op.getOperand(2));
11439   }
11440
11441   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11442   case Intrinsic::x86_sse2_pmaxu_b:
11443   case Intrinsic::x86_sse41_pmaxuw:
11444   case Intrinsic::x86_sse41_pmaxud:
11445   case Intrinsic::x86_avx2_pmaxu_b:
11446   case Intrinsic::x86_avx2_pmaxu_w:
11447   case Intrinsic::x86_avx2_pmaxu_d:
11448   case Intrinsic::x86_sse2_pminu_b:
11449   case Intrinsic::x86_sse41_pminuw:
11450   case Intrinsic::x86_sse41_pminud:
11451   case Intrinsic::x86_avx2_pminu_b:
11452   case Intrinsic::x86_avx2_pminu_w:
11453   case Intrinsic::x86_avx2_pminu_d:
11454   case Intrinsic::x86_sse41_pmaxsb:
11455   case Intrinsic::x86_sse2_pmaxs_w:
11456   case Intrinsic::x86_sse41_pmaxsd:
11457   case Intrinsic::x86_avx2_pmaxs_b:
11458   case Intrinsic::x86_avx2_pmaxs_w:
11459   case Intrinsic::x86_avx2_pmaxs_d:
11460   case Intrinsic::x86_sse41_pminsb:
11461   case Intrinsic::x86_sse2_pmins_w:
11462   case Intrinsic::x86_sse41_pminsd:
11463   case Intrinsic::x86_avx2_pmins_b:
11464   case Intrinsic::x86_avx2_pmins_w:
11465   case Intrinsic::x86_avx2_pmins_d: {
11466     unsigned Opcode;
11467     switch (IntNo) {
11468     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11469     case Intrinsic::x86_sse2_pmaxu_b:
11470     case Intrinsic::x86_sse41_pmaxuw:
11471     case Intrinsic::x86_sse41_pmaxud:
11472     case Intrinsic::x86_avx2_pmaxu_b:
11473     case Intrinsic::x86_avx2_pmaxu_w:
11474     case Intrinsic::x86_avx2_pmaxu_d:
11475       Opcode = X86ISD::UMAX;
11476       break;
11477     case Intrinsic::x86_sse2_pminu_b:
11478     case Intrinsic::x86_sse41_pminuw:
11479     case Intrinsic::x86_sse41_pminud:
11480     case Intrinsic::x86_avx2_pminu_b:
11481     case Intrinsic::x86_avx2_pminu_w:
11482     case Intrinsic::x86_avx2_pminu_d:
11483       Opcode = X86ISD::UMIN;
11484       break;
11485     case Intrinsic::x86_sse41_pmaxsb:
11486     case Intrinsic::x86_sse2_pmaxs_w:
11487     case Intrinsic::x86_sse41_pmaxsd:
11488     case Intrinsic::x86_avx2_pmaxs_b:
11489     case Intrinsic::x86_avx2_pmaxs_w:
11490     case Intrinsic::x86_avx2_pmaxs_d:
11491       Opcode = X86ISD::SMAX;
11492       break;
11493     case Intrinsic::x86_sse41_pminsb:
11494     case Intrinsic::x86_sse2_pmins_w:
11495     case Intrinsic::x86_sse41_pminsd:
11496     case Intrinsic::x86_avx2_pmins_b:
11497     case Intrinsic::x86_avx2_pmins_w:
11498     case Intrinsic::x86_avx2_pmins_d:
11499       Opcode = X86ISD::SMIN;
11500       break;
11501     }
11502     return DAG.getNode(Opcode, dl, Op.getValueType(),
11503                        Op.getOperand(1), Op.getOperand(2));
11504   }
11505
11506   // SSE/SSE2/AVX floating point max/min intrinsics.
11507   case Intrinsic::x86_sse_max_ps:
11508   case Intrinsic::x86_sse2_max_pd:
11509   case Intrinsic::x86_avx_max_ps_256:
11510   case Intrinsic::x86_avx_max_pd_256:
11511   case Intrinsic::x86_sse_min_ps:
11512   case Intrinsic::x86_sse2_min_pd:
11513   case Intrinsic::x86_avx_min_ps_256:
11514   case Intrinsic::x86_avx_min_pd_256: {
11515     unsigned Opcode;
11516     switch (IntNo) {
11517     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11518     case Intrinsic::x86_sse_max_ps:
11519     case Intrinsic::x86_sse2_max_pd:
11520     case Intrinsic::x86_avx_max_ps_256:
11521     case Intrinsic::x86_avx_max_pd_256:
11522       Opcode = X86ISD::FMAX;
11523       break;
11524     case Intrinsic::x86_sse_min_ps:
11525     case Intrinsic::x86_sse2_min_pd:
11526     case Intrinsic::x86_avx_min_ps_256:
11527     case Intrinsic::x86_avx_min_pd_256:
11528       Opcode = X86ISD::FMIN;
11529       break;
11530     }
11531     return DAG.getNode(Opcode, dl, Op.getValueType(),
11532                        Op.getOperand(1), Op.getOperand(2));
11533   }
11534
11535   // AVX2 variable shift intrinsics
11536   case Intrinsic::x86_avx2_psllv_d:
11537   case Intrinsic::x86_avx2_psllv_q:
11538   case Intrinsic::x86_avx2_psllv_d_256:
11539   case Intrinsic::x86_avx2_psllv_q_256:
11540   case Intrinsic::x86_avx2_psrlv_d:
11541   case Intrinsic::x86_avx2_psrlv_q:
11542   case Intrinsic::x86_avx2_psrlv_d_256:
11543   case Intrinsic::x86_avx2_psrlv_q_256:
11544   case Intrinsic::x86_avx2_psrav_d:
11545   case Intrinsic::x86_avx2_psrav_d_256: {
11546     unsigned Opcode;
11547     switch (IntNo) {
11548     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11549     case Intrinsic::x86_avx2_psllv_d:
11550     case Intrinsic::x86_avx2_psllv_q:
11551     case Intrinsic::x86_avx2_psllv_d_256:
11552     case Intrinsic::x86_avx2_psllv_q_256:
11553       Opcode = ISD::SHL;
11554       break;
11555     case Intrinsic::x86_avx2_psrlv_d:
11556     case Intrinsic::x86_avx2_psrlv_q:
11557     case Intrinsic::x86_avx2_psrlv_d_256:
11558     case Intrinsic::x86_avx2_psrlv_q_256:
11559       Opcode = ISD::SRL;
11560       break;
11561     case Intrinsic::x86_avx2_psrav_d:
11562     case Intrinsic::x86_avx2_psrav_d_256:
11563       Opcode = ISD::SRA;
11564       break;
11565     }
11566     return DAG.getNode(Opcode, dl, Op.getValueType(),
11567                        Op.getOperand(1), Op.getOperand(2));
11568   }
11569
11570   case Intrinsic::x86_ssse3_pshuf_b_128:
11571   case Intrinsic::x86_avx2_pshuf_b:
11572     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11573                        Op.getOperand(1), Op.getOperand(2));
11574
11575   case Intrinsic::x86_ssse3_psign_b_128:
11576   case Intrinsic::x86_ssse3_psign_w_128:
11577   case Intrinsic::x86_ssse3_psign_d_128:
11578   case Intrinsic::x86_avx2_psign_b:
11579   case Intrinsic::x86_avx2_psign_w:
11580   case Intrinsic::x86_avx2_psign_d:
11581     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11582                        Op.getOperand(1), Op.getOperand(2));
11583
11584   case Intrinsic::x86_sse41_insertps:
11585     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11586                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11587
11588   case Intrinsic::x86_avx_vperm2f128_ps_256:
11589   case Intrinsic::x86_avx_vperm2f128_pd_256:
11590   case Intrinsic::x86_avx_vperm2f128_si_256:
11591   case Intrinsic::x86_avx2_vperm2i128:
11592     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11593                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11594
11595   case Intrinsic::x86_avx2_permd:
11596   case Intrinsic::x86_avx2_permps:
11597     // Operands intentionally swapped. Mask is last operand to intrinsic,
11598     // but second operand for node/instruction.
11599     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11600                        Op.getOperand(2), Op.getOperand(1));
11601
11602   case Intrinsic::x86_sse_sqrt_ps:
11603   case Intrinsic::x86_sse2_sqrt_pd:
11604   case Intrinsic::x86_avx_sqrt_ps_256:
11605   case Intrinsic::x86_avx_sqrt_pd_256:
11606     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11607
11608   // ptest and testp intrinsics. The intrinsic these come from are designed to
11609   // return an integer value, not just an instruction so lower it to the ptest
11610   // or testp pattern and a setcc for the result.
11611   case Intrinsic::x86_sse41_ptestz:
11612   case Intrinsic::x86_sse41_ptestc:
11613   case Intrinsic::x86_sse41_ptestnzc:
11614   case Intrinsic::x86_avx_ptestz_256:
11615   case Intrinsic::x86_avx_ptestc_256:
11616   case Intrinsic::x86_avx_ptestnzc_256:
11617   case Intrinsic::x86_avx_vtestz_ps:
11618   case Intrinsic::x86_avx_vtestc_ps:
11619   case Intrinsic::x86_avx_vtestnzc_ps:
11620   case Intrinsic::x86_avx_vtestz_pd:
11621   case Intrinsic::x86_avx_vtestc_pd:
11622   case Intrinsic::x86_avx_vtestnzc_pd:
11623   case Intrinsic::x86_avx_vtestz_ps_256:
11624   case Intrinsic::x86_avx_vtestc_ps_256:
11625   case Intrinsic::x86_avx_vtestnzc_ps_256:
11626   case Intrinsic::x86_avx_vtestz_pd_256:
11627   case Intrinsic::x86_avx_vtestc_pd_256:
11628   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11629     bool IsTestPacked = false;
11630     unsigned X86CC;
11631     switch (IntNo) {
11632     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11633     case Intrinsic::x86_avx_vtestz_ps:
11634     case Intrinsic::x86_avx_vtestz_pd:
11635     case Intrinsic::x86_avx_vtestz_ps_256:
11636     case Intrinsic::x86_avx_vtestz_pd_256:
11637       IsTestPacked = true; // Fallthrough
11638     case Intrinsic::x86_sse41_ptestz:
11639     case Intrinsic::x86_avx_ptestz_256:
11640       // ZF = 1
11641       X86CC = X86::COND_E;
11642       break;
11643     case Intrinsic::x86_avx_vtestc_ps:
11644     case Intrinsic::x86_avx_vtestc_pd:
11645     case Intrinsic::x86_avx_vtestc_ps_256:
11646     case Intrinsic::x86_avx_vtestc_pd_256:
11647       IsTestPacked = true; // Fallthrough
11648     case Intrinsic::x86_sse41_ptestc:
11649     case Intrinsic::x86_avx_ptestc_256:
11650       // CF = 1
11651       X86CC = X86::COND_B;
11652       break;
11653     case Intrinsic::x86_avx_vtestnzc_ps:
11654     case Intrinsic::x86_avx_vtestnzc_pd:
11655     case Intrinsic::x86_avx_vtestnzc_ps_256:
11656     case Intrinsic::x86_avx_vtestnzc_pd_256:
11657       IsTestPacked = true; // Fallthrough
11658     case Intrinsic::x86_sse41_ptestnzc:
11659     case Intrinsic::x86_avx_ptestnzc_256:
11660       // ZF and CF = 0
11661       X86CC = X86::COND_A;
11662       break;
11663     }
11664
11665     SDValue LHS = Op.getOperand(1);
11666     SDValue RHS = Op.getOperand(2);
11667     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11668     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11669     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11670     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11671     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11672   }
11673   case Intrinsic::x86_avx512_kortestz_w:
11674   case Intrinsic::x86_avx512_kortestc_w: {
11675     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11676     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11677     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11678     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11679     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11680     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11681     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11682   }
11683
11684   // SSE/AVX shift intrinsics
11685   case Intrinsic::x86_sse2_psll_w:
11686   case Intrinsic::x86_sse2_psll_d:
11687   case Intrinsic::x86_sse2_psll_q:
11688   case Intrinsic::x86_avx2_psll_w:
11689   case Intrinsic::x86_avx2_psll_d:
11690   case Intrinsic::x86_avx2_psll_q:
11691   case Intrinsic::x86_sse2_psrl_w:
11692   case Intrinsic::x86_sse2_psrl_d:
11693   case Intrinsic::x86_sse2_psrl_q:
11694   case Intrinsic::x86_avx2_psrl_w:
11695   case Intrinsic::x86_avx2_psrl_d:
11696   case Intrinsic::x86_avx2_psrl_q:
11697   case Intrinsic::x86_sse2_psra_w:
11698   case Intrinsic::x86_sse2_psra_d:
11699   case Intrinsic::x86_avx2_psra_w:
11700   case Intrinsic::x86_avx2_psra_d: {
11701     unsigned Opcode;
11702     switch (IntNo) {
11703     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11704     case Intrinsic::x86_sse2_psll_w:
11705     case Intrinsic::x86_sse2_psll_d:
11706     case Intrinsic::x86_sse2_psll_q:
11707     case Intrinsic::x86_avx2_psll_w:
11708     case Intrinsic::x86_avx2_psll_d:
11709     case Intrinsic::x86_avx2_psll_q:
11710       Opcode = X86ISD::VSHL;
11711       break;
11712     case Intrinsic::x86_sse2_psrl_w:
11713     case Intrinsic::x86_sse2_psrl_d:
11714     case Intrinsic::x86_sse2_psrl_q:
11715     case Intrinsic::x86_avx2_psrl_w:
11716     case Intrinsic::x86_avx2_psrl_d:
11717     case Intrinsic::x86_avx2_psrl_q:
11718       Opcode = X86ISD::VSRL;
11719       break;
11720     case Intrinsic::x86_sse2_psra_w:
11721     case Intrinsic::x86_sse2_psra_d:
11722     case Intrinsic::x86_avx2_psra_w:
11723     case Intrinsic::x86_avx2_psra_d:
11724       Opcode = X86ISD::VSRA;
11725       break;
11726     }
11727     return DAG.getNode(Opcode, dl, Op.getValueType(),
11728                        Op.getOperand(1), Op.getOperand(2));
11729   }
11730
11731   // SSE/AVX immediate shift intrinsics
11732   case Intrinsic::x86_sse2_pslli_w:
11733   case Intrinsic::x86_sse2_pslli_d:
11734   case Intrinsic::x86_sse2_pslli_q:
11735   case Intrinsic::x86_avx2_pslli_w:
11736   case Intrinsic::x86_avx2_pslli_d:
11737   case Intrinsic::x86_avx2_pslli_q:
11738   case Intrinsic::x86_sse2_psrli_w:
11739   case Intrinsic::x86_sse2_psrli_d:
11740   case Intrinsic::x86_sse2_psrli_q:
11741   case Intrinsic::x86_avx2_psrli_w:
11742   case Intrinsic::x86_avx2_psrli_d:
11743   case Intrinsic::x86_avx2_psrli_q:
11744   case Intrinsic::x86_sse2_psrai_w:
11745   case Intrinsic::x86_sse2_psrai_d:
11746   case Intrinsic::x86_avx2_psrai_w:
11747   case Intrinsic::x86_avx2_psrai_d: {
11748     unsigned Opcode;
11749     switch (IntNo) {
11750     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11751     case Intrinsic::x86_sse2_pslli_w:
11752     case Intrinsic::x86_sse2_pslli_d:
11753     case Intrinsic::x86_sse2_pslli_q:
11754     case Intrinsic::x86_avx2_pslli_w:
11755     case Intrinsic::x86_avx2_pslli_d:
11756     case Intrinsic::x86_avx2_pslli_q:
11757       Opcode = X86ISD::VSHLI;
11758       break;
11759     case Intrinsic::x86_sse2_psrli_w:
11760     case Intrinsic::x86_sse2_psrli_d:
11761     case Intrinsic::x86_sse2_psrli_q:
11762     case Intrinsic::x86_avx2_psrli_w:
11763     case Intrinsic::x86_avx2_psrli_d:
11764     case Intrinsic::x86_avx2_psrli_q:
11765       Opcode = X86ISD::VSRLI;
11766       break;
11767     case Intrinsic::x86_sse2_psrai_w:
11768     case Intrinsic::x86_sse2_psrai_d:
11769     case Intrinsic::x86_avx2_psrai_w:
11770     case Intrinsic::x86_avx2_psrai_d:
11771       Opcode = X86ISD::VSRAI;
11772       break;
11773     }
11774     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11775                                Op.getOperand(1), Op.getOperand(2), DAG);
11776   }
11777
11778   case Intrinsic::x86_sse42_pcmpistria128:
11779   case Intrinsic::x86_sse42_pcmpestria128:
11780   case Intrinsic::x86_sse42_pcmpistric128:
11781   case Intrinsic::x86_sse42_pcmpestric128:
11782   case Intrinsic::x86_sse42_pcmpistrio128:
11783   case Intrinsic::x86_sse42_pcmpestrio128:
11784   case Intrinsic::x86_sse42_pcmpistris128:
11785   case Intrinsic::x86_sse42_pcmpestris128:
11786   case Intrinsic::x86_sse42_pcmpistriz128:
11787   case Intrinsic::x86_sse42_pcmpestriz128: {
11788     unsigned Opcode;
11789     unsigned X86CC;
11790     switch (IntNo) {
11791     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11792     case Intrinsic::x86_sse42_pcmpistria128:
11793       Opcode = X86ISD::PCMPISTRI;
11794       X86CC = X86::COND_A;
11795       break;
11796     case Intrinsic::x86_sse42_pcmpestria128:
11797       Opcode = X86ISD::PCMPESTRI;
11798       X86CC = X86::COND_A;
11799       break;
11800     case Intrinsic::x86_sse42_pcmpistric128:
11801       Opcode = X86ISD::PCMPISTRI;
11802       X86CC = X86::COND_B;
11803       break;
11804     case Intrinsic::x86_sse42_pcmpestric128:
11805       Opcode = X86ISD::PCMPESTRI;
11806       X86CC = X86::COND_B;
11807       break;
11808     case Intrinsic::x86_sse42_pcmpistrio128:
11809       Opcode = X86ISD::PCMPISTRI;
11810       X86CC = X86::COND_O;
11811       break;
11812     case Intrinsic::x86_sse42_pcmpestrio128:
11813       Opcode = X86ISD::PCMPESTRI;
11814       X86CC = X86::COND_O;
11815       break;
11816     case Intrinsic::x86_sse42_pcmpistris128:
11817       Opcode = X86ISD::PCMPISTRI;
11818       X86CC = X86::COND_S;
11819       break;
11820     case Intrinsic::x86_sse42_pcmpestris128:
11821       Opcode = X86ISD::PCMPESTRI;
11822       X86CC = X86::COND_S;
11823       break;
11824     case Intrinsic::x86_sse42_pcmpistriz128:
11825       Opcode = X86ISD::PCMPISTRI;
11826       X86CC = X86::COND_E;
11827       break;
11828     case Intrinsic::x86_sse42_pcmpestriz128:
11829       Opcode = X86ISD::PCMPESTRI;
11830       X86CC = X86::COND_E;
11831       break;
11832     }
11833     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11834     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11835     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11836     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11837                                 DAG.getConstant(X86CC, MVT::i8),
11838                                 SDValue(PCMP.getNode(), 1));
11839     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11840   }
11841
11842   case Intrinsic::x86_sse42_pcmpistri128:
11843   case Intrinsic::x86_sse42_pcmpestri128: {
11844     unsigned Opcode;
11845     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11846       Opcode = X86ISD::PCMPISTRI;
11847     else
11848       Opcode = X86ISD::PCMPESTRI;
11849
11850     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11851     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11852     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11853   }
11854   case Intrinsic::x86_fma_vfmadd_ps:
11855   case Intrinsic::x86_fma_vfmadd_pd:
11856   case Intrinsic::x86_fma_vfmsub_ps:
11857   case Intrinsic::x86_fma_vfmsub_pd:
11858   case Intrinsic::x86_fma_vfnmadd_ps:
11859   case Intrinsic::x86_fma_vfnmadd_pd:
11860   case Intrinsic::x86_fma_vfnmsub_ps:
11861   case Intrinsic::x86_fma_vfnmsub_pd:
11862   case Intrinsic::x86_fma_vfmaddsub_ps:
11863   case Intrinsic::x86_fma_vfmaddsub_pd:
11864   case Intrinsic::x86_fma_vfmsubadd_ps:
11865   case Intrinsic::x86_fma_vfmsubadd_pd:
11866   case Intrinsic::x86_fma_vfmadd_ps_256:
11867   case Intrinsic::x86_fma_vfmadd_pd_256:
11868   case Intrinsic::x86_fma_vfmsub_ps_256:
11869   case Intrinsic::x86_fma_vfmsub_pd_256:
11870   case Intrinsic::x86_fma_vfnmadd_ps_256:
11871   case Intrinsic::x86_fma_vfnmadd_pd_256:
11872   case Intrinsic::x86_fma_vfnmsub_ps_256:
11873   case Intrinsic::x86_fma_vfnmsub_pd_256:
11874   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11875   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11876   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11877   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11878   case Intrinsic::x86_fma_vfmadd_ps_512:
11879   case Intrinsic::x86_fma_vfmadd_pd_512:
11880   case Intrinsic::x86_fma_vfmsub_ps_512:
11881   case Intrinsic::x86_fma_vfmsub_pd_512:
11882   case Intrinsic::x86_fma_vfnmadd_ps_512:
11883   case Intrinsic::x86_fma_vfnmadd_pd_512:
11884   case Intrinsic::x86_fma_vfnmsub_ps_512:
11885   case Intrinsic::x86_fma_vfnmsub_pd_512:
11886   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11887   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11888   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11889   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11890     unsigned Opc;
11891     switch (IntNo) {
11892     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11893     case Intrinsic::x86_fma_vfmadd_ps:
11894     case Intrinsic::x86_fma_vfmadd_pd:
11895     case Intrinsic::x86_fma_vfmadd_ps_256:
11896     case Intrinsic::x86_fma_vfmadd_pd_256:
11897     case Intrinsic::x86_fma_vfmadd_ps_512:
11898     case Intrinsic::x86_fma_vfmadd_pd_512:
11899       Opc = X86ISD::FMADD;
11900       break;
11901     case Intrinsic::x86_fma_vfmsub_ps:
11902     case Intrinsic::x86_fma_vfmsub_pd:
11903     case Intrinsic::x86_fma_vfmsub_ps_256:
11904     case Intrinsic::x86_fma_vfmsub_pd_256:
11905     case Intrinsic::x86_fma_vfmsub_ps_512:
11906     case Intrinsic::x86_fma_vfmsub_pd_512:
11907       Opc = X86ISD::FMSUB;
11908       break;
11909     case Intrinsic::x86_fma_vfnmadd_ps:
11910     case Intrinsic::x86_fma_vfnmadd_pd:
11911     case Intrinsic::x86_fma_vfnmadd_ps_256:
11912     case Intrinsic::x86_fma_vfnmadd_pd_256:
11913     case Intrinsic::x86_fma_vfnmadd_ps_512:
11914     case Intrinsic::x86_fma_vfnmadd_pd_512:
11915       Opc = X86ISD::FNMADD;
11916       break;
11917     case Intrinsic::x86_fma_vfnmsub_ps:
11918     case Intrinsic::x86_fma_vfnmsub_pd:
11919     case Intrinsic::x86_fma_vfnmsub_ps_256:
11920     case Intrinsic::x86_fma_vfnmsub_pd_256:
11921     case Intrinsic::x86_fma_vfnmsub_ps_512:
11922     case Intrinsic::x86_fma_vfnmsub_pd_512:
11923       Opc = X86ISD::FNMSUB;
11924       break;
11925     case Intrinsic::x86_fma_vfmaddsub_ps:
11926     case Intrinsic::x86_fma_vfmaddsub_pd:
11927     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11928     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11929     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11930     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11931       Opc = X86ISD::FMADDSUB;
11932       break;
11933     case Intrinsic::x86_fma_vfmsubadd_ps:
11934     case Intrinsic::x86_fma_vfmsubadd_pd:
11935     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11936     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11937     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11938     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11939       Opc = X86ISD::FMSUBADD;
11940       break;
11941     }
11942
11943     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11944                        Op.getOperand(2), Op.getOperand(3));
11945   }
11946   }
11947 }
11948
11949 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11950                              SDValue Base, SDValue Index,
11951                              SDValue ScaleOp, SDValue Chain,
11952                              const X86Subtarget * Subtarget) {
11953   SDLoc dl(Op);
11954   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11955   assert(C && "Invalid scale type");
11956   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11957   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11958   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11959                              Index.getSimpleValueType().getVectorNumElements());
11960   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11961   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11962   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11963   SDValue Segment = DAG.getRegister(0, MVT::i32);
11964   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11965   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11966   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11967   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11968 }
11969
11970 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11971                               SDValue Src, SDValue Mask, SDValue Base,
11972                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11973                               const X86Subtarget * Subtarget) {
11974   SDLoc dl(Op);
11975   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11976   assert(C && "Invalid scale type");
11977   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11978   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11979                              Index.getSimpleValueType().getVectorNumElements());
11980   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11981   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11982   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11983   SDValue Segment = DAG.getRegister(0, MVT::i32);
11984   if (Src.getOpcode() == ISD::UNDEF)
11985     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11986   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11987   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11988   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11989   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11990 }
11991
11992 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11993                               SDValue Src, SDValue Base, SDValue Index,
11994                               SDValue ScaleOp, SDValue Chain) {
11995   SDLoc dl(Op);
11996   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11997   assert(C && "Invalid scale type");
11998   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11999   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12000   SDValue Segment = DAG.getRegister(0, MVT::i32);
12001   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12002                              Index.getSimpleValueType().getVectorNumElements());
12003   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12004   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12005   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12006   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12007   return SDValue(Res, 1);
12008 }
12009
12010 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12011                                SDValue Src, SDValue Mask, SDValue Base,
12012                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12013   SDLoc dl(Op);
12014   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12015   assert(C && "Invalid scale type");
12016   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12017   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12018   SDValue Segment = DAG.getRegister(0, MVT::i32);
12019   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12020                              Index.getSimpleValueType().getVectorNumElements());
12021   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12022   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12023   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12024   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12025   return SDValue(Res, 1);
12026 }
12027
12028 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12029                                       SelectionDAG &DAG) {
12030   SDLoc dl(Op);
12031   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12032   switch (IntNo) {
12033   default: return SDValue();    // Don't custom lower most intrinsics.
12034
12035   // RDRAND/RDSEED intrinsics.
12036   case Intrinsic::x86_rdrand_16:
12037   case Intrinsic::x86_rdrand_32:
12038   case Intrinsic::x86_rdrand_64:
12039   case Intrinsic::x86_rdseed_16:
12040   case Intrinsic::x86_rdseed_32:
12041   case Intrinsic::x86_rdseed_64: {
12042     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12043                        IntNo == Intrinsic::x86_rdseed_32 ||
12044                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12045                                                             X86ISD::RDRAND;
12046     // Emit the node with the right value type.
12047     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12048     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12049
12050     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12051     // Otherwise return the value from Rand, which is always 0, casted to i32.
12052     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12053                       DAG.getConstant(1, Op->getValueType(1)),
12054                       DAG.getConstant(X86::COND_B, MVT::i32),
12055                       SDValue(Result.getNode(), 1) };
12056     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12057                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12058                                   Ops, array_lengthof(Ops));
12059
12060     // Return { result, isValid, chain }.
12061     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12062                        SDValue(Result.getNode(), 2));
12063   }
12064   //int_gather(index, base, scale);
12065   case Intrinsic::x86_avx512_gather_qpd_512:
12066   case Intrinsic::x86_avx512_gather_qps_512:
12067   case Intrinsic::x86_avx512_gather_dpd_512:
12068   case Intrinsic::x86_avx512_gather_qpi_512:
12069   case Intrinsic::x86_avx512_gather_qpq_512:
12070   case Intrinsic::x86_avx512_gather_dpq_512:
12071   case Intrinsic::x86_avx512_gather_dps_512:
12072   case Intrinsic::x86_avx512_gather_dpi_512: {
12073     unsigned Opc;
12074     switch (IntNo) {
12075     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12076     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12077     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12078     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12079     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12080     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12081     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12082     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12083     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12084     }
12085     SDValue Chain = Op.getOperand(0);
12086     SDValue Index = Op.getOperand(2);
12087     SDValue Base  = Op.getOperand(3);
12088     SDValue Scale = Op.getOperand(4);
12089     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12090   }
12091   //int_gather_mask(v1, mask, index, base, scale);
12092   case Intrinsic::x86_avx512_gather_qps_mask_512:
12093   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12094   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12095   case Intrinsic::x86_avx512_gather_dps_mask_512:
12096   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12097   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12098   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12099   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12100     unsigned Opc;
12101     switch (IntNo) {
12102     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12103     case Intrinsic::x86_avx512_gather_qps_mask_512:
12104       Opc = X86::VGATHERQPSZrm; break;
12105     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12106       Opc = X86::VGATHERQPDZrm; break;
12107     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12108       Opc = X86::VGATHERDPDZrm; break;
12109     case Intrinsic::x86_avx512_gather_dps_mask_512:
12110       Opc = X86::VGATHERDPSZrm; break;
12111     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12112       Opc = X86::VPGATHERQDZrm; break;
12113     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12114       Opc = X86::VPGATHERQQZrm; break;
12115     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12116       Opc = X86::VPGATHERDDZrm; break;
12117     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12118       Opc = X86::VPGATHERDQZrm; break;
12119     }
12120     SDValue Chain = Op.getOperand(0);
12121     SDValue Src   = Op.getOperand(2);
12122     SDValue Mask  = Op.getOperand(3);
12123     SDValue Index = Op.getOperand(4);
12124     SDValue Base  = Op.getOperand(5);
12125     SDValue Scale = Op.getOperand(6);
12126     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12127                           Subtarget);
12128   }
12129   //int_scatter(base, index, v1, scale);
12130   case Intrinsic::x86_avx512_scatter_qpd_512:
12131   case Intrinsic::x86_avx512_scatter_qps_512:
12132   case Intrinsic::x86_avx512_scatter_dpd_512:
12133   case Intrinsic::x86_avx512_scatter_qpi_512:
12134   case Intrinsic::x86_avx512_scatter_qpq_512:
12135   case Intrinsic::x86_avx512_scatter_dpq_512:
12136   case Intrinsic::x86_avx512_scatter_dps_512:
12137   case Intrinsic::x86_avx512_scatter_dpi_512: {
12138     unsigned Opc;
12139     switch (IntNo) {
12140     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12141     case Intrinsic::x86_avx512_scatter_qpd_512:
12142       Opc = X86::VSCATTERQPDZmr; break;
12143     case Intrinsic::x86_avx512_scatter_qps_512:
12144       Opc = X86::VSCATTERQPSZmr; break;
12145     case Intrinsic::x86_avx512_scatter_dpd_512:
12146       Opc = X86::VSCATTERDPDZmr; break;
12147     case Intrinsic::x86_avx512_scatter_dps_512:
12148       Opc = X86::VSCATTERDPSZmr; break;
12149     case Intrinsic::x86_avx512_scatter_qpi_512:
12150       Opc = X86::VPSCATTERQDZmr; break;
12151     case Intrinsic::x86_avx512_scatter_qpq_512:
12152       Opc = X86::VPSCATTERQQZmr; break;
12153     case Intrinsic::x86_avx512_scatter_dpq_512:
12154       Opc = X86::VPSCATTERDQZmr; break;
12155     case Intrinsic::x86_avx512_scatter_dpi_512:
12156       Opc = X86::VPSCATTERDDZmr; break;
12157     }
12158     SDValue Chain = Op.getOperand(0);
12159     SDValue Base  = Op.getOperand(2);
12160     SDValue Index = Op.getOperand(3);
12161     SDValue Src   = Op.getOperand(4);
12162     SDValue Scale = Op.getOperand(5);
12163     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12164   }
12165   //int_scatter_mask(base, mask, index, v1, scale);
12166   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12167   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12168   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12169   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12170   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12171   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12172   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12173   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12174     unsigned Opc;
12175     switch (IntNo) {
12176     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12177     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12178       Opc = X86::VSCATTERQPDZmr; break;
12179     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12180       Opc = X86::VSCATTERQPSZmr; break;
12181     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12182       Opc = X86::VSCATTERDPDZmr; break;
12183     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12184       Opc = X86::VSCATTERDPSZmr; break;
12185     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12186       Opc = X86::VPSCATTERQDZmr; break;
12187     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12188       Opc = X86::VPSCATTERQQZmr; break;
12189     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12190       Opc = X86::VPSCATTERDQZmr; break;
12191     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12192       Opc = X86::VPSCATTERDDZmr; break;
12193     }
12194     SDValue Chain = Op.getOperand(0);
12195     SDValue Base  = Op.getOperand(2);
12196     SDValue Mask  = Op.getOperand(3);
12197     SDValue Index = Op.getOperand(4);
12198     SDValue Src   = Op.getOperand(5);
12199     SDValue Scale = Op.getOperand(6);
12200     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12201   }
12202   // XTEST intrinsics.
12203   case Intrinsic::x86_xtest: {
12204     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12205     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12206     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12207                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12208                                 InTrans);
12209     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12210     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12211                        Ret, SDValue(InTrans.getNode(), 1));
12212   }
12213   }
12214 }
12215
12216 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12217                                            SelectionDAG &DAG) const {
12218   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12219   MFI->setReturnAddressIsTaken(true);
12220
12221   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12222     return SDValue();
12223
12224   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12225   SDLoc dl(Op);
12226   EVT PtrVT = getPointerTy();
12227
12228   if (Depth > 0) {
12229     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12230     const X86RegisterInfo *RegInfo =
12231       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12232     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12233     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12234                        DAG.getNode(ISD::ADD, dl, PtrVT,
12235                                    FrameAddr, Offset),
12236                        MachinePointerInfo(), false, false, false, 0);
12237   }
12238
12239   // Just load the return address.
12240   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12241   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12242                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12243 }
12244
12245 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12246   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12247   MFI->setFrameAddressIsTaken(true);
12248
12249   EVT VT = Op.getValueType();
12250   SDLoc dl(Op);  // FIXME probably not meaningful
12251   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12252   const X86RegisterInfo *RegInfo =
12253     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12254   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12255   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12256           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12257          "Invalid Frame Register!");
12258   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12259   while (Depth--)
12260     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12261                             MachinePointerInfo(),
12262                             false, false, false, 0);
12263   return FrameAddr;
12264 }
12265
12266 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12267                                                      SelectionDAG &DAG) const {
12268   const X86RegisterInfo *RegInfo =
12269     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12270   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12271 }
12272
12273 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12274   SDValue Chain     = Op.getOperand(0);
12275   SDValue Offset    = Op.getOperand(1);
12276   SDValue Handler   = Op.getOperand(2);
12277   SDLoc dl      (Op);
12278
12279   EVT PtrVT = getPointerTy();
12280   const X86RegisterInfo *RegInfo =
12281     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12282   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12283   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12284           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12285          "Invalid Frame Register!");
12286   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12287   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12288
12289   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12290                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12291   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12292   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12293                        false, false, 0);
12294   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12295
12296   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12297                      DAG.getRegister(StoreAddrReg, PtrVT));
12298 }
12299
12300 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12301                                                SelectionDAG &DAG) const {
12302   SDLoc DL(Op);
12303   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12304                      DAG.getVTList(MVT::i32, MVT::Other),
12305                      Op.getOperand(0), Op.getOperand(1));
12306 }
12307
12308 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12309                                                 SelectionDAG &DAG) const {
12310   SDLoc DL(Op);
12311   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12312                      Op.getOperand(0), Op.getOperand(1));
12313 }
12314
12315 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12316   return Op.getOperand(0);
12317 }
12318
12319 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12320                                                 SelectionDAG &DAG) const {
12321   SDValue Root = Op.getOperand(0);
12322   SDValue Trmp = Op.getOperand(1); // trampoline
12323   SDValue FPtr = Op.getOperand(2); // nested function
12324   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12325   SDLoc dl (Op);
12326
12327   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12328   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12329
12330   if (Subtarget->is64Bit()) {
12331     SDValue OutChains[6];
12332
12333     // Large code-model.
12334     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12335     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12336
12337     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12338     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12339
12340     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12341
12342     // Load the pointer to the nested function into R11.
12343     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12344     SDValue Addr = Trmp;
12345     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12346                                 Addr, MachinePointerInfo(TrmpAddr),
12347                                 false, false, 0);
12348
12349     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12350                        DAG.getConstant(2, MVT::i64));
12351     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12352                                 MachinePointerInfo(TrmpAddr, 2),
12353                                 false, false, 2);
12354
12355     // Load the 'nest' parameter value into R10.
12356     // R10 is specified in X86CallingConv.td
12357     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12358     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12359                        DAG.getConstant(10, MVT::i64));
12360     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12361                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12362                                 false, false, 0);
12363
12364     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12365                        DAG.getConstant(12, MVT::i64));
12366     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12367                                 MachinePointerInfo(TrmpAddr, 12),
12368                                 false, false, 2);
12369
12370     // Jump to the nested function.
12371     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12372     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12373                        DAG.getConstant(20, MVT::i64));
12374     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12375                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12376                                 false, false, 0);
12377
12378     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12379     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12380                        DAG.getConstant(22, MVT::i64));
12381     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12382                                 MachinePointerInfo(TrmpAddr, 22),
12383                                 false, false, 0);
12384
12385     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12386   } else {
12387     const Function *Func =
12388       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12389     CallingConv::ID CC = Func->getCallingConv();
12390     unsigned NestReg;
12391
12392     switch (CC) {
12393     default:
12394       llvm_unreachable("Unsupported calling convention");
12395     case CallingConv::C:
12396     case CallingConv::X86_StdCall: {
12397       // Pass 'nest' parameter in ECX.
12398       // Must be kept in sync with X86CallingConv.td
12399       NestReg = X86::ECX;
12400
12401       // Check that ECX wasn't needed by an 'inreg' parameter.
12402       FunctionType *FTy = Func->getFunctionType();
12403       const AttributeSet &Attrs = Func->getAttributes();
12404
12405       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12406         unsigned InRegCount = 0;
12407         unsigned Idx = 1;
12408
12409         for (FunctionType::param_iterator I = FTy->param_begin(),
12410              E = FTy->param_end(); I != E; ++I, ++Idx)
12411           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12412             // FIXME: should only count parameters that are lowered to integers.
12413             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12414
12415         if (InRegCount > 2) {
12416           report_fatal_error("Nest register in use - reduce number of inreg"
12417                              " parameters!");
12418         }
12419       }
12420       break;
12421     }
12422     case CallingConv::X86_FastCall:
12423     case CallingConv::X86_ThisCall:
12424     case CallingConv::Fast:
12425       // Pass 'nest' parameter in EAX.
12426       // Must be kept in sync with X86CallingConv.td
12427       NestReg = X86::EAX;
12428       break;
12429     }
12430
12431     SDValue OutChains[4];
12432     SDValue Addr, Disp;
12433
12434     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12435                        DAG.getConstant(10, MVT::i32));
12436     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12437
12438     // This is storing the opcode for MOV32ri.
12439     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12440     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12441     OutChains[0] = DAG.getStore(Root, dl,
12442                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12443                                 Trmp, MachinePointerInfo(TrmpAddr),
12444                                 false, false, 0);
12445
12446     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12447                        DAG.getConstant(1, MVT::i32));
12448     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12449                                 MachinePointerInfo(TrmpAddr, 1),
12450                                 false, false, 1);
12451
12452     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12454                        DAG.getConstant(5, MVT::i32));
12455     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12456                                 MachinePointerInfo(TrmpAddr, 5),
12457                                 false, false, 1);
12458
12459     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12460                        DAG.getConstant(6, MVT::i32));
12461     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12462                                 MachinePointerInfo(TrmpAddr, 6),
12463                                 false, false, 1);
12464
12465     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12466   }
12467 }
12468
12469 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12470                                             SelectionDAG &DAG) const {
12471   /*
12472    The rounding mode is in bits 11:10 of FPSR, and has the following
12473    settings:
12474      00 Round to nearest
12475      01 Round to -inf
12476      10 Round to +inf
12477      11 Round to 0
12478
12479   FLT_ROUNDS, on the other hand, expects the following:
12480     -1 Undefined
12481      0 Round to 0
12482      1 Round to nearest
12483      2 Round to +inf
12484      3 Round to -inf
12485
12486   To perform the conversion, we do:
12487     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12488   */
12489
12490   MachineFunction &MF = DAG.getMachineFunction();
12491   const TargetMachine &TM = MF.getTarget();
12492   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12493   unsigned StackAlignment = TFI.getStackAlignment();
12494   MVT VT = Op.getSimpleValueType();
12495   SDLoc DL(Op);
12496
12497   // Save FP Control Word to stack slot
12498   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12499   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12500
12501   MachineMemOperand *MMO =
12502    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12503                            MachineMemOperand::MOStore, 2, 2);
12504
12505   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12506   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12507                                           DAG.getVTList(MVT::Other),
12508                                           Ops, array_lengthof(Ops), MVT::i16,
12509                                           MMO);
12510
12511   // Load FP Control Word from stack slot
12512   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12513                             MachinePointerInfo(), false, false, false, 0);
12514
12515   // Transform as necessary
12516   SDValue CWD1 =
12517     DAG.getNode(ISD::SRL, DL, MVT::i16,
12518                 DAG.getNode(ISD::AND, DL, MVT::i16,
12519                             CWD, DAG.getConstant(0x800, MVT::i16)),
12520                 DAG.getConstant(11, MVT::i8));
12521   SDValue CWD2 =
12522     DAG.getNode(ISD::SRL, DL, MVT::i16,
12523                 DAG.getNode(ISD::AND, DL, MVT::i16,
12524                             CWD, DAG.getConstant(0x400, MVT::i16)),
12525                 DAG.getConstant(9, MVT::i8));
12526
12527   SDValue RetVal =
12528     DAG.getNode(ISD::AND, DL, MVT::i16,
12529                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12530                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12531                             DAG.getConstant(1, MVT::i16)),
12532                 DAG.getConstant(3, MVT::i16));
12533
12534   return DAG.getNode((VT.getSizeInBits() < 16 ?
12535                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12536 }
12537
12538 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12539   MVT VT = Op.getSimpleValueType();
12540   EVT OpVT = VT;
12541   unsigned NumBits = VT.getSizeInBits();
12542   SDLoc dl(Op);
12543
12544   Op = Op.getOperand(0);
12545   if (VT == MVT::i8) {
12546     // Zero extend to i32 since there is not an i8 bsr.
12547     OpVT = MVT::i32;
12548     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12549   }
12550
12551   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12552   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12553   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12554
12555   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12556   SDValue Ops[] = {
12557     Op,
12558     DAG.getConstant(NumBits+NumBits-1, OpVT),
12559     DAG.getConstant(X86::COND_E, MVT::i8),
12560     Op.getValue(1)
12561   };
12562   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12563
12564   // Finally xor with NumBits-1.
12565   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12566
12567   if (VT == MVT::i8)
12568     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12569   return Op;
12570 }
12571
12572 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12573   MVT VT = Op.getSimpleValueType();
12574   EVT OpVT = VT;
12575   unsigned NumBits = VT.getSizeInBits();
12576   SDLoc dl(Op);
12577
12578   Op = Op.getOperand(0);
12579   if (VT == MVT::i8) {
12580     // Zero extend to i32 since there is not an i8 bsr.
12581     OpVT = MVT::i32;
12582     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12583   }
12584
12585   // Issue a bsr (scan bits in reverse).
12586   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12587   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12588
12589   // And xor with NumBits-1.
12590   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12591
12592   if (VT == MVT::i8)
12593     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12594   return Op;
12595 }
12596
12597 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12598   MVT VT = Op.getSimpleValueType();
12599   unsigned NumBits = VT.getSizeInBits();
12600   SDLoc dl(Op);
12601   Op = Op.getOperand(0);
12602
12603   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12604   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12605   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12606
12607   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12608   SDValue Ops[] = {
12609     Op,
12610     DAG.getConstant(NumBits, VT),
12611     DAG.getConstant(X86::COND_E, MVT::i8),
12612     Op.getValue(1)
12613   };
12614   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12615 }
12616
12617 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12618 // ones, and then concatenate the result back.
12619 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12620   MVT VT = Op.getSimpleValueType();
12621
12622   assert(VT.is256BitVector() && VT.isInteger() &&
12623          "Unsupported value type for operation");
12624
12625   unsigned NumElems = VT.getVectorNumElements();
12626   SDLoc dl(Op);
12627
12628   // Extract the LHS vectors
12629   SDValue LHS = Op.getOperand(0);
12630   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12631   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12632
12633   // Extract the RHS vectors
12634   SDValue RHS = Op.getOperand(1);
12635   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12636   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12637
12638   MVT EltVT = VT.getVectorElementType();
12639   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12640
12641   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12642                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12643                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12644 }
12645
12646 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12647   assert(Op.getSimpleValueType().is256BitVector() &&
12648          Op.getSimpleValueType().isInteger() &&
12649          "Only handle AVX 256-bit vector integer operation");
12650   return Lower256IntArith(Op, DAG);
12651 }
12652
12653 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12654   assert(Op.getSimpleValueType().is256BitVector() &&
12655          Op.getSimpleValueType().isInteger() &&
12656          "Only handle AVX 256-bit vector integer operation");
12657   return Lower256IntArith(Op, DAG);
12658 }
12659
12660 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12661                         SelectionDAG &DAG) {
12662   SDLoc dl(Op);
12663   MVT VT = Op.getSimpleValueType();
12664
12665   // Decompose 256-bit ops into smaller 128-bit ops.
12666   if (VT.is256BitVector() && !Subtarget->hasInt256())
12667     return Lower256IntArith(Op, DAG);
12668
12669   SDValue A = Op.getOperand(0);
12670   SDValue B = Op.getOperand(1);
12671
12672   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12673   if (VT == MVT::v4i32) {
12674     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12675            "Should not custom lower when pmuldq is available!");
12676
12677     // Extract the odd parts.
12678     static const int UnpackMask[] = { 1, -1, 3, -1 };
12679     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12680     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12681
12682     // Multiply the even parts.
12683     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12684     // Now multiply odd parts.
12685     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12686
12687     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12688     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12689
12690     // Merge the two vectors back together with a shuffle. This expands into 2
12691     // shuffles.
12692     static const int ShufMask[] = { 0, 4, 2, 6 };
12693     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12694   }
12695
12696   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12697          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12698
12699   //  Ahi = psrlqi(a, 32);
12700   //  Bhi = psrlqi(b, 32);
12701   //
12702   //  AloBlo = pmuludq(a, b);
12703   //  AloBhi = pmuludq(a, Bhi);
12704   //  AhiBlo = pmuludq(Ahi, b);
12705
12706   //  AloBhi = psllqi(AloBhi, 32);
12707   //  AhiBlo = psllqi(AhiBlo, 32);
12708   //  return AloBlo + AloBhi + AhiBlo;
12709
12710   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12711   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12712
12713   // Bit cast to 32-bit vectors for MULUDQ
12714   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12715                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12716   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12717   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12718   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12719   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12720
12721   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12722   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12723   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12724
12725   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12726   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12727
12728   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12729   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12730 }
12731
12732 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12733   MVT VT = Op.getSimpleValueType();
12734   MVT EltTy = VT.getVectorElementType();
12735   unsigned NumElts = VT.getVectorNumElements();
12736   SDValue N0 = Op.getOperand(0);
12737   SDLoc dl(Op);
12738
12739   // Lower sdiv X, pow2-const.
12740   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12741   if (!C)
12742     return SDValue();
12743
12744   APInt SplatValue, SplatUndef;
12745   unsigned SplatBitSize;
12746   bool HasAnyUndefs;
12747   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12748                           HasAnyUndefs) ||
12749       EltTy.getSizeInBits() < SplatBitSize)
12750     return SDValue();
12751
12752   if ((SplatValue != 0) &&
12753       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12754     unsigned Lg2 = SplatValue.countTrailingZeros();
12755     // Splat the sign bit.
12756     SmallVector<SDValue, 16> Sz(NumElts,
12757                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12758                                                 EltTy));
12759     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12760                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12761                                           NumElts));
12762     // Add (N0 < 0) ? abs2 - 1 : 0;
12763     SmallVector<SDValue, 16> Amt(NumElts,
12764                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12765                                                  EltTy));
12766     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12767                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12768                                           NumElts));
12769     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12770     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12771     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12772                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12773                                           NumElts));
12774
12775     // If we're dividing by a positive value, we're done.  Otherwise, we must
12776     // negate the result.
12777     if (SplatValue.isNonNegative())
12778       return SRA;
12779
12780     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12781     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12782     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12783   }
12784   return SDValue();
12785 }
12786
12787 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12788                                          const X86Subtarget *Subtarget) {
12789   MVT VT = Op.getSimpleValueType();
12790   SDLoc dl(Op);
12791   SDValue R = Op.getOperand(0);
12792   SDValue Amt = Op.getOperand(1);
12793
12794   // Optimize shl/srl/sra with constant shift amount.
12795   if (isSplatVector(Amt.getNode())) {
12796     SDValue SclrAmt = Amt->getOperand(0);
12797     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12798       uint64_t ShiftAmt = C->getZExtValue();
12799
12800       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12801           (Subtarget->hasInt256() &&
12802            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12803           (Subtarget->hasAVX512() &&
12804            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12805         if (Op.getOpcode() == ISD::SHL)
12806           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12807                                             DAG);
12808         if (Op.getOpcode() == ISD::SRL)
12809           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12810                                             DAG);
12811         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12812           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12813                                             DAG);
12814       }
12815
12816       if (VT == MVT::v16i8) {
12817         if (Op.getOpcode() == ISD::SHL) {
12818           // Make a large shift.
12819           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12820                                                    MVT::v8i16, R, ShiftAmt,
12821                                                    DAG);
12822           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12823           // Zero out the rightmost bits.
12824           SmallVector<SDValue, 16> V(16,
12825                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12826                                                      MVT::i8));
12827           return DAG.getNode(ISD::AND, dl, VT, SHL,
12828                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12829         }
12830         if (Op.getOpcode() == ISD::SRL) {
12831           // Make a large shift.
12832           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12833                                                    MVT::v8i16, R, ShiftAmt,
12834                                                    DAG);
12835           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12836           // Zero out the leftmost bits.
12837           SmallVector<SDValue, 16> V(16,
12838                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12839                                                      MVT::i8));
12840           return DAG.getNode(ISD::AND, dl, VT, SRL,
12841                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12842         }
12843         if (Op.getOpcode() == ISD::SRA) {
12844           if (ShiftAmt == 7) {
12845             // R s>> 7  ===  R s< 0
12846             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12847             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12848           }
12849
12850           // R s>> a === ((R u>> a) ^ m) - m
12851           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12852           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12853                                                          MVT::i8));
12854           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12855           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12856           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12857           return Res;
12858         }
12859         llvm_unreachable("Unknown shift opcode.");
12860       }
12861
12862       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12863         if (Op.getOpcode() == ISD::SHL) {
12864           // Make a large shift.
12865           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12866                                                    MVT::v16i16, R, ShiftAmt,
12867                                                    DAG);
12868           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12869           // Zero out the rightmost bits.
12870           SmallVector<SDValue, 32> V(32,
12871                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12872                                                      MVT::i8));
12873           return DAG.getNode(ISD::AND, dl, VT, SHL,
12874                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12875         }
12876         if (Op.getOpcode() == ISD::SRL) {
12877           // Make a large shift.
12878           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12879                                                    MVT::v16i16, R, ShiftAmt,
12880                                                    DAG);
12881           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12882           // Zero out the leftmost bits.
12883           SmallVector<SDValue, 32> V(32,
12884                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12885                                                      MVT::i8));
12886           return DAG.getNode(ISD::AND, dl, VT, SRL,
12887                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12888         }
12889         if (Op.getOpcode() == ISD::SRA) {
12890           if (ShiftAmt == 7) {
12891             // R s>> 7  ===  R s< 0
12892             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12893             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12894           }
12895
12896           // R s>> a === ((R u>> a) ^ m) - m
12897           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12898           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12899                                                          MVT::i8));
12900           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12901           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12902           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12903           return Res;
12904         }
12905         llvm_unreachable("Unknown shift opcode.");
12906       }
12907     }
12908   }
12909
12910   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12911   if (!Subtarget->is64Bit() &&
12912       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12913       Amt.getOpcode() == ISD::BITCAST &&
12914       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12915     Amt = Amt.getOperand(0);
12916     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
12917                      VT.getVectorNumElements();
12918     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12919     uint64_t ShiftAmt = 0;
12920     for (unsigned i = 0; i != Ratio; ++i) {
12921       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12922       if (C == 0)
12923         return SDValue();
12924       // 6 == Log2(64)
12925       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12926     }
12927     // Check remaining shift amounts.
12928     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12929       uint64_t ShAmt = 0;
12930       for (unsigned j = 0; j != Ratio; ++j) {
12931         ConstantSDNode *C =
12932           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12933         if (C == 0)
12934           return SDValue();
12935         // 6 == Log2(64)
12936         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12937       }
12938       if (ShAmt != ShiftAmt)
12939         return SDValue();
12940     }
12941     switch (Op.getOpcode()) {
12942     default:
12943       llvm_unreachable("Unknown shift opcode!");
12944     case ISD::SHL:
12945       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12946                                         DAG);
12947     case ISD::SRL:
12948       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12949                                         DAG);
12950     case ISD::SRA:
12951       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12952                                         DAG);
12953     }
12954   }
12955
12956   return SDValue();
12957 }
12958
12959 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12960                                         const X86Subtarget* Subtarget) {
12961   MVT VT = Op.getSimpleValueType();
12962   SDLoc dl(Op);
12963   SDValue R = Op.getOperand(0);
12964   SDValue Amt = Op.getOperand(1);
12965
12966   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12967       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12968       (Subtarget->hasInt256() &&
12969        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12970         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12971        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12972     SDValue BaseShAmt;
12973     EVT EltVT = VT.getVectorElementType();
12974
12975     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12976       unsigned NumElts = VT.getVectorNumElements();
12977       unsigned i, j;
12978       for (i = 0; i != NumElts; ++i) {
12979         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12980           continue;
12981         break;
12982       }
12983       for (j = i; j != NumElts; ++j) {
12984         SDValue Arg = Amt.getOperand(j);
12985         if (Arg.getOpcode() == ISD::UNDEF) continue;
12986         if (Arg != Amt.getOperand(i))
12987           break;
12988       }
12989       if (i != NumElts && j == NumElts)
12990         BaseShAmt = Amt.getOperand(i);
12991     } else {
12992       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12993         Amt = Amt.getOperand(0);
12994       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12995                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12996         SDValue InVec = Amt.getOperand(0);
12997         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12998           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12999           unsigned i = 0;
13000           for (; i != NumElts; ++i) {
13001             SDValue Arg = InVec.getOperand(i);
13002             if (Arg.getOpcode() == ISD::UNDEF) continue;
13003             BaseShAmt = Arg;
13004             break;
13005           }
13006         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13007            if (ConstantSDNode *C =
13008                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13009              unsigned SplatIdx =
13010                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13011              if (C->getZExtValue() == SplatIdx)
13012                BaseShAmt = InVec.getOperand(1);
13013            }
13014         }
13015         if (BaseShAmt.getNode() == 0)
13016           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13017                                   DAG.getIntPtrConstant(0));
13018       }
13019     }
13020
13021     if (BaseShAmt.getNode()) {
13022       if (EltVT.bitsGT(MVT::i32))
13023         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13024       else if (EltVT.bitsLT(MVT::i32))
13025         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13026
13027       switch (Op.getOpcode()) {
13028       default:
13029         llvm_unreachable("Unknown shift opcode!");
13030       case ISD::SHL:
13031         switch (VT.SimpleTy) {
13032         default: return SDValue();
13033         case MVT::v2i64:
13034         case MVT::v4i32:
13035         case MVT::v8i16:
13036         case MVT::v4i64:
13037         case MVT::v8i32:
13038         case MVT::v16i16:
13039         case MVT::v16i32:
13040         case MVT::v8i64:
13041           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13042         }
13043       case ISD::SRA:
13044         switch (VT.SimpleTy) {
13045         default: return SDValue();
13046         case MVT::v4i32:
13047         case MVT::v8i16:
13048         case MVT::v8i32:
13049         case MVT::v16i16:
13050         case MVT::v16i32:
13051         case MVT::v8i64:
13052           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13053         }
13054       case ISD::SRL:
13055         switch (VT.SimpleTy) {
13056         default: return SDValue();
13057         case MVT::v2i64:
13058         case MVT::v4i32:
13059         case MVT::v8i16:
13060         case MVT::v4i64:
13061         case MVT::v8i32:
13062         case MVT::v16i16:
13063         case MVT::v16i32:
13064         case MVT::v8i64:
13065           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13066         }
13067       }
13068     }
13069   }
13070
13071   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13072   if (!Subtarget->is64Bit() &&
13073       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13074       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13075       Amt.getOpcode() == ISD::BITCAST &&
13076       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13077     Amt = Amt.getOperand(0);
13078     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13079                      VT.getVectorNumElements();
13080     std::vector<SDValue> Vals(Ratio);
13081     for (unsigned i = 0; i != Ratio; ++i)
13082       Vals[i] = Amt.getOperand(i);
13083     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13084       for (unsigned j = 0; j != Ratio; ++j)
13085         if (Vals[j] != Amt.getOperand(i + j))
13086           return SDValue();
13087     }
13088     switch (Op.getOpcode()) {
13089     default:
13090       llvm_unreachable("Unknown shift opcode!");
13091     case ISD::SHL:
13092       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13093     case ISD::SRL:
13094       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13095     case ISD::SRA:
13096       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13097     }
13098   }
13099
13100   return SDValue();
13101 }
13102
13103 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13104                           SelectionDAG &DAG) {
13105
13106   MVT VT = Op.getSimpleValueType();
13107   SDLoc dl(Op);
13108   SDValue R = Op.getOperand(0);
13109   SDValue Amt = Op.getOperand(1);
13110   SDValue V;
13111
13112   if (!Subtarget->hasSSE2())
13113     return SDValue();
13114
13115   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13116   if (V.getNode())
13117     return V;
13118
13119   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13120   if (V.getNode())
13121       return V;
13122
13123   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13124     return Op;
13125   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13126   if (Subtarget->hasInt256()) {
13127     if (Op.getOpcode() == ISD::SRL &&
13128         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13129          VT == MVT::v4i64 || VT == MVT::v8i32))
13130       return Op;
13131     if (Op.getOpcode() == ISD::SHL &&
13132         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13133          VT == MVT::v4i64 || VT == MVT::v8i32))
13134       return Op;
13135     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13136       return Op;
13137   }
13138
13139   // Lower SHL with variable shift amount.
13140   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13141     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13142
13143     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13144     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13145     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13146     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13147   }
13148   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13149     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13150
13151     // a = a << 5;
13152     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13153     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13154
13155     // Turn 'a' into a mask suitable for VSELECT
13156     SDValue VSelM = DAG.getConstant(0x80, VT);
13157     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13158     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13159
13160     SDValue CM1 = DAG.getConstant(0x0f, VT);
13161     SDValue CM2 = DAG.getConstant(0x3f, VT);
13162
13163     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13164     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13165     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13166     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13167     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13168
13169     // a += a
13170     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13171     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13172     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13173
13174     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13175     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13176     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13177     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13178     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13179
13180     // a += a
13181     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13182     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13183     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13184
13185     // return VSELECT(r, r+r, a);
13186     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13187                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13188     return R;
13189   }
13190
13191   // Decompose 256-bit shifts into smaller 128-bit shifts.
13192   if (VT.is256BitVector()) {
13193     unsigned NumElems = VT.getVectorNumElements();
13194     MVT EltVT = VT.getVectorElementType();
13195     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13196
13197     // Extract the two vectors
13198     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13199     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13200
13201     // Recreate the shift amount vectors
13202     SDValue Amt1, Amt2;
13203     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13204       // Constant shift amount
13205       SmallVector<SDValue, 4> Amt1Csts;
13206       SmallVector<SDValue, 4> Amt2Csts;
13207       for (unsigned i = 0; i != NumElems/2; ++i)
13208         Amt1Csts.push_back(Amt->getOperand(i));
13209       for (unsigned i = NumElems/2; i != NumElems; ++i)
13210         Amt2Csts.push_back(Amt->getOperand(i));
13211
13212       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13213                                  &Amt1Csts[0], NumElems/2);
13214       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13215                                  &Amt2Csts[0], NumElems/2);
13216     } else {
13217       // Variable shift amount
13218       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13219       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13220     }
13221
13222     // Issue new vector shifts for the smaller types
13223     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13224     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13225
13226     // Concatenate the result back
13227     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13228   }
13229
13230   return SDValue();
13231 }
13232
13233 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13234   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13235   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13236   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13237   // has only one use.
13238   SDNode *N = Op.getNode();
13239   SDValue LHS = N->getOperand(0);
13240   SDValue RHS = N->getOperand(1);
13241   unsigned BaseOp = 0;
13242   unsigned Cond = 0;
13243   SDLoc DL(Op);
13244   switch (Op.getOpcode()) {
13245   default: llvm_unreachable("Unknown ovf instruction!");
13246   case ISD::SADDO:
13247     // A subtract of one will be selected as a INC. Note that INC doesn't
13248     // set CF, so we can't do this for UADDO.
13249     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13250       if (C->isOne()) {
13251         BaseOp = X86ISD::INC;
13252         Cond = X86::COND_O;
13253         break;
13254       }
13255     BaseOp = X86ISD::ADD;
13256     Cond = X86::COND_O;
13257     break;
13258   case ISD::UADDO:
13259     BaseOp = X86ISD::ADD;
13260     Cond = X86::COND_B;
13261     break;
13262   case ISD::SSUBO:
13263     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13264     // set CF, so we can't do this for USUBO.
13265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13266       if (C->isOne()) {
13267         BaseOp = X86ISD::DEC;
13268         Cond = X86::COND_O;
13269         break;
13270       }
13271     BaseOp = X86ISD::SUB;
13272     Cond = X86::COND_O;
13273     break;
13274   case ISD::USUBO:
13275     BaseOp = X86ISD::SUB;
13276     Cond = X86::COND_B;
13277     break;
13278   case ISD::SMULO:
13279     BaseOp = X86ISD::SMUL;
13280     Cond = X86::COND_O;
13281     break;
13282   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13283     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13284                                  MVT::i32);
13285     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13286
13287     SDValue SetCC =
13288       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13289                   DAG.getConstant(X86::COND_O, MVT::i32),
13290                   SDValue(Sum.getNode(), 2));
13291
13292     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13293   }
13294   }
13295
13296   // Also sets EFLAGS.
13297   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13298   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13299
13300   SDValue SetCC =
13301     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13302                 DAG.getConstant(Cond, MVT::i32),
13303                 SDValue(Sum.getNode(), 1));
13304
13305   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13306 }
13307
13308 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13309                                                   SelectionDAG &DAG) const {
13310   SDLoc dl(Op);
13311   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13312   MVT VT = Op.getSimpleValueType();
13313
13314   if (!Subtarget->hasSSE2() || !VT.isVector())
13315     return SDValue();
13316
13317   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13318                       ExtraVT.getScalarType().getSizeInBits();
13319
13320   switch (VT.SimpleTy) {
13321     default: return SDValue();
13322     case MVT::v8i32:
13323     case MVT::v16i16:
13324       if (!Subtarget->hasFp256())
13325         return SDValue();
13326       if (!Subtarget->hasInt256()) {
13327         // needs to be split
13328         unsigned NumElems = VT.getVectorNumElements();
13329
13330         // Extract the LHS vectors
13331         SDValue LHS = Op.getOperand(0);
13332         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13333         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13334
13335         MVT EltVT = VT.getVectorElementType();
13336         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13337
13338         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13339         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13340         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13341                                    ExtraNumElems/2);
13342         SDValue Extra = DAG.getValueType(ExtraVT);
13343
13344         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13345         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13346
13347         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13348       }
13349       // fall through
13350     case MVT::v4i32:
13351     case MVT::v8i16: {
13352       SDValue Op0 = Op.getOperand(0);
13353       SDValue Op00 = Op0.getOperand(0);
13354       SDValue Tmp1;
13355       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13356       if (Op0.getOpcode() == ISD::BITCAST &&
13357           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13358         // (sext (vzext x)) -> (vsext x)
13359         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13360         if (Tmp1.getNode()) {
13361           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13362           // This folding is only valid when the in-reg type is a vector of i8,
13363           // i16, or i32.
13364           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13365               ExtraEltVT == MVT::i32) {
13366             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13367             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13368                    "This optimization is invalid without a VZEXT.");
13369             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13370           }
13371           Op0 = Tmp1;
13372         }
13373       }
13374
13375       // If the above didn't work, then just use Shift-Left + Shift-Right.
13376       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13377                                         DAG);
13378       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13379                                         DAG);
13380     }
13381   }
13382 }
13383
13384 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13385                                  SelectionDAG &DAG) {
13386   SDLoc dl(Op);
13387   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13388     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13389   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13390     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13391
13392   // The only fence that needs an instruction is a sequentially-consistent
13393   // cross-thread fence.
13394   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13395     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13396     // no-sse2). There isn't any reason to disable it if the target processor
13397     // supports it.
13398     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13399       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13400
13401     SDValue Chain = Op.getOperand(0);
13402     SDValue Zero = DAG.getConstant(0, MVT::i32);
13403     SDValue Ops[] = {
13404       DAG.getRegister(X86::ESP, MVT::i32), // Base
13405       DAG.getTargetConstant(1, MVT::i8),   // Scale
13406       DAG.getRegister(0, MVT::i32),        // Index
13407       DAG.getTargetConstant(0, MVT::i32),  // Disp
13408       DAG.getRegister(0, MVT::i32),        // Segment.
13409       Zero,
13410       Chain
13411     };
13412     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13413     return SDValue(Res, 0);
13414   }
13415
13416   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13417   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13418 }
13419
13420 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13421                              SelectionDAG &DAG) {
13422   MVT T = Op.getSimpleValueType();
13423   SDLoc DL(Op);
13424   unsigned Reg = 0;
13425   unsigned size = 0;
13426   switch(T.SimpleTy) {
13427   default: llvm_unreachable("Invalid value type!");
13428   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13429   case MVT::i16: Reg = X86::AX;  size = 2; break;
13430   case MVT::i32: Reg = X86::EAX; size = 4; break;
13431   case MVT::i64:
13432     assert(Subtarget->is64Bit() && "Node not type legal!");
13433     Reg = X86::RAX; size = 8;
13434     break;
13435   }
13436   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13437                                     Op.getOperand(2), SDValue());
13438   SDValue Ops[] = { cpIn.getValue(0),
13439                     Op.getOperand(1),
13440                     Op.getOperand(3),
13441                     DAG.getTargetConstant(size, MVT::i8),
13442                     cpIn.getValue(1) };
13443   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13444   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13445   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13446                                            Ops, array_lengthof(Ops), T, MMO);
13447   SDValue cpOut =
13448     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13449   return cpOut;
13450 }
13451
13452 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13453                                      SelectionDAG &DAG) {
13454   assert(Subtarget->is64Bit() && "Result not type legalized?");
13455   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13456   SDValue TheChain = Op.getOperand(0);
13457   SDLoc dl(Op);
13458   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13459   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13460   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13461                                    rax.getValue(2));
13462   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13463                             DAG.getConstant(32, MVT::i8));
13464   SDValue Ops[] = {
13465     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13466     rdx.getValue(1)
13467   };
13468   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13469 }
13470
13471 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13472                             SelectionDAG &DAG) {
13473   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13474   MVT DstVT = Op.getSimpleValueType();
13475   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13476          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13477   assert((DstVT == MVT::i64 ||
13478           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13479          "Unexpected custom BITCAST");
13480   // i64 <=> MMX conversions are Legal.
13481   if (SrcVT==MVT::i64 && DstVT.isVector())
13482     return Op;
13483   if (DstVT==MVT::i64 && SrcVT.isVector())
13484     return Op;
13485   // MMX <=> MMX conversions are Legal.
13486   if (SrcVT.isVector() && DstVT.isVector())
13487     return Op;
13488   // All other conversions need to be expanded.
13489   return SDValue();
13490 }
13491
13492 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13493   SDNode *Node = Op.getNode();
13494   SDLoc dl(Node);
13495   EVT T = Node->getValueType(0);
13496   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13497                               DAG.getConstant(0, T), Node->getOperand(2));
13498   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13499                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13500                        Node->getOperand(0),
13501                        Node->getOperand(1), negOp,
13502                        cast<AtomicSDNode>(Node)->getSrcValue(),
13503                        cast<AtomicSDNode>(Node)->getAlignment(),
13504                        cast<AtomicSDNode>(Node)->getOrdering(),
13505                        cast<AtomicSDNode>(Node)->getSynchScope());
13506 }
13507
13508 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13509   SDNode *Node = Op.getNode();
13510   SDLoc dl(Node);
13511   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13512
13513   // Convert seq_cst store -> xchg
13514   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13515   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13516   //        (The only way to get a 16-byte store is cmpxchg16b)
13517   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13518   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13519       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13520     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13521                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13522                                  Node->getOperand(0),
13523                                  Node->getOperand(1), Node->getOperand(2),
13524                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13525                                  cast<AtomicSDNode>(Node)->getOrdering(),
13526                                  cast<AtomicSDNode>(Node)->getSynchScope());
13527     return Swap.getValue(1);
13528   }
13529   // Other atomic stores have a simple pattern.
13530   return Op;
13531 }
13532
13533 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13534   EVT VT = Op.getNode()->getSimpleValueType(0);
13535
13536   // Let legalize expand this if it isn't a legal type yet.
13537   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13538     return SDValue();
13539
13540   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13541
13542   unsigned Opc;
13543   bool ExtraOp = false;
13544   switch (Op.getOpcode()) {
13545   default: llvm_unreachable("Invalid code");
13546   case ISD::ADDC: Opc = X86ISD::ADD; break;
13547   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13548   case ISD::SUBC: Opc = X86ISD::SUB; break;
13549   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13550   }
13551
13552   if (!ExtraOp)
13553     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13554                        Op.getOperand(1));
13555   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13556                      Op.getOperand(1), Op.getOperand(2));
13557 }
13558
13559 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13560                             SelectionDAG &DAG) {
13561   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13562
13563   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13564   // which returns the values as { float, float } (in XMM0) or
13565   // { double, double } (which is returned in XMM0, XMM1).
13566   SDLoc dl(Op);
13567   SDValue Arg = Op.getOperand(0);
13568   EVT ArgVT = Arg.getValueType();
13569   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13570
13571   TargetLowering::ArgListTy Args;
13572   TargetLowering::ArgListEntry Entry;
13573
13574   Entry.Node = Arg;
13575   Entry.Ty = ArgTy;
13576   Entry.isSExt = false;
13577   Entry.isZExt = false;
13578   Args.push_back(Entry);
13579
13580   bool isF64 = ArgVT == MVT::f64;
13581   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13582   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13583   // the results are returned via SRet in memory.
13584   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13586   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13587
13588   Type *RetTy = isF64
13589     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13590     : (Type*)VectorType::get(ArgTy, 4);
13591   TargetLowering::
13592     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13593                          false, false, false, false, 0,
13594                          CallingConv::C, /*isTaillCall=*/false,
13595                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13596                          Callee, Args, DAG, dl);
13597   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13598
13599   if (isF64)
13600     // Returned in xmm0 and xmm1.
13601     return CallResult.first;
13602
13603   // Returned in bits 0:31 and 32:64 xmm0.
13604   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13605                                CallResult.first, DAG.getIntPtrConstant(0));
13606   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13607                                CallResult.first, DAG.getIntPtrConstant(1));
13608   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13609   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13610 }
13611
13612 /// LowerOperation - Provide custom lowering hooks for some operations.
13613 ///
13614 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13615   switch (Op.getOpcode()) {
13616   default: llvm_unreachable("Should not custom lower this!");
13617   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13618   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13619   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13620   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13621   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13622   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13623   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13624   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13625   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13626   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13627   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13628   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13629   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13630   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13631   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13632   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13633   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13634   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13635   case ISD::SHL_PARTS:
13636   case ISD::SRA_PARTS:
13637   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13638   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13639   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13640   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13641   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13642   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13643   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13644   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13645   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13646   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13647   case ISD::FABS:               return LowerFABS(Op, DAG);
13648   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13649   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13650   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13651   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13652   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13653   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13654   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13655   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13656   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13657   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13658   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13659   case ISD::INTRINSIC_VOID:
13660   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13661   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13662   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13663   case ISD::FRAME_TO_ARGS_OFFSET:
13664                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13665   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13666   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13667   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13668   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13669   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13670   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13671   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13672   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13673   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13674   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13675   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13676   case ISD::SRA:
13677   case ISD::SRL:
13678   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13679   case ISD::SADDO:
13680   case ISD::UADDO:
13681   case ISD::SSUBO:
13682   case ISD::USUBO:
13683   case ISD::SMULO:
13684   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13685   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13686   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13687   case ISD::ADDC:
13688   case ISD::ADDE:
13689   case ISD::SUBC:
13690   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13691   case ISD::ADD:                return LowerADD(Op, DAG);
13692   case ISD::SUB:                return LowerSUB(Op, DAG);
13693   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13694   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13695   }
13696 }
13697
13698 static void ReplaceATOMIC_LOAD(SDNode *Node,
13699                                   SmallVectorImpl<SDValue> &Results,
13700                                   SelectionDAG &DAG) {
13701   SDLoc dl(Node);
13702   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13703
13704   // Convert wide load -> cmpxchg8b/cmpxchg16b
13705   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13706   //        (The only way to get a 16-byte load is cmpxchg16b)
13707   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13708   SDValue Zero = DAG.getConstant(0, VT);
13709   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13710                                Node->getOperand(0),
13711                                Node->getOperand(1), Zero, Zero,
13712                                cast<AtomicSDNode>(Node)->getMemOperand(),
13713                                cast<AtomicSDNode>(Node)->getOrdering(),
13714                                cast<AtomicSDNode>(Node)->getSynchScope());
13715   Results.push_back(Swap.getValue(0));
13716   Results.push_back(Swap.getValue(1));
13717 }
13718
13719 static void
13720 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13721                         SelectionDAG &DAG, unsigned NewOp) {
13722   SDLoc dl(Node);
13723   assert (Node->getValueType(0) == MVT::i64 &&
13724           "Only know how to expand i64 atomics");
13725
13726   SDValue Chain = Node->getOperand(0);
13727   SDValue In1 = Node->getOperand(1);
13728   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13729                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13730   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13731                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13732   SDValue Ops[] = { Chain, In1, In2L, In2H };
13733   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13734   SDValue Result =
13735     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13736                             cast<MemSDNode>(Node)->getMemOperand());
13737   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13738   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13739   Results.push_back(Result.getValue(2));
13740 }
13741
13742 /// ReplaceNodeResults - Replace a node with an illegal result type
13743 /// with a new node built out of custom code.
13744 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13745                                            SmallVectorImpl<SDValue>&Results,
13746                                            SelectionDAG &DAG) const {
13747   SDLoc dl(N);
13748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13749   switch (N->getOpcode()) {
13750   default:
13751     llvm_unreachable("Do not know how to custom type legalize this operation!");
13752   case ISD::SIGN_EXTEND_INREG:
13753   case ISD::ADDC:
13754   case ISD::ADDE:
13755   case ISD::SUBC:
13756   case ISD::SUBE:
13757     // We don't want to expand or promote these.
13758     return;
13759   case ISD::FP_TO_SINT:
13760   case ISD::FP_TO_UINT: {
13761     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13762
13763     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13764       return;
13765
13766     std::pair<SDValue,SDValue> Vals =
13767         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13768     SDValue FIST = Vals.first, StackSlot = Vals.second;
13769     if (FIST.getNode() != 0) {
13770       EVT VT = N->getValueType(0);
13771       // Return a load from the stack slot.
13772       if (StackSlot.getNode() != 0)
13773         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13774                                       MachinePointerInfo(),
13775                                       false, false, false, 0));
13776       else
13777         Results.push_back(FIST);
13778     }
13779     return;
13780   }
13781   case ISD::UINT_TO_FP: {
13782     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13783     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13784         N->getValueType(0) != MVT::v2f32)
13785       return;
13786     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13787                                  N->getOperand(0));
13788     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13789                                      MVT::f64);
13790     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13791     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13792                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13793     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13794     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13795     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13796     return;
13797   }
13798   case ISD::FP_ROUND: {
13799     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13800         return;
13801     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13802     Results.push_back(V);
13803     return;
13804   }
13805   case ISD::READCYCLECOUNTER: {
13806     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13807     SDValue TheChain = N->getOperand(0);
13808     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13809     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13810                                      rd.getValue(1));
13811     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13812                                      eax.getValue(2));
13813     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13814     SDValue Ops[] = { eax, edx };
13815     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13816                                   array_lengthof(Ops)));
13817     Results.push_back(edx.getValue(1));
13818     return;
13819   }
13820   case ISD::ATOMIC_CMP_SWAP: {
13821     EVT T = N->getValueType(0);
13822     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13823     bool Regs64bit = T == MVT::i128;
13824     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13825     SDValue cpInL, cpInH;
13826     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13827                         DAG.getConstant(0, HalfT));
13828     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13829                         DAG.getConstant(1, HalfT));
13830     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13831                              Regs64bit ? X86::RAX : X86::EAX,
13832                              cpInL, SDValue());
13833     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13834                              Regs64bit ? X86::RDX : X86::EDX,
13835                              cpInH, cpInL.getValue(1));
13836     SDValue swapInL, swapInH;
13837     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13838                           DAG.getConstant(0, HalfT));
13839     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13840                           DAG.getConstant(1, HalfT));
13841     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13842                                Regs64bit ? X86::RBX : X86::EBX,
13843                                swapInL, cpInH.getValue(1));
13844     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13845                                Regs64bit ? X86::RCX : X86::ECX,
13846                                swapInH, swapInL.getValue(1));
13847     SDValue Ops[] = { swapInH.getValue(0),
13848                       N->getOperand(1),
13849                       swapInH.getValue(1) };
13850     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13851     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13852     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13853                                   X86ISD::LCMPXCHG8_DAG;
13854     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13855                                              Ops, array_lengthof(Ops), T, MMO);
13856     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13857                                         Regs64bit ? X86::RAX : X86::EAX,
13858                                         HalfT, Result.getValue(1));
13859     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13860                                         Regs64bit ? X86::RDX : X86::EDX,
13861                                         HalfT, cpOutL.getValue(2));
13862     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13863     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13864     Results.push_back(cpOutH.getValue(1));
13865     return;
13866   }
13867   case ISD::ATOMIC_LOAD_ADD:
13868   case ISD::ATOMIC_LOAD_AND:
13869   case ISD::ATOMIC_LOAD_NAND:
13870   case ISD::ATOMIC_LOAD_OR:
13871   case ISD::ATOMIC_LOAD_SUB:
13872   case ISD::ATOMIC_LOAD_XOR:
13873   case ISD::ATOMIC_LOAD_MAX:
13874   case ISD::ATOMIC_LOAD_MIN:
13875   case ISD::ATOMIC_LOAD_UMAX:
13876   case ISD::ATOMIC_LOAD_UMIN:
13877   case ISD::ATOMIC_SWAP: {
13878     unsigned Opc;
13879     switch (N->getOpcode()) {
13880     default: llvm_unreachable("Unexpected opcode");
13881     case ISD::ATOMIC_LOAD_ADD:
13882       Opc = X86ISD::ATOMADD64_DAG;
13883       break;
13884     case ISD::ATOMIC_LOAD_AND:
13885       Opc = X86ISD::ATOMAND64_DAG;
13886       break;
13887     case ISD::ATOMIC_LOAD_NAND:
13888       Opc = X86ISD::ATOMNAND64_DAG;
13889       break;
13890     case ISD::ATOMIC_LOAD_OR:
13891       Opc = X86ISD::ATOMOR64_DAG;
13892       break;
13893     case ISD::ATOMIC_LOAD_SUB:
13894       Opc = X86ISD::ATOMSUB64_DAG;
13895       break;
13896     case ISD::ATOMIC_LOAD_XOR:
13897       Opc = X86ISD::ATOMXOR64_DAG;
13898       break;
13899     case ISD::ATOMIC_LOAD_MAX:
13900       Opc = X86ISD::ATOMMAX64_DAG;
13901       break;
13902     case ISD::ATOMIC_LOAD_MIN:
13903       Opc = X86ISD::ATOMMIN64_DAG;
13904       break;
13905     case ISD::ATOMIC_LOAD_UMAX:
13906       Opc = X86ISD::ATOMUMAX64_DAG;
13907       break;
13908     case ISD::ATOMIC_LOAD_UMIN:
13909       Opc = X86ISD::ATOMUMIN64_DAG;
13910       break;
13911     case ISD::ATOMIC_SWAP:
13912       Opc = X86ISD::ATOMSWAP64_DAG;
13913       break;
13914     }
13915     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13916     return;
13917   }
13918   case ISD::ATOMIC_LOAD:
13919     ReplaceATOMIC_LOAD(N, Results, DAG);
13920   }
13921 }
13922
13923 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13924   switch (Opcode) {
13925   default: return NULL;
13926   case X86ISD::BSF:                return "X86ISD::BSF";
13927   case X86ISD::BSR:                return "X86ISD::BSR";
13928   case X86ISD::SHLD:               return "X86ISD::SHLD";
13929   case X86ISD::SHRD:               return "X86ISD::SHRD";
13930   case X86ISD::FAND:               return "X86ISD::FAND";
13931   case X86ISD::FANDN:              return "X86ISD::FANDN";
13932   case X86ISD::FOR:                return "X86ISD::FOR";
13933   case X86ISD::FXOR:               return "X86ISD::FXOR";
13934   case X86ISD::FSRL:               return "X86ISD::FSRL";
13935   case X86ISD::FILD:               return "X86ISD::FILD";
13936   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13937   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13938   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13939   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13940   case X86ISD::FLD:                return "X86ISD::FLD";
13941   case X86ISD::FST:                return "X86ISD::FST";
13942   case X86ISD::CALL:               return "X86ISD::CALL";
13943   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13944   case X86ISD::BT:                 return "X86ISD::BT";
13945   case X86ISD::CMP:                return "X86ISD::CMP";
13946   case X86ISD::COMI:               return "X86ISD::COMI";
13947   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13948   case X86ISD::CMPM:               return "X86ISD::CMPM";
13949   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13950   case X86ISD::SETCC:              return "X86ISD::SETCC";
13951   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13952   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
13953   case X86ISD::CMOV:               return "X86ISD::CMOV";
13954   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13955   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13956   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13957   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13958   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13959   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13960   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13961   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13962   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13963   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13964   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13965   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13966   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13967   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13968   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13969   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13970   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13971   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13972   case X86ISD::HADD:               return "X86ISD::HADD";
13973   case X86ISD::HSUB:               return "X86ISD::HSUB";
13974   case X86ISD::FHADD:              return "X86ISD::FHADD";
13975   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13976   case X86ISD::UMAX:               return "X86ISD::UMAX";
13977   case X86ISD::UMIN:               return "X86ISD::UMIN";
13978   case X86ISD::SMAX:               return "X86ISD::SMAX";
13979   case X86ISD::SMIN:               return "X86ISD::SMIN";
13980   case X86ISD::FMAX:               return "X86ISD::FMAX";
13981   case X86ISD::FMIN:               return "X86ISD::FMIN";
13982   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13983   case X86ISD::FMINC:              return "X86ISD::FMINC";
13984   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13985   case X86ISD::FRCP:               return "X86ISD::FRCP";
13986   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13987   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13988   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13989   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13990   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13991   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13992   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13993   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13994   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13995   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13996   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13997   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13998   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13999   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14000   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14001   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14002   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14003   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14004   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
14005   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14006   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14007   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14008   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14009   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14010   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14011   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14012   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14013   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14014   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14015   case X86ISD::VSHL:               return "X86ISD::VSHL";
14016   case X86ISD::VSRL:               return "X86ISD::VSRL";
14017   case X86ISD::VSRA:               return "X86ISD::VSRA";
14018   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14019   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14020   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14021   case X86ISD::CMPP:               return "X86ISD::CMPP";
14022   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14023   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14024   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14025   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14026   case X86ISD::ADD:                return "X86ISD::ADD";
14027   case X86ISD::SUB:                return "X86ISD::SUB";
14028   case X86ISD::ADC:                return "X86ISD::ADC";
14029   case X86ISD::SBB:                return "X86ISD::SBB";
14030   case X86ISD::SMUL:               return "X86ISD::SMUL";
14031   case X86ISD::UMUL:               return "X86ISD::UMUL";
14032   case X86ISD::INC:                return "X86ISD::INC";
14033   case X86ISD::DEC:                return "X86ISD::DEC";
14034   case X86ISD::OR:                 return "X86ISD::OR";
14035   case X86ISD::XOR:                return "X86ISD::XOR";
14036   case X86ISD::AND:                return "X86ISD::AND";
14037   case X86ISD::BLSI:               return "X86ISD::BLSI";
14038   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
14039   case X86ISD::BLSR:               return "X86ISD::BLSR";
14040   case X86ISD::BZHI:               return "X86ISD::BZHI";
14041   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14042   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14043   case X86ISD::PTEST:              return "X86ISD::PTEST";
14044   case X86ISD::TESTP:              return "X86ISD::TESTP";
14045   case X86ISD::TESTM:              return "X86ISD::TESTM";
14046   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14047   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14048   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14049   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14050   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14051   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14052   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14053   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14054   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14055   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14056   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14057   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14058   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14059   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14060   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14061   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14062   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14063   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14064   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14065   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14066   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14067   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14068   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14069   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14070   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14071   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14072   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14073   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14074   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14075   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14076   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14077   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14078   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14079   case X86ISD::SAHF:               return "X86ISD::SAHF";
14080   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14081   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14082   case X86ISD::FMADD:              return "X86ISD::FMADD";
14083   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14084   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14085   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14086   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14087   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14088   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14089   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14090   case X86ISD::XTEST:              return "X86ISD::XTEST";
14091   }
14092 }
14093
14094 // isLegalAddressingMode - Return true if the addressing mode represented
14095 // by AM is legal for this target, for a load/store of the specified type.
14096 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14097                                               Type *Ty) const {
14098   // X86 supports extremely general addressing modes.
14099   CodeModel::Model M = getTargetMachine().getCodeModel();
14100   Reloc::Model R = getTargetMachine().getRelocationModel();
14101
14102   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14103   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14104     return false;
14105
14106   if (AM.BaseGV) {
14107     unsigned GVFlags =
14108       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14109
14110     // If a reference to this global requires an extra load, we can't fold it.
14111     if (isGlobalStubReference(GVFlags))
14112       return false;
14113
14114     // If BaseGV requires a register for the PIC base, we cannot also have a
14115     // BaseReg specified.
14116     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14117       return false;
14118
14119     // If lower 4G is not available, then we must use rip-relative addressing.
14120     if ((M != CodeModel::Small || R != Reloc::Static) &&
14121         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14122       return false;
14123   }
14124
14125   switch (AM.Scale) {
14126   case 0:
14127   case 1:
14128   case 2:
14129   case 4:
14130   case 8:
14131     // These scales always work.
14132     break;
14133   case 3:
14134   case 5:
14135   case 9:
14136     // These scales are formed with basereg+scalereg.  Only accept if there is
14137     // no basereg yet.
14138     if (AM.HasBaseReg)
14139       return false;
14140     break;
14141   default:  // Other stuff never works.
14142     return false;
14143   }
14144
14145   return true;
14146 }
14147
14148 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14149   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14150     return false;
14151   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14152   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14153   return NumBits1 > NumBits2;
14154 }
14155
14156 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14157   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14158     return false;
14159
14160   if (!isTypeLegal(EVT::getEVT(Ty1)))
14161     return false;
14162
14163   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14164
14165   // Assuming the caller doesn't have a zeroext or signext return parameter,
14166   // truncation all the way down to i1 is valid.
14167   return true;
14168 }
14169
14170 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14171   return isInt<32>(Imm);
14172 }
14173
14174 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14175   // Can also use sub to handle negated immediates.
14176   return isInt<32>(Imm);
14177 }
14178
14179 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14180   if (!VT1.isInteger() || !VT2.isInteger())
14181     return false;
14182   unsigned NumBits1 = VT1.getSizeInBits();
14183   unsigned NumBits2 = VT2.getSizeInBits();
14184   return NumBits1 > NumBits2;
14185 }
14186
14187 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14188   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14189   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14190 }
14191
14192 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14193   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14194   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14195 }
14196
14197 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14198   EVT VT1 = Val.getValueType();
14199   if (isZExtFree(VT1, VT2))
14200     return true;
14201
14202   if (Val.getOpcode() != ISD::LOAD)
14203     return false;
14204
14205   if (!VT1.isSimple() || !VT1.isInteger() ||
14206       !VT2.isSimple() || !VT2.isInteger())
14207     return false;
14208
14209   switch (VT1.getSimpleVT().SimpleTy) {
14210   default: break;
14211   case MVT::i8:
14212   case MVT::i16:
14213   case MVT::i32:
14214     // X86 has 8, 16, and 32-bit zero-extending loads.
14215     return true;
14216   }
14217
14218   return false;
14219 }
14220
14221 bool
14222 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14223   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14224     return false;
14225
14226   VT = VT.getScalarType();
14227
14228   if (!VT.isSimple())
14229     return false;
14230
14231   switch (VT.getSimpleVT().SimpleTy) {
14232   case MVT::f32:
14233   case MVT::f64:
14234     return true;
14235   default:
14236     break;
14237   }
14238
14239   return false;
14240 }
14241
14242 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14243   // i16 instructions are longer (0x66 prefix) and potentially slower.
14244   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14245 }
14246
14247 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14248 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14249 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14250 /// are assumed to be legal.
14251 bool
14252 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14253                                       EVT VT) const {
14254   if (!VT.isSimple())
14255     return false;
14256
14257   MVT SVT = VT.getSimpleVT();
14258
14259   // Very little shuffling can be done for 64-bit vectors right now.
14260   if (VT.getSizeInBits() == 64)
14261     return false;
14262
14263   // FIXME: pshufb, blends, shifts.
14264   return (SVT.getVectorNumElements() == 2 ||
14265           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14266           isMOVLMask(M, SVT) ||
14267           isSHUFPMask(M, SVT) ||
14268           isPSHUFDMask(M, SVT) ||
14269           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14270           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14271           isPALIGNRMask(M, SVT, Subtarget) ||
14272           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14273           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14274           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14275           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14276 }
14277
14278 bool
14279 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14280                                           EVT VT) const {
14281   if (!VT.isSimple())
14282     return false;
14283
14284   MVT SVT = VT.getSimpleVT();
14285   unsigned NumElts = SVT.getVectorNumElements();
14286   // FIXME: This collection of masks seems suspect.
14287   if (NumElts == 2)
14288     return true;
14289   if (NumElts == 4 && SVT.is128BitVector()) {
14290     return (isMOVLMask(Mask, SVT)  ||
14291             isCommutedMOVLMask(Mask, SVT, true) ||
14292             isSHUFPMask(Mask, SVT) ||
14293             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14294   }
14295   return false;
14296 }
14297
14298 //===----------------------------------------------------------------------===//
14299 //                           X86 Scheduler Hooks
14300 //===----------------------------------------------------------------------===//
14301
14302 /// Utility function to emit xbegin specifying the start of an RTM region.
14303 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14304                                      const TargetInstrInfo *TII) {
14305   DebugLoc DL = MI->getDebugLoc();
14306
14307   const BasicBlock *BB = MBB->getBasicBlock();
14308   MachineFunction::iterator I = MBB;
14309   ++I;
14310
14311   // For the v = xbegin(), we generate
14312   //
14313   // thisMBB:
14314   //  xbegin sinkMBB
14315   //
14316   // mainMBB:
14317   //  eax = -1
14318   //
14319   // sinkMBB:
14320   //  v = eax
14321
14322   MachineBasicBlock *thisMBB = MBB;
14323   MachineFunction *MF = MBB->getParent();
14324   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14325   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14326   MF->insert(I, mainMBB);
14327   MF->insert(I, sinkMBB);
14328
14329   // Transfer the remainder of BB and its successor edges to sinkMBB.
14330   sinkMBB->splice(sinkMBB->begin(), MBB,
14331                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14332   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14333
14334   // thisMBB:
14335   //  xbegin sinkMBB
14336   //  # fallthrough to mainMBB
14337   //  # abortion to sinkMBB
14338   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14339   thisMBB->addSuccessor(mainMBB);
14340   thisMBB->addSuccessor(sinkMBB);
14341
14342   // mainMBB:
14343   //  EAX = -1
14344   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14345   mainMBB->addSuccessor(sinkMBB);
14346
14347   // sinkMBB:
14348   // EAX is live into the sinkMBB
14349   sinkMBB->addLiveIn(X86::EAX);
14350   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14351           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14352     .addReg(X86::EAX);
14353
14354   MI->eraseFromParent();
14355   return sinkMBB;
14356 }
14357
14358 // Get CMPXCHG opcode for the specified data type.
14359 static unsigned getCmpXChgOpcode(EVT VT) {
14360   switch (VT.getSimpleVT().SimpleTy) {
14361   case MVT::i8:  return X86::LCMPXCHG8;
14362   case MVT::i16: return X86::LCMPXCHG16;
14363   case MVT::i32: return X86::LCMPXCHG32;
14364   case MVT::i64: return X86::LCMPXCHG64;
14365   default:
14366     break;
14367   }
14368   llvm_unreachable("Invalid operand size!");
14369 }
14370
14371 // Get LOAD opcode for the specified data type.
14372 static unsigned getLoadOpcode(EVT VT) {
14373   switch (VT.getSimpleVT().SimpleTy) {
14374   case MVT::i8:  return X86::MOV8rm;
14375   case MVT::i16: return X86::MOV16rm;
14376   case MVT::i32: return X86::MOV32rm;
14377   case MVT::i64: return X86::MOV64rm;
14378   default:
14379     break;
14380   }
14381   llvm_unreachable("Invalid operand size!");
14382 }
14383
14384 // Get opcode of the non-atomic one from the specified atomic instruction.
14385 static unsigned getNonAtomicOpcode(unsigned Opc) {
14386   switch (Opc) {
14387   case X86::ATOMAND8:  return X86::AND8rr;
14388   case X86::ATOMAND16: return X86::AND16rr;
14389   case X86::ATOMAND32: return X86::AND32rr;
14390   case X86::ATOMAND64: return X86::AND64rr;
14391   case X86::ATOMOR8:   return X86::OR8rr;
14392   case X86::ATOMOR16:  return X86::OR16rr;
14393   case X86::ATOMOR32:  return X86::OR32rr;
14394   case X86::ATOMOR64:  return X86::OR64rr;
14395   case X86::ATOMXOR8:  return X86::XOR8rr;
14396   case X86::ATOMXOR16: return X86::XOR16rr;
14397   case X86::ATOMXOR32: return X86::XOR32rr;
14398   case X86::ATOMXOR64: return X86::XOR64rr;
14399   }
14400   llvm_unreachable("Unhandled atomic-load-op opcode!");
14401 }
14402
14403 // Get opcode of the non-atomic one from the specified atomic instruction with
14404 // extra opcode.
14405 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14406                                                unsigned &ExtraOpc) {
14407   switch (Opc) {
14408   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14409   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14410   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14411   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14412   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14413   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14414   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14415   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14416   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14417   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14418   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14419   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14420   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14421   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14422   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14423   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14424   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14425   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14426   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14427   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14428   }
14429   llvm_unreachable("Unhandled atomic-load-op opcode!");
14430 }
14431
14432 // Get opcode of the non-atomic one from the specified atomic instruction for
14433 // 64-bit data type on 32-bit target.
14434 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14435   switch (Opc) {
14436   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14437   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14438   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14439   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14440   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14441   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14442   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14443   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14444   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14445   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14446   }
14447   llvm_unreachable("Unhandled atomic-load-op opcode!");
14448 }
14449
14450 // Get opcode of the non-atomic one from the specified atomic instruction for
14451 // 64-bit data type on 32-bit target with extra opcode.
14452 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14453                                                    unsigned &HiOpc,
14454                                                    unsigned &ExtraOpc) {
14455   switch (Opc) {
14456   case X86::ATOMNAND6432:
14457     ExtraOpc = X86::NOT32r;
14458     HiOpc = X86::AND32rr;
14459     return X86::AND32rr;
14460   }
14461   llvm_unreachable("Unhandled atomic-load-op opcode!");
14462 }
14463
14464 // Get pseudo CMOV opcode from the specified data type.
14465 static unsigned getPseudoCMOVOpc(EVT VT) {
14466   switch (VT.getSimpleVT().SimpleTy) {
14467   case MVT::i8:  return X86::CMOV_GR8;
14468   case MVT::i16: return X86::CMOV_GR16;
14469   case MVT::i32: return X86::CMOV_GR32;
14470   default:
14471     break;
14472   }
14473   llvm_unreachable("Unknown CMOV opcode!");
14474 }
14475
14476 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14477 // They will be translated into a spin-loop or compare-exchange loop from
14478 //
14479 //    ...
14480 //    dst = atomic-fetch-op MI.addr, MI.val
14481 //    ...
14482 //
14483 // to
14484 //
14485 //    ...
14486 //    t1 = LOAD MI.addr
14487 // loop:
14488 //    t4 = phi(t1, t3 / loop)
14489 //    t2 = OP MI.val, t4
14490 //    EAX = t4
14491 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14492 //    t3 = EAX
14493 //    JNE loop
14494 // sink:
14495 //    dst = t3
14496 //    ...
14497 MachineBasicBlock *
14498 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14499                                        MachineBasicBlock *MBB) const {
14500   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14501   DebugLoc DL = MI->getDebugLoc();
14502
14503   MachineFunction *MF = MBB->getParent();
14504   MachineRegisterInfo &MRI = MF->getRegInfo();
14505
14506   const BasicBlock *BB = MBB->getBasicBlock();
14507   MachineFunction::iterator I = MBB;
14508   ++I;
14509
14510   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14511          "Unexpected number of operands");
14512
14513   assert(MI->hasOneMemOperand() &&
14514          "Expected atomic-load-op to have one memoperand");
14515
14516   // Memory Reference
14517   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14518   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14519
14520   unsigned DstReg, SrcReg;
14521   unsigned MemOpndSlot;
14522
14523   unsigned CurOp = 0;
14524
14525   DstReg = MI->getOperand(CurOp++).getReg();
14526   MemOpndSlot = CurOp;
14527   CurOp += X86::AddrNumOperands;
14528   SrcReg = MI->getOperand(CurOp++).getReg();
14529
14530   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14531   MVT::SimpleValueType VT = *RC->vt_begin();
14532   unsigned t1 = MRI.createVirtualRegister(RC);
14533   unsigned t2 = MRI.createVirtualRegister(RC);
14534   unsigned t3 = MRI.createVirtualRegister(RC);
14535   unsigned t4 = MRI.createVirtualRegister(RC);
14536   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14537
14538   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14539   unsigned LOADOpc = getLoadOpcode(VT);
14540
14541   // For the atomic load-arith operator, we generate
14542   //
14543   //  thisMBB:
14544   //    t1 = LOAD [MI.addr]
14545   //  mainMBB:
14546   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14547   //    t1 = OP MI.val, EAX
14548   //    EAX = t4
14549   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14550   //    t3 = EAX
14551   //    JNE mainMBB
14552   //  sinkMBB:
14553   //    dst = t3
14554
14555   MachineBasicBlock *thisMBB = MBB;
14556   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14557   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14558   MF->insert(I, mainMBB);
14559   MF->insert(I, sinkMBB);
14560
14561   MachineInstrBuilder MIB;
14562
14563   // Transfer the remainder of BB and its successor edges to sinkMBB.
14564   sinkMBB->splice(sinkMBB->begin(), MBB,
14565                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14566   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14567
14568   // thisMBB:
14569   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14570   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14571     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14572     if (NewMO.isReg())
14573       NewMO.setIsKill(false);
14574     MIB.addOperand(NewMO);
14575   }
14576   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14577     unsigned flags = (*MMOI)->getFlags();
14578     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14579     MachineMemOperand *MMO =
14580       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14581                                (*MMOI)->getSize(),
14582                                (*MMOI)->getBaseAlignment(),
14583                                (*MMOI)->getTBAAInfo(),
14584                                (*MMOI)->getRanges());
14585     MIB.addMemOperand(MMO);
14586   }
14587
14588   thisMBB->addSuccessor(mainMBB);
14589
14590   // mainMBB:
14591   MachineBasicBlock *origMainMBB = mainMBB;
14592
14593   // Add a PHI.
14594   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14595                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14596
14597   unsigned Opc = MI->getOpcode();
14598   switch (Opc) {
14599   default:
14600     llvm_unreachable("Unhandled atomic-load-op opcode!");
14601   case X86::ATOMAND8:
14602   case X86::ATOMAND16:
14603   case X86::ATOMAND32:
14604   case X86::ATOMAND64:
14605   case X86::ATOMOR8:
14606   case X86::ATOMOR16:
14607   case X86::ATOMOR32:
14608   case X86::ATOMOR64:
14609   case X86::ATOMXOR8:
14610   case X86::ATOMXOR16:
14611   case X86::ATOMXOR32:
14612   case X86::ATOMXOR64: {
14613     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14614     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14615       .addReg(t4);
14616     break;
14617   }
14618   case X86::ATOMNAND8:
14619   case X86::ATOMNAND16:
14620   case X86::ATOMNAND32:
14621   case X86::ATOMNAND64: {
14622     unsigned Tmp = MRI.createVirtualRegister(RC);
14623     unsigned NOTOpc;
14624     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14625     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14626       .addReg(t4);
14627     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14628     break;
14629   }
14630   case X86::ATOMMAX8:
14631   case X86::ATOMMAX16:
14632   case X86::ATOMMAX32:
14633   case X86::ATOMMAX64:
14634   case X86::ATOMMIN8:
14635   case X86::ATOMMIN16:
14636   case X86::ATOMMIN32:
14637   case X86::ATOMMIN64:
14638   case X86::ATOMUMAX8:
14639   case X86::ATOMUMAX16:
14640   case X86::ATOMUMAX32:
14641   case X86::ATOMUMAX64:
14642   case X86::ATOMUMIN8:
14643   case X86::ATOMUMIN16:
14644   case X86::ATOMUMIN32:
14645   case X86::ATOMUMIN64: {
14646     unsigned CMPOpc;
14647     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14648
14649     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14650       .addReg(SrcReg)
14651       .addReg(t4);
14652
14653     if (Subtarget->hasCMov()) {
14654       if (VT != MVT::i8) {
14655         // Native support
14656         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14657           .addReg(SrcReg)
14658           .addReg(t4);
14659       } else {
14660         // Promote i8 to i32 to use CMOV32
14661         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14662         const TargetRegisterClass *RC32 =
14663           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14664         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14665         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14666         unsigned Tmp = MRI.createVirtualRegister(RC32);
14667
14668         unsigned Undef = MRI.createVirtualRegister(RC32);
14669         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14670
14671         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14672           .addReg(Undef)
14673           .addReg(SrcReg)
14674           .addImm(X86::sub_8bit);
14675         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14676           .addReg(Undef)
14677           .addReg(t4)
14678           .addImm(X86::sub_8bit);
14679
14680         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14681           .addReg(SrcReg32)
14682           .addReg(AccReg32);
14683
14684         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14685           .addReg(Tmp, 0, X86::sub_8bit);
14686       }
14687     } else {
14688       // Use pseudo select and lower them.
14689       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14690              "Invalid atomic-load-op transformation!");
14691       unsigned SelOpc = getPseudoCMOVOpc(VT);
14692       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14693       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14694       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14695               .addReg(SrcReg).addReg(t4)
14696               .addImm(CC);
14697       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14698       // Replace the original PHI node as mainMBB is changed after CMOV
14699       // lowering.
14700       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14701         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14702       Phi->eraseFromParent();
14703     }
14704     break;
14705   }
14706   }
14707
14708   // Copy PhyReg back from virtual register.
14709   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14710     .addReg(t4);
14711
14712   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14713   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14714     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14715     if (NewMO.isReg())
14716       NewMO.setIsKill(false);
14717     MIB.addOperand(NewMO);
14718   }
14719   MIB.addReg(t2);
14720   MIB.setMemRefs(MMOBegin, MMOEnd);
14721
14722   // Copy PhyReg back to virtual register.
14723   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14724     .addReg(PhyReg);
14725
14726   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14727
14728   mainMBB->addSuccessor(origMainMBB);
14729   mainMBB->addSuccessor(sinkMBB);
14730
14731   // sinkMBB:
14732   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14733           TII->get(TargetOpcode::COPY), DstReg)
14734     .addReg(t3);
14735
14736   MI->eraseFromParent();
14737   return sinkMBB;
14738 }
14739
14740 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14741 // instructions. They will be translated into a spin-loop or compare-exchange
14742 // loop from
14743 //
14744 //    ...
14745 //    dst = atomic-fetch-op MI.addr, MI.val
14746 //    ...
14747 //
14748 // to
14749 //
14750 //    ...
14751 //    t1L = LOAD [MI.addr + 0]
14752 //    t1H = LOAD [MI.addr + 4]
14753 // loop:
14754 //    t4L = phi(t1L, t3L / loop)
14755 //    t4H = phi(t1H, t3H / loop)
14756 //    t2L = OP MI.val.lo, t4L
14757 //    t2H = OP MI.val.hi, t4H
14758 //    EAX = t4L
14759 //    EDX = t4H
14760 //    EBX = t2L
14761 //    ECX = t2H
14762 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14763 //    t3L = EAX
14764 //    t3H = EDX
14765 //    JNE loop
14766 // sink:
14767 //    dstL = t3L
14768 //    dstH = t3H
14769 //    ...
14770 MachineBasicBlock *
14771 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14772                                            MachineBasicBlock *MBB) const {
14773   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14774   DebugLoc DL = MI->getDebugLoc();
14775
14776   MachineFunction *MF = MBB->getParent();
14777   MachineRegisterInfo &MRI = MF->getRegInfo();
14778
14779   const BasicBlock *BB = MBB->getBasicBlock();
14780   MachineFunction::iterator I = MBB;
14781   ++I;
14782
14783   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14784          "Unexpected number of operands");
14785
14786   assert(MI->hasOneMemOperand() &&
14787          "Expected atomic-load-op32 to have one memoperand");
14788
14789   // Memory Reference
14790   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14791   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14792
14793   unsigned DstLoReg, DstHiReg;
14794   unsigned SrcLoReg, SrcHiReg;
14795   unsigned MemOpndSlot;
14796
14797   unsigned CurOp = 0;
14798
14799   DstLoReg = MI->getOperand(CurOp++).getReg();
14800   DstHiReg = MI->getOperand(CurOp++).getReg();
14801   MemOpndSlot = CurOp;
14802   CurOp += X86::AddrNumOperands;
14803   SrcLoReg = MI->getOperand(CurOp++).getReg();
14804   SrcHiReg = MI->getOperand(CurOp++).getReg();
14805
14806   const TargetRegisterClass *RC = &X86::GR32RegClass;
14807   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14808
14809   unsigned t1L = MRI.createVirtualRegister(RC);
14810   unsigned t1H = MRI.createVirtualRegister(RC);
14811   unsigned t2L = MRI.createVirtualRegister(RC);
14812   unsigned t2H = MRI.createVirtualRegister(RC);
14813   unsigned t3L = MRI.createVirtualRegister(RC);
14814   unsigned t3H = MRI.createVirtualRegister(RC);
14815   unsigned t4L = MRI.createVirtualRegister(RC);
14816   unsigned t4H = MRI.createVirtualRegister(RC);
14817
14818   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14819   unsigned LOADOpc = X86::MOV32rm;
14820
14821   // For the atomic load-arith operator, we generate
14822   //
14823   //  thisMBB:
14824   //    t1L = LOAD [MI.addr + 0]
14825   //    t1H = LOAD [MI.addr + 4]
14826   //  mainMBB:
14827   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14828   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14829   //    t2L = OP MI.val.lo, t4L
14830   //    t2H = OP MI.val.hi, t4H
14831   //    EBX = t2L
14832   //    ECX = t2H
14833   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14834   //    t3L = EAX
14835   //    t3H = EDX
14836   //    JNE loop
14837   //  sinkMBB:
14838   //    dstL = t3L
14839   //    dstH = t3H
14840
14841   MachineBasicBlock *thisMBB = MBB;
14842   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14843   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14844   MF->insert(I, mainMBB);
14845   MF->insert(I, sinkMBB);
14846
14847   MachineInstrBuilder MIB;
14848
14849   // Transfer the remainder of BB and its successor edges to sinkMBB.
14850   sinkMBB->splice(sinkMBB->begin(), MBB,
14851                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14852   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14853
14854   // thisMBB:
14855   // Lo
14856   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14857   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14858     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14859     if (NewMO.isReg())
14860       NewMO.setIsKill(false);
14861     MIB.addOperand(NewMO);
14862   }
14863   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14864     unsigned flags = (*MMOI)->getFlags();
14865     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14866     MachineMemOperand *MMO =
14867       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14868                                (*MMOI)->getSize(),
14869                                (*MMOI)->getBaseAlignment(),
14870                                (*MMOI)->getTBAAInfo(),
14871                                (*MMOI)->getRanges());
14872     MIB.addMemOperand(MMO);
14873   };
14874   MachineInstr *LowMI = MIB;
14875
14876   // Hi
14877   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14878   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14879     if (i == X86::AddrDisp) {
14880       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14881     } else {
14882       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14883       if (NewMO.isReg())
14884         NewMO.setIsKill(false);
14885       MIB.addOperand(NewMO);
14886     }
14887   }
14888   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14889
14890   thisMBB->addSuccessor(mainMBB);
14891
14892   // mainMBB:
14893   MachineBasicBlock *origMainMBB = mainMBB;
14894
14895   // Add PHIs.
14896   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14897                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14898   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14899                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14900
14901   unsigned Opc = MI->getOpcode();
14902   switch (Opc) {
14903   default:
14904     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14905   case X86::ATOMAND6432:
14906   case X86::ATOMOR6432:
14907   case X86::ATOMXOR6432:
14908   case X86::ATOMADD6432:
14909   case X86::ATOMSUB6432: {
14910     unsigned HiOpc;
14911     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14912     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14913       .addReg(SrcLoReg);
14914     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14915       .addReg(SrcHiReg);
14916     break;
14917   }
14918   case X86::ATOMNAND6432: {
14919     unsigned HiOpc, NOTOpc;
14920     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14921     unsigned TmpL = MRI.createVirtualRegister(RC);
14922     unsigned TmpH = MRI.createVirtualRegister(RC);
14923     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14924       .addReg(t4L);
14925     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14926       .addReg(t4H);
14927     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14928     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14929     break;
14930   }
14931   case X86::ATOMMAX6432:
14932   case X86::ATOMMIN6432:
14933   case X86::ATOMUMAX6432:
14934   case X86::ATOMUMIN6432: {
14935     unsigned HiOpc;
14936     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14937     unsigned cL = MRI.createVirtualRegister(RC8);
14938     unsigned cH = MRI.createVirtualRegister(RC8);
14939     unsigned cL32 = MRI.createVirtualRegister(RC);
14940     unsigned cH32 = MRI.createVirtualRegister(RC);
14941     unsigned cc = MRI.createVirtualRegister(RC);
14942     // cl := cmp src_lo, lo
14943     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14944       .addReg(SrcLoReg).addReg(t4L);
14945     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14946     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14947     // ch := cmp src_hi, hi
14948     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14949       .addReg(SrcHiReg).addReg(t4H);
14950     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14951     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14952     // cc := if (src_hi == hi) ? cl : ch;
14953     if (Subtarget->hasCMov()) {
14954       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14955         .addReg(cH32).addReg(cL32);
14956     } else {
14957       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14958               .addReg(cH32).addReg(cL32)
14959               .addImm(X86::COND_E);
14960       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14961     }
14962     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14963     if (Subtarget->hasCMov()) {
14964       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14965         .addReg(SrcLoReg).addReg(t4L);
14966       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14967         .addReg(SrcHiReg).addReg(t4H);
14968     } else {
14969       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14970               .addReg(SrcLoReg).addReg(t4L)
14971               .addImm(X86::COND_NE);
14972       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14973       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14974       // 2nd CMOV lowering.
14975       mainMBB->addLiveIn(X86::EFLAGS);
14976       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14977               .addReg(SrcHiReg).addReg(t4H)
14978               .addImm(X86::COND_NE);
14979       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14980       // Replace the original PHI node as mainMBB is changed after CMOV
14981       // lowering.
14982       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14983         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14984       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14985         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14986       PhiL->eraseFromParent();
14987       PhiH->eraseFromParent();
14988     }
14989     break;
14990   }
14991   case X86::ATOMSWAP6432: {
14992     unsigned HiOpc;
14993     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14994     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14995     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14996     break;
14997   }
14998   }
14999
15000   // Copy EDX:EAX back from HiReg:LoReg
15001   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15002   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15003   // Copy ECX:EBX from t1H:t1L
15004   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15005   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15006
15007   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15008   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15009     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15010     if (NewMO.isReg())
15011       NewMO.setIsKill(false);
15012     MIB.addOperand(NewMO);
15013   }
15014   MIB.setMemRefs(MMOBegin, MMOEnd);
15015
15016   // Copy EDX:EAX back to t3H:t3L
15017   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15018   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15019
15020   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15021
15022   mainMBB->addSuccessor(origMainMBB);
15023   mainMBB->addSuccessor(sinkMBB);
15024
15025   // sinkMBB:
15026   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15027           TII->get(TargetOpcode::COPY), DstLoReg)
15028     .addReg(t3L);
15029   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15030           TII->get(TargetOpcode::COPY), DstHiReg)
15031     .addReg(t3H);
15032
15033   MI->eraseFromParent();
15034   return sinkMBB;
15035 }
15036
15037 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15038 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15039 // in the .td file.
15040 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15041                                        const TargetInstrInfo *TII) {
15042   unsigned Opc;
15043   switch (MI->getOpcode()) {
15044   default: llvm_unreachable("illegal opcode!");
15045   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15046   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15047   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15048   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15049   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15050   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15051   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15052   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15053   }
15054
15055   DebugLoc dl = MI->getDebugLoc();
15056   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15057
15058   unsigned NumArgs = MI->getNumOperands();
15059   for (unsigned i = 1; i < NumArgs; ++i) {
15060     MachineOperand &Op = MI->getOperand(i);
15061     if (!(Op.isReg() && Op.isImplicit()))
15062       MIB.addOperand(Op);
15063   }
15064   if (MI->hasOneMemOperand())
15065     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15066
15067   BuildMI(*BB, MI, dl,
15068     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15069     .addReg(X86::XMM0);
15070
15071   MI->eraseFromParent();
15072   return BB;
15073 }
15074
15075 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15076 // defs in an instruction pattern
15077 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15078                                        const TargetInstrInfo *TII) {
15079   unsigned Opc;
15080   switch (MI->getOpcode()) {
15081   default: llvm_unreachable("illegal opcode!");
15082   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15083   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15084   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15085   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15086   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15087   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15088   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15089   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15090   }
15091
15092   DebugLoc dl = MI->getDebugLoc();
15093   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15094
15095   unsigned NumArgs = MI->getNumOperands(); // remove the results
15096   for (unsigned i = 1; i < NumArgs; ++i) {
15097     MachineOperand &Op = MI->getOperand(i);
15098     if (!(Op.isReg() && Op.isImplicit()))
15099       MIB.addOperand(Op);
15100   }
15101   if (MI->hasOneMemOperand())
15102     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15103
15104   BuildMI(*BB, MI, dl,
15105     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15106     .addReg(X86::ECX);
15107
15108   MI->eraseFromParent();
15109   return BB;
15110 }
15111
15112 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15113                                        const TargetInstrInfo *TII,
15114                                        const X86Subtarget* Subtarget) {
15115   DebugLoc dl = MI->getDebugLoc();
15116
15117   // Address into RAX/EAX, other two args into ECX, EDX.
15118   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15119   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15120   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15121   for (int i = 0; i < X86::AddrNumOperands; ++i)
15122     MIB.addOperand(MI->getOperand(i));
15123
15124   unsigned ValOps = X86::AddrNumOperands;
15125   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15126     .addReg(MI->getOperand(ValOps).getReg());
15127   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15128     .addReg(MI->getOperand(ValOps+1).getReg());
15129
15130   // The instruction doesn't actually take any operands though.
15131   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15132
15133   MI->eraseFromParent(); // The pseudo is gone now.
15134   return BB;
15135 }
15136
15137 MachineBasicBlock *
15138 X86TargetLowering::EmitVAARG64WithCustomInserter(
15139                    MachineInstr *MI,
15140                    MachineBasicBlock *MBB) const {
15141   // Emit va_arg instruction on X86-64.
15142
15143   // Operands to this pseudo-instruction:
15144   // 0  ) Output        : destination address (reg)
15145   // 1-5) Input         : va_list address (addr, i64mem)
15146   // 6  ) ArgSize       : Size (in bytes) of vararg type
15147   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15148   // 8  ) Align         : Alignment of type
15149   // 9  ) EFLAGS (implicit-def)
15150
15151   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15152   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15153
15154   unsigned DestReg = MI->getOperand(0).getReg();
15155   MachineOperand &Base = MI->getOperand(1);
15156   MachineOperand &Scale = MI->getOperand(2);
15157   MachineOperand &Index = MI->getOperand(3);
15158   MachineOperand &Disp = MI->getOperand(4);
15159   MachineOperand &Segment = MI->getOperand(5);
15160   unsigned ArgSize = MI->getOperand(6).getImm();
15161   unsigned ArgMode = MI->getOperand(7).getImm();
15162   unsigned Align = MI->getOperand(8).getImm();
15163
15164   // Memory Reference
15165   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15166   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15167   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15168
15169   // Machine Information
15170   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15171   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15172   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15173   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15174   DebugLoc DL = MI->getDebugLoc();
15175
15176   // struct va_list {
15177   //   i32   gp_offset
15178   //   i32   fp_offset
15179   //   i64   overflow_area (address)
15180   //   i64   reg_save_area (address)
15181   // }
15182   // sizeof(va_list) = 24
15183   // alignment(va_list) = 8
15184
15185   unsigned TotalNumIntRegs = 6;
15186   unsigned TotalNumXMMRegs = 8;
15187   bool UseGPOffset = (ArgMode == 1);
15188   bool UseFPOffset = (ArgMode == 2);
15189   unsigned MaxOffset = TotalNumIntRegs * 8 +
15190                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15191
15192   /* Align ArgSize to a multiple of 8 */
15193   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15194   bool NeedsAlign = (Align > 8);
15195
15196   MachineBasicBlock *thisMBB = MBB;
15197   MachineBasicBlock *overflowMBB;
15198   MachineBasicBlock *offsetMBB;
15199   MachineBasicBlock *endMBB;
15200
15201   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15202   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15203   unsigned OffsetReg = 0;
15204
15205   if (!UseGPOffset && !UseFPOffset) {
15206     // If we only pull from the overflow region, we don't create a branch.
15207     // We don't need to alter control flow.
15208     OffsetDestReg = 0; // unused
15209     OverflowDestReg = DestReg;
15210
15211     offsetMBB = NULL;
15212     overflowMBB = thisMBB;
15213     endMBB = thisMBB;
15214   } else {
15215     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15216     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15217     // If not, pull from overflow_area. (branch to overflowMBB)
15218     //
15219     //       thisMBB
15220     //         |     .
15221     //         |        .
15222     //     offsetMBB   overflowMBB
15223     //         |        .
15224     //         |     .
15225     //        endMBB
15226
15227     // Registers for the PHI in endMBB
15228     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15229     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15230
15231     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15232     MachineFunction *MF = MBB->getParent();
15233     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15234     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15235     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15236
15237     MachineFunction::iterator MBBIter = MBB;
15238     ++MBBIter;
15239
15240     // Insert the new basic blocks
15241     MF->insert(MBBIter, offsetMBB);
15242     MF->insert(MBBIter, overflowMBB);
15243     MF->insert(MBBIter, endMBB);
15244
15245     // Transfer the remainder of MBB and its successor edges to endMBB.
15246     endMBB->splice(endMBB->begin(), thisMBB,
15247                     llvm::next(MachineBasicBlock::iterator(MI)),
15248                     thisMBB->end());
15249     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15250
15251     // Make offsetMBB and overflowMBB successors of thisMBB
15252     thisMBB->addSuccessor(offsetMBB);
15253     thisMBB->addSuccessor(overflowMBB);
15254
15255     // endMBB is a successor of both offsetMBB and overflowMBB
15256     offsetMBB->addSuccessor(endMBB);
15257     overflowMBB->addSuccessor(endMBB);
15258
15259     // Load the offset value into a register
15260     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15261     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15262       .addOperand(Base)
15263       .addOperand(Scale)
15264       .addOperand(Index)
15265       .addDisp(Disp, UseFPOffset ? 4 : 0)
15266       .addOperand(Segment)
15267       .setMemRefs(MMOBegin, MMOEnd);
15268
15269     // Check if there is enough room left to pull this argument.
15270     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15271       .addReg(OffsetReg)
15272       .addImm(MaxOffset + 8 - ArgSizeA8);
15273
15274     // Branch to "overflowMBB" if offset >= max
15275     // Fall through to "offsetMBB" otherwise
15276     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15277       .addMBB(overflowMBB);
15278   }
15279
15280   // In offsetMBB, emit code to use the reg_save_area.
15281   if (offsetMBB) {
15282     assert(OffsetReg != 0);
15283
15284     // Read the reg_save_area address.
15285     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15286     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15287       .addOperand(Base)
15288       .addOperand(Scale)
15289       .addOperand(Index)
15290       .addDisp(Disp, 16)
15291       .addOperand(Segment)
15292       .setMemRefs(MMOBegin, MMOEnd);
15293
15294     // Zero-extend the offset
15295     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15296       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15297         .addImm(0)
15298         .addReg(OffsetReg)
15299         .addImm(X86::sub_32bit);
15300
15301     // Add the offset to the reg_save_area to get the final address.
15302     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15303       .addReg(OffsetReg64)
15304       .addReg(RegSaveReg);
15305
15306     // Compute the offset for the next argument
15307     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15308     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15309       .addReg(OffsetReg)
15310       .addImm(UseFPOffset ? 16 : 8);
15311
15312     // Store it back into the va_list.
15313     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15314       .addOperand(Base)
15315       .addOperand(Scale)
15316       .addOperand(Index)
15317       .addDisp(Disp, UseFPOffset ? 4 : 0)
15318       .addOperand(Segment)
15319       .addReg(NextOffsetReg)
15320       .setMemRefs(MMOBegin, MMOEnd);
15321
15322     // Jump to endMBB
15323     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15324       .addMBB(endMBB);
15325   }
15326
15327   //
15328   // Emit code to use overflow area
15329   //
15330
15331   // Load the overflow_area address into a register.
15332   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15333   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15334     .addOperand(Base)
15335     .addOperand(Scale)
15336     .addOperand(Index)
15337     .addDisp(Disp, 8)
15338     .addOperand(Segment)
15339     .setMemRefs(MMOBegin, MMOEnd);
15340
15341   // If we need to align it, do so. Otherwise, just copy the address
15342   // to OverflowDestReg.
15343   if (NeedsAlign) {
15344     // Align the overflow address
15345     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15346     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15347
15348     // aligned_addr = (addr + (align-1)) & ~(align-1)
15349     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15350       .addReg(OverflowAddrReg)
15351       .addImm(Align-1);
15352
15353     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15354       .addReg(TmpReg)
15355       .addImm(~(uint64_t)(Align-1));
15356   } else {
15357     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15358       .addReg(OverflowAddrReg);
15359   }
15360
15361   // Compute the next overflow address after this argument.
15362   // (the overflow address should be kept 8-byte aligned)
15363   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15364   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15365     .addReg(OverflowDestReg)
15366     .addImm(ArgSizeA8);
15367
15368   // Store the new overflow address.
15369   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15370     .addOperand(Base)
15371     .addOperand(Scale)
15372     .addOperand(Index)
15373     .addDisp(Disp, 8)
15374     .addOperand(Segment)
15375     .addReg(NextAddrReg)
15376     .setMemRefs(MMOBegin, MMOEnd);
15377
15378   // If we branched, emit the PHI to the front of endMBB.
15379   if (offsetMBB) {
15380     BuildMI(*endMBB, endMBB->begin(), DL,
15381             TII->get(X86::PHI), DestReg)
15382       .addReg(OffsetDestReg).addMBB(offsetMBB)
15383       .addReg(OverflowDestReg).addMBB(overflowMBB);
15384   }
15385
15386   // Erase the pseudo instruction
15387   MI->eraseFromParent();
15388
15389   return endMBB;
15390 }
15391
15392 MachineBasicBlock *
15393 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15394                                                  MachineInstr *MI,
15395                                                  MachineBasicBlock *MBB) const {
15396   // Emit code to save XMM registers to the stack. The ABI says that the
15397   // number of registers to save is given in %al, so it's theoretically
15398   // possible to do an indirect jump trick to avoid saving all of them,
15399   // however this code takes a simpler approach and just executes all
15400   // of the stores if %al is non-zero. It's less code, and it's probably
15401   // easier on the hardware branch predictor, and stores aren't all that
15402   // expensive anyway.
15403
15404   // Create the new basic blocks. One block contains all the XMM stores,
15405   // and one block is the final destination regardless of whether any
15406   // stores were performed.
15407   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15408   MachineFunction *F = MBB->getParent();
15409   MachineFunction::iterator MBBIter = MBB;
15410   ++MBBIter;
15411   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15412   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15413   F->insert(MBBIter, XMMSaveMBB);
15414   F->insert(MBBIter, EndMBB);
15415
15416   // Transfer the remainder of MBB and its successor edges to EndMBB.
15417   EndMBB->splice(EndMBB->begin(), MBB,
15418                  llvm::next(MachineBasicBlock::iterator(MI)),
15419                  MBB->end());
15420   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15421
15422   // The original block will now fall through to the XMM save block.
15423   MBB->addSuccessor(XMMSaveMBB);
15424   // The XMMSaveMBB will fall through to the end block.
15425   XMMSaveMBB->addSuccessor(EndMBB);
15426
15427   // Now add the instructions.
15428   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15429   DebugLoc DL = MI->getDebugLoc();
15430
15431   unsigned CountReg = MI->getOperand(0).getReg();
15432   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15433   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15434
15435   if (!Subtarget->isTargetWin64()) {
15436     // If %al is 0, branch around the XMM save block.
15437     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15438     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15439     MBB->addSuccessor(EndMBB);
15440   }
15441
15442   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15443   // that was just emitted, but clearly shouldn't be "saved".
15444   assert((MI->getNumOperands() <= 3 ||
15445           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15446           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15447          && "Expected last argument to be EFLAGS");
15448   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15449   // In the XMM save block, save all the XMM argument registers.
15450   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15451     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15452     MachineMemOperand *MMO =
15453       F->getMachineMemOperand(
15454           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15455         MachineMemOperand::MOStore,
15456         /*Size=*/16, /*Align=*/16);
15457     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15458       .addFrameIndex(RegSaveFrameIndex)
15459       .addImm(/*Scale=*/1)
15460       .addReg(/*IndexReg=*/0)
15461       .addImm(/*Disp=*/Offset)
15462       .addReg(/*Segment=*/0)
15463       .addReg(MI->getOperand(i).getReg())
15464       .addMemOperand(MMO);
15465   }
15466
15467   MI->eraseFromParent();   // The pseudo instruction is gone now.
15468
15469   return EndMBB;
15470 }
15471
15472 // The EFLAGS operand of SelectItr might be missing a kill marker
15473 // because there were multiple uses of EFLAGS, and ISel didn't know
15474 // which to mark. Figure out whether SelectItr should have had a
15475 // kill marker, and set it if it should. Returns the correct kill
15476 // marker value.
15477 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15478                                      MachineBasicBlock* BB,
15479                                      const TargetRegisterInfo* TRI) {
15480   // Scan forward through BB for a use/def of EFLAGS.
15481   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15482   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15483     const MachineInstr& mi = *miI;
15484     if (mi.readsRegister(X86::EFLAGS))
15485       return false;
15486     if (mi.definesRegister(X86::EFLAGS))
15487       break; // Should have kill-flag - update below.
15488   }
15489
15490   // If we hit the end of the block, check whether EFLAGS is live into a
15491   // successor.
15492   if (miI == BB->end()) {
15493     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15494                                           sEnd = BB->succ_end();
15495          sItr != sEnd; ++sItr) {
15496       MachineBasicBlock* succ = *sItr;
15497       if (succ->isLiveIn(X86::EFLAGS))
15498         return false;
15499     }
15500   }
15501
15502   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15503   // out. SelectMI should have a kill flag on EFLAGS.
15504   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15505   return true;
15506 }
15507
15508 MachineBasicBlock *
15509 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15510                                      MachineBasicBlock *BB) const {
15511   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15512   DebugLoc DL = MI->getDebugLoc();
15513
15514   // To "insert" a SELECT_CC instruction, we actually have to insert the
15515   // diamond control-flow pattern.  The incoming instruction knows the
15516   // destination vreg to set, the condition code register to branch on, the
15517   // true/false values to select between, and a branch opcode to use.
15518   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15519   MachineFunction::iterator It = BB;
15520   ++It;
15521
15522   //  thisMBB:
15523   //  ...
15524   //   TrueVal = ...
15525   //   cmpTY ccX, r1, r2
15526   //   bCC copy1MBB
15527   //   fallthrough --> copy0MBB
15528   MachineBasicBlock *thisMBB = BB;
15529   MachineFunction *F = BB->getParent();
15530   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15531   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15532   F->insert(It, copy0MBB);
15533   F->insert(It, sinkMBB);
15534
15535   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15536   // live into the sink and copy blocks.
15537   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15538   if (!MI->killsRegister(X86::EFLAGS) &&
15539       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15540     copy0MBB->addLiveIn(X86::EFLAGS);
15541     sinkMBB->addLiveIn(X86::EFLAGS);
15542   }
15543
15544   // Transfer the remainder of BB and its successor edges to sinkMBB.
15545   sinkMBB->splice(sinkMBB->begin(), BB,
15546                   llvm::next(MachineBasicBlock::iterator(MI)),
15547                   BB->end());
15548   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15549
15550   // Add the true and fallthrough blocks as its successors.
15551   BB->addSuccessor(copy0MBB);
15552   BB->addSuccessor(sinkMBB);
15553
15554   // Create the conditional branch instruction.
15555   unsigned Opc =
15556     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15557   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15558
15559   //  copy0MBB:
15560   //   %FalseValue = ...
15561   //   # fallthrough to sinkMBB
15562   copy0MBB->addSuccessor(sinkMBB);
15563
15564   //  sinkMBB:
15565   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15566   //  ...
15567   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15568           TII->get(X86::PHI), MI->getOperand(0).getReg())
15569     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15570     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15571
15572   MI->eraseFromParent();   // The pseudo instruction is gone now.
15573   return sinkMBB;
15574 }
15575
15576 MachineBasicBlock *
15577 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15578                                         bool Is64Bit) const {
15579   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15580   DebugLoc DL = MI->getDebugLoc();
15581   MachineFunction *MF = BB->getParent();
15582   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15583
15584   assert(getTargetMachine().Options.EnableSegmentedStacks);
15585
15586   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15587   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15588
15589   // BB:
15590   //  ... [Till the alloca]
15591   // If stacklet is not large enough, jump to mallocMBB
15592   //
15593   // bumpMBB:
15594   //  Allocate by subtracting from RSP
15595   //  Jump to continueMBB
15596   //
15597   // mallocMBB:
15598   //  Allocate by call to runtime
15599   //
15600   // continueMBB:
15601   //  ...
15602   //  [rest of original BB]
15603   //
15604
15605   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15606   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15607   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15608
15609   MachineRegisterInfo &MRI = MF->getRegInfo();
15610   const TargetRegisterClass *AddrRegClass =
15611     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15612
15613   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15614     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15615     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15616     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15617     sizeVReg = MI->getOperand(1).getReg(),
15618     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15619
15620   MachineFunction::iterator MBBIter = BB;
15621   ++MBBIter;
15622
15623   MF->insert(MBBIter, bumpMBB);
15624   MF->insert(MBBIter, mallocMBB);
15625   MF->insert(MBBIter, continueMBB);
15626
15627   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15628                       (MachineBasicBlock::iterator(MI)), BB->end());
15629   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15630
15631   // Add code to the main basic block to check if the stack limit has been hit,
15632   // and if so, jump to mallocMBB otherwise to bumpMBB.
15633   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15634   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15635     .addReg(tmpSPVReg).addReg(sizeVReg);
15636   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15637     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15638     .addReg(SPLimitVReg);
15639   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15640
15641   // bumpMBB simply decreases the stack pointer, since we know the current
15642   // stacklet has enough space.
15643   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15644     .addReg(SPLimitVReg);
15645   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15646     .addReg(SPLimitVReg);
15647   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15648
15649   // Calls into a routine in libgcc to allocate more space from the heap.
15650   const uint32_t *RegMask =
15651     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15652   if (Is64Bit) {
15653     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15654       .addReg(sizeVReg);
15655     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15656       .addExternalSymbol("__morestack_allocate_stack_space")
15657       .addRegMask(RegMask)
15658       .addReg(X86::RDI, RegState::Implicit)
15659       .addReg(X86::RAX, RegState::ImplicitDefine);
15660   } else {
15661     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15662       .addImm(12);
15663     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15664     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15665       .addExternalSymbol("__morestack_allocate_stack_space")
15666       .addRegMask(RegMask)
15667       .addReg(X86::EAX, RegState::ImplicitDefine);
15668   }
15669
15670   if (!Is64Bit)
15671     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15672       .addImm(16);
15673
15674   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15675     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15676   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15677
15678   // Set up the CFG correctly.
15679   BB->addSuccessor(bumpMBB);
15680   BB->addSuccessor(mallocMBB);
15681   mallocMBB->addSuccessor(continueMBB);
15682   bumpMBB->addSuccessor(continueMBB);
15683
15684   // Take care of the PHI nodes.
15685   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15686           MI->getOperand(0).getReg())
15687     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15688     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15689
15690   // Delete the original pseudo instruction.
15691   MI->eraseFromParent();
15692
15693   // And we're done.
15694   return continueMBB;
15695 }
15696
15697 MachineBasicBlock *
15698 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15699                                           MachineBasicBlock *BB) const {
15700   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15701   DebugLoc DL = MI->getDebugLoc();
15702
15703   assert(!Subtarget->isTargetMacho());
15704
15705   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15706   // non-trivial part is impdef of ESP.
15707
15708   if (Subtarget->isTargetWin64()) {
15709     if (Subtarget->isTargetCygMing()) {
15710       // ___chkstk(Mingw64):
15711       // Clobbers R10, R11, RAX and EFLAGS.
15712       // Updates RSP.
15713       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15714         .addExternalSymbol("___chkstk")
15715         .addReg(X86::RAX, RegState::Implicit)
15716         .addReg(X86::RSP, RegState::Implicit)
15717         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15718         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15719         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15720     } else {
15721       // __chkstk(MSVCRT): does not update stack pointer.
15722       // Clobbers R10, R11 and EFLAGS.
15723       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15724         .addExternalSymbol("__chkstk")
15725         .addReg(X86::RAX, RegState::Implicit)
15726         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15727       // RAX has the offset to be subtracted from RSP.
15728       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15729         .addReg(X86::RSP)
15730         .addReg(X86::RAX);
15731     }
15732   } else {
15733     const char *StackProbeSymbol =
15734       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15735
15736     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15737       .addExternalSymbol(StackProbeSymbol)
15738       .addReg(X86::EAX, RegState::Implicit)
15739       .addReg(X86::ESP, RegState::Implicit)
15740       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15741       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15742       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15743   }
15744
15745   MI->eraseFromParent();   // The pseudo instruction is gone now.
15746   return BB;
15747 }
15748
15749 MachineBasicBlock *
15750 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15751                                       MachineBasicBlock *BB) const {
15752   // This is pretty easy.  We're taking the value that we received from
15753   // our load from the relocation, sticking it in either RDI (x86-64)
15754   // or EAX and doing an indirect call.  The return value will then
15755   // be in the normal return register.
15756   const X86InstrInfo *TII
15757     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15758   DebugLoc DL = MI->getDebugLoc();
15759   MachineFunction *F = BB->getParent();
15760
15761   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15762   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15763
15764   // Get a register mask for the lowered call.
15765   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15766   // proper register mask.
15767   const uint32_t *RegMask =
15768     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15769   if (Subtarget->is64Bit()) {
15770     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15771                                       TII->get(X86::MOV64rm), X86::RDI)
15772     .addReg(X86::RIP)
15773     .addImm(0).addReg(0)
15774     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15775                       MI->getOperand(3).getTargetFlags())
15776     .addReg(0);
15777     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15778     addDirectMem(MIB, X86::RDI);
15779     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15780   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15781     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15782                                       TII->get(X86::MOV32rm), X86::EAX)
15783     .addReg(0)
15784     .addImm(0).addReg(0)
15785     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15786                       MI->getOperand(3).getTargetFlags())
15787     .addReg(0);
15788     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15789     addDirectMem(MIB, X86::EAX);
15790     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15791   } else {
15792     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15793                                       TII->get(X86::MOV32rm), X86::EAX)
15794     .addReg(TII->getGlobalBaseReg(F))
15795     .addImm(0).addReg(0)
15796     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15797                       MI->getOperand(3).getTargetFlags())
15798     .addReg(0);
15799     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15800     addDirectMem(MIB, X86::EAX);
15801     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15802   }
15803
15804   MI->eraseFromParent(); // The pseudo instruction is gone now.
15805   return BB;
15806 }
15807
15808 MachineBasicBlock *
15809 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15810                                     MachineBasicBlock *MBB) const {
15811   DebugLoc DL = MI->getDebugLoc();
15812   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15813
15814   MachineFunction *MF = MBB->getParent();
15815   MachineRegisterInfo &MRI = MF->getRegInfo();
15816
15817   const BasicBlock *BB = MBB->getBasicBlock();
15818   MachineFunction::iterator I = MBB;
15819   ++I;
15820
15821   // Memory Reference
15822   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15823   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15824
15825   unsigned DstReg;
15826   unsigned MemOpndSlot = 0;
15827
15828   unsigned CurOp = 0;
15829
15830   DstReg = MI->getOperand(CurOp++).getReg();
15831   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15832   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15833   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15834   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15835
15836   MemOpndSlot = CurOp;
15837
15838   MVT PVT = getPointerTy();
15839   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15840          "Invalid Pointer Size!");
15841
15842   // For v = setjmp(buf), we generate
15843   //
15844   // thisMBB:
15845   //  buf[LabelOffset] = restoreMBB
15846   //  SjLjSetup restoreMBB
15847   //
15848   // mainMBB:
15849   //  v_main = 0
15850   //
15851   // sinkMBB:
15852   //  v = phi(main, restore)
15853   //
15854   // restoreMBB:
15855   //  v_restore = 1
15856
15857   MachineBasicBlock *thisMBB = MBB;
15858   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15859   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15860   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15861   MF->insert(I, mainMBB);
15862   MF->insert(I, sinkMBB);
15863   MF->push_back(restoreMBB);
15864
15865   MachineInstrBuilder MIB;
15866
15867   // Transfer the remainder of BB and its successor edges to sinkMBB.
15868   sinkMBB->splice(sinkMBB->begin(), MBB,
15869                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15870   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15871
15872   // thisMBB:
15873   unsigned PtrStoreOpc = 0;
15874   unsigned LabelReg = 0;
15875   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15876   Reloc::Model RM = getTargetMachine().getRelocationModel();
15877   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15878                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15879
15880   // Prepare IP either in reg or imm.
15881   if (!UseImmLabel) {
15882     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15883     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15884     LabelReg = MRI.createVirtualRegister(PtrRC);
15885     if (Subtarget->is64Bit()) {
15886       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15887               .addReg(X86::RIP)
15888               .addImm(0)
15889               .addReg(0)
15890               .addMBB(restoreMBB)
15891               .addReg(0);
15892     } else {
15893       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15894       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15895               .addReg(XII->getGlobalBaseReg(MF))
15896               .addImm(0)
15897               .addReg(0)
15898               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15899               .addReg(0);
15900     }
15901   } else
15902     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15903   // Store IP
15904   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15905   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15906     if (i == X86::AddrDisp)
15907       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15908     else
15909       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15910   }
15911   if (!UseImmLabel)
15912     MIB.addReg(LabelReg);
15913   else
15914     MIB.addMBB(restoreMBB);
15915   MIB.setMemRefs(MMOBegin, MMOEnd);
15916   // Setup
15917   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15918           .addMBB(restoreMBB);
15919
15920   const X86RegisterInfo *RegInfo =
15921     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15922   MIB.addRegMask(RegInfo->getNoPreservedMask());
15923   thisMBB->addSuccessor(mainMBB);
15924   thisMBB->addSuccessor(restoreMBB);
15925
15926   // mainMBB:
15927   //  EAX = 0
15928   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15929   mainMBB->addSuccessor(sinkMBB);
15930
15931   // sinkMBB:
15932   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15933           TII->get(X86::PHI), DstReg)
15934     .addReg(mainDstReg).addMBB(mainMBB)
15935     .addReg(restoreDstReg).addMBB(restoreMBB);
15936
15937   // restoreMBB:
15938   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15939   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15940   restoreMBB->addSuccessor(sinkMBB);
15941
15942   MI->eraseFromParent();
15943   return sinkMBB;
15944 }
15945
15946 MachineBasicBlock *
15947 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15948                                      MachineBasicBlock *MBB) const {
15949   DebugLoc DL = MI->getDebugLoc();
15950   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15951
15952   MachineFunction *MF = MBB->getParent();
15953   MachineRegisterInfo &MRI = MF->getRegInfo();
15954
15955   // Memory Reference
15956   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15957   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15958
15959   MVT PVT = getPointerTy();
15960   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15961          "Invalid Pointer Size!");
15962
15963   const TargetRegisterClass *RC =
15964     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15965   unsigned Tmp = MRI.createVirtualRegister(RC);
15966   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15967   const X86RegisterInfo *RegInfo =
15968     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15969   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15970   unsigned SP = RegInfo->getStackRegister();
15971
15972   MachineInstrBuilder MIB;
15973
15974   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15975   const int64_t SPOffset = 2 * PVT.getStoreSize();
15976
15977   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15978   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15979
15980   // Reload FP
15981   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15982   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15983     MIB.addOperand(MI->getOperand(i));
15984   MIB.setMemRefs(MMOBegin, MMOEnd);
15985   // Reload IP
15986   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15987   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15988     if (i == X86::AddrDisp)
15989       MIB.addDisp(MI->getOperand(i), LabelOffset);
15990     else
15991       MIB.addOperand(MI->getOperand(i));
15992   }
15993   MIB.setMemRefs(MMOBegin, MMOEnd);
15994   // Reload SP
15995   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15996   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15997     if (i == X86::AddrDisp)
15998       MIB.addDisp(MI->getOperand(i), SPOffset);
15999     else
16000       MIB.addOperand(MI->getOperand(i));
16001   }
16002   MIB.setMemRefs(MMOBegin, MMOEnd);
16003   // Jump
16004   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16005
16006   MI->eraseFromParent();
16007   return MBB;
16008 }
16009
16010 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16011 // accumulator loops. Writing back to the accumulator allows the coalescer
16012 // to remove extra copies in the loop.   
16013 MachineBasicBlock *
16014 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16015                                  MachineBasicBlock *MBB) const {
16016   MachineOperand &AddendOp = MI->getOperand(3);
16017
16018   // Bail out early if the addend isn't a register - we can't switch these.
16019   if (!AddendOp.isReg())
16020     return MBB;
16021
16022   MachineFunction &MF = *MBB->getParent();
16023   MachineRegisterInfo &MRI = MF.getRegInfo();
16024
16025   // Check whether the addend is defined by a PHI:
16026   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16027   MachineInstr &AddendDef = *MRI.def_begin(AddendOp.getReg());
16028   if (!AddendDef.isPHI())
16029     return MBB;
16030
16031   // Look for the following pattern:
16032   // loop:
16033   //   %addend = phi [%entry, 0], [%loop, %result]
16034   //   ...
16035   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16036
16037   // Replace with:
16038   //   loop:
16039   //   %addend = phi [%entry, 0], [%loop, %result]
16040   //   ...
16041   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16042
16043   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16044     assert(AddendDef.getOperand(i).isReg());
16045     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16046     MachineInstr &PHISrcInst = *MRI.def_begin(PHISrcOp.getReg());
16047     if (&PHISrcInst == MI) {
16048       // Found a matching instruction.
16049       unsigned NewFMAOpc = 0;
16050       switch (MI->getOpcode()) {
16051         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16052         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16053         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16054         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16055         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16056         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16057         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16058         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16059         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16060         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16061         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16062         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16063         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16064         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16065         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16066         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16067         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16068         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16069         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16070         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16071         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16072         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16073         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16074         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16075         default: llvm_unreachable("Unrecognized FMA variant.");
16076       }
16077
16078       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16079       MachineInstrBuilder MIB =
16080         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16081         .addOperand(MI->getOperand(0))
16082         .addOperand(MI->getOperand(3))
16083         .addOperand(MI->getOperand(2))
16084         .addOperand(MI->getOperand(1));
16085       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16086       MI->eraseFromParent();
16087     }
16088   }
16089
16090   return MBB;
16091 }
16092
16093 MachineBasicBlock *
16094 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16095                                                MachineBasicBlock *BB) const {
16096   switch (MI->getOpcode()) {
16097   default: llvm_unreachable("Unexpected instr type to insert");
16098   case X86::TAILJMPd64:
16099   case X86::TAILJMPr64:
16100   case X86::TAILJMPm64:
16101     llvm_unreachable("TAILJMP64 would not be touched here.");
16102   case X86::TCRETURNdi64:
16103   case X86::TCRETURNri64:
16104   case X86::TCRETURNmi64:
16105     return BB;
16106   case X86::WIN_ALLOCA:
16107     return EmitLoweredWinAlloca(MI, BB);
16108   case X86::SEG_ALLOCA_32:
16109     return EmitLoweredSegAlloca(MI, BB, false);
16110   case X86::SEG_ALLOCA_64:
16111     return EmitLoweredSegAlloca(MI, BB, true);
16112   case X86::TLSCall_32:
16113   case X86::TLSCall_64:
16114     return EmitLoweredTLSCall(MI, BB);
16115   case X86::CMOV_GR8:
16116   case X86::CMOV_FR32:
16117   case X86::CMOV_FR64:
16118   case X86::CMOV_V4F32:
16119   case X86::CMOV_V2F64:
16120   case X86::CMOV_V2I64:
16121   case X86::CMOV_V8F32:
16122   case X86::CMOV_V4F64:
16123   case X86::CMOV_V4I64:
16124   case X86::CMOV_V16F32:
16125   case X86::CMOV_V8F64:
16126   case X86::CMOV_V8I64:
16127   case X86::CMOV_GR16:
16128   case X86::CMOV_GR32:
16129   case X86::CMOV_RFP32:
16130   case X86::CMOV_RFP64:
16131   case X86::CMOV_RFP80:
16132     return EmitLoweredSelect(MI, BB);
16133
16134   case X86::FP32_TO_INT16_IN_MEM:
16135   case X86::FP32_TO_INT32_IN_MEM:
16136   case X86::FP32_TO_INT64_IN_MEM:
16137   case X86::FP64_TO_INT16_IN_MEM:
16138   case X86::FP64_TO_INT32_IN_MEM:
16139   case X86::FP64_TO_INT64_IN_MEM:
16140   case X86::FP80_TO_INT16_IN_MEM:
16141   case X86::FP80_TO_INT32_IN_MEM:
16142   case X86::FP80_TO_INT64_IN_MEM: {
16143     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16144     DebugLoc DL = MI->getDebugLoc();
16145
16146     // Change the floating point control register to use "round towards zero"
16147     // mode when truncating to an integer value.
16148     MachineFunction *F = BB->getParent();
16149     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16150     addFrameReference(BuildMI(*BB, MI, DL,
16151                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16152
16153     // Load the old value of the high byte of the control word...
16154     unsigned OldCW =
16155       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16156     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16157                       CWFrameIdx);
16158
16159     // Set the high part to be round to zero...
16160     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16161       .addImm(0xC7F);
16162
16163     // Reload the modified control word now...
16164     addFrameReference(BuildMI(*BB, MI, DL,
16165                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16166
16167     // Restore the memory image of control word to original value
16168     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16169       .addReg(OldCW);
16170
16171     // Get the X86 opcode to use.
16172     unsigned Opc;
16173     switch (MI->getOpcode()) {
16174     default: llvm_unreachable("illegal opcode!");
16175     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16176     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16177     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16178     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16179     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16180     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16181     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16182     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16183     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16184     }
16185
16186     X86AddressMode AM;
16187     MachineOperand &Op = MI->getOperand(0);
16188     if (Op.isReg()) {
16189       AM.BaseType = X86AddressMode::RegBase;
16190       AM.Base.Reg = Op.getReg();
16191     } else {
16192       AM.BaseType = X86AddressMode::FrameIndexBase;
16193       AM.Base.FrameIndex = Op.getIndex();
16194     }
16195     Op = MI->getOperand(1);
16196     if (Op.isImm())
16197       AM.Scale = Op.getImm();
16198     Op = MI->getOperand(2);
16199     if (Op.isImm())
16200       AM.IndexReg = Op.getImm();
16201     Op = MI->getOperand(3);
16202     if (Op.isGlobal()) {
16203       AM.GV = Op.getGlobal();
16204     } else {
16205       AM.Disp = Op.getImm();
16206     }
16207     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16208                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16209
16210     // Reload the original control word now.
16211     addFrameReference(BuildMI(*BB, MI, DL,
16212                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16213
16214     MI->eraseFromParent();   // The pseudo instruction is gone now.
16215     return BB;
16216   }
16217     // String/text processing lowering.
16218   case X86::PCMPISTRM128REG:
16219   case X86::VPCMPISTRM128REG:
16220   case X86::PCMPISTRM128MEM:
16221   case X86::VPCMPISTRM128MEM:
16222   case X86::PCMPESTRM128REG:
16223   case X86::VPCMPESTRM128REG:
16224   case X86::PCMPESTRM128MEM:
16225   case X86::VPCMPESTRM128MEM:
16226     assert(Subtarget->hasSSE42() &&
16227            "Target must have SSE4.2 or AVX features enabled");
16228     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16229
16230   // String/text processing lowering.
16231   case X86::PCMPISTRIREG:
16232   case X86::VPCMPISTRIREG:
16233   case X86::PCMPISTRIMEM:
16234   case X86::VPCMPISTRIMEM:
16235   case X86::PCMPESTRIREG:
16236   case X86::VPCMPESTRIREG:
16237   case X86::PCMPESTRIMEM:
16238   case X86::VPCMPESTRIMEM:
16239     assert(Subtarget->hasSSE42() &&
16240            "Target must have SSE4.2 or AVX features enabled");
16241     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16242
16243   // Thread synchronization.
16244   case X86::MONITOR:
16245     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16246
16247   // xbegin
16248   case X86::XBEGIN:
16249     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16250
16251   // Atomic Lowering.
16252   case X86::ATOMAND8:
16253   case X86::ATOMAND16:
16254   case X86::ATOMAND32:
16255   case X86::ATOMAND64:
16256     // Fall through
16257   case X86::ATOMOR8:
16258   case X86::ATOMOR16:
16259   case X86::ATOMOR32:
16260   case X86::ATOMOR64:
16261     // Fall through
16262   case X86::ATOMXOR16:
16263   case X86::ATOMXOR8:
16264   case X86::ATOMXOR32:
16265   case X86::ATOMXOR64:
16266     // Fall through
16267   case X86::ATOMNAND8:
16268   case X86::ATOMNAND16:
16269   case X86::ATOMNAND32:
16270   case X86::ATOMNAND64:
16271     // Fall through
16272   case X86::ATOMMAX8:
16273   case X86::ATOMMAX16:
16274   case X86::ATOMMAX32:
16275   case X86::ATOMMAX64:
16276     // Fall through
16277   case X86::ATOMMIN8:
16278   case X86::ATOMMIN16:
16279   case X86::ATOMMIN32:
16280   case X86::ATOMMIN64:
16281     // Fall through
16282   case X86::ATOMUMAX8:
16283   case X86::ATOMUMAX16:
16284   case X86::ATOMUMAX32:
16285   case X86::ATOMUMAX64:
16286     // Fall through
16287   case X86::ATOMUMIN8:
16288   case X86::ATOMUMIN16:
16289   case X86::ATOMUMIN32:
16290   case X86::ATOMUMIN64:
16291     return EmitAtomicLoadArith(MI, BB);
16292
16293   // This group does 64-bit operations on a 32-bit host.
16294   case X86::ATOMAND6432:
16295   case X86::ATOMOR6432:
16296   case X86::ATOMXOR6432:
16297   case X86::ATOMNAND6432:
16298   case X86::ATOMADD6432:
16299   case X86::ATOMSUB6432:
16300   case X86::ATOMMAX6432:
16301   case X86::ATOMMIN6432:
16302   case X86::ATOMUMAX6432:
16303   case X86::ATOMUMIN6432:
16304   case X86::ATOMSWAP6432:
16305     return EmitAtomicLoadArith6432(MI, BB);
16306
16307   case X86::VASTART_SAVE_XMM_REGS:
16308     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16309
16310   case X86::VAARG_64:
16311     return EmitVAARG64WithCustomInserter(MI, BB);
16312
16313   case X86::EH_SjLj_SetJmp32:
16314   case X86::EH_SjLj_SetJmp64:
16315     return emitEHSjLjSetJmp(MI, BB);
16316
16317   case X86::EH_SjLj_LongJmp32:
16318   case X86::EH_SjLj_LongJmp64:
16319     return emitEHSjLjLongJmp(MI, BB);
16320
16321   case TargetOpcode::STACKMAP:
16322   case TargetOpcode::PATCHPOINT:
16323     return emitPatchPoint(MI, BB);
16324
16325   case X86::VFMADDPDr213r:
16326   case X86::VFMADDPSr213r:
16327   case X86::VFMADDSDr213r:
16328   case X86::VFMADDSSr213r:
16329   case X86::VFMSUBPDr213r:
16330   case X86::VFMSUBPSr213r:
16331   case X86::VFMSUBSDr213r:
16332   case X86::VFMSUBSSr213r:
16333   case X86::VFNMADDPDr213r:
16334   case X86::VFNMADDPSr213r:
16335   case X86::VFNMADDSDr213r:
16336   case X86::VFNMADDSSr213r:
16337   case X86::VFNMSUBPDr213r:
16338   case X86::VFNMSUBPSr213r:
16339   case X86::VFNMSUBSDr213r:
16340   case X86::VFNMSUBSSr213r:
16341   case X86::VFMADDPDr213rY:
16342   case X86::VFMADDPSr213rY:
16343   case X86::VFMSUBPDr213rY:
16344   case X86::VFMSUBPSr213rY:
16345   case X86::VFNMADDPDr213rY:
16346   case X86::VFNMADDPSr213rY:
16347   case X86::VFNMSUBPDr213rY:
16348   case X86::VFNMSUBPSr213rY:
16349     return emitFMA3Instr(MI, BB);
16350   }
16351 }
16352
16353 //===----------------------------------------------------------------------===//
16354 //                           X86 Optimization Hooks
16355 //===----------------------------------------------------------------------===//
16356
16357 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16358                                                        APInt &KnownZero,
16359                                                        APInt &KnownOne,
16360                                                        const SelectionDAG &DAG,
16361                                                        unsigned Depth) const {
16362   unsigned BitWidth = KnownZero.getBitWidth();
16363   unsigned Opc = Op.getOpcode();
16364   assert((Opc >= ISD::BUILTIN_OP_END ||
16365           Opc == ISD::INTRINSIC_WO_CHAIN ||
16366           Opc == ISD::INTRINSIC_W_CHAIN ||
16367           Opc == ISD::INTRINSIC_VOID) &&
16368          "Should use MaskedValueIsZero if you don't know whether Op"
16369          " is a target node!");
16370
16371   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16372   switch (Opc) {
16373   default: break;
16374   case X86ISD::ADD:
16375   case X86ISD::SUB:
16376   case X86ISD::ADC:
16377   case X86ISD::SBB:
16378   case X86ISD::SMUL:
16379   case X86ISD::UMUL:
16380   case X86ISD::INC:
16381   case X86ISD::DEC:
16382   case X86ISD::OR:
16383   case X86ISD::XOR:
16384   case X86ISD::AND:
16385     // These nodes' second result is a boolean.
16386     if (Op.getResNo() == 0)
16387       break;
16388     // Fallthrough
16389   case X86ISD::SETCC:
16390     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16391     break;
16392   case ISD::INTRINSIC_WO_CHAIN: {
16393     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16394     unsigned NumLoBits = 0;
16395     switch (IntId) {
16396     default: break;
16397     case Intrinsic::x86_sse_movmsk_ps:
16398     case Intrinsic::x86_avx_movmsk_ps_256:
16399     case Intrinsic::x86_sse2_movmsk_pd:
16400     case Intrinsic::x86_avx_movmsk_pd_256:
16401     case Intrinsic::x86_mmx_pmovmskb:
16402     case Intrinsic::x86_sse2_pmovmskb_128:
16403     case Intrinsic::x86_avx2_pmovmskb: {
16404       // High bits of movmskp{s|d}, pmovmskb are known zero.
16405       switch (IntId) {
16406         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16407         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16408         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16409         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16410         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16411         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16412         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16413         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16414       }
16415       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16416       break;
16417     }
16418     }
16419     break;
16420   }
16421   }
16422 }
16423
16424 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16425                                                          unsigned Depth) const {
16426   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16427   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16428     return Op.getValueType().getScalarType().getSizeInBits();
16429
16430   // Fallback case.
16431   return 1;
16432 }
16433
16434 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16435 /// node is a GlobalAddress + offset.
16436 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16437                                        const GlobalValue* &GA,
16438                                        int64_t &Offset) const {
16439   if (N->getOpcode() == X86ISD::Wrapper) {
16440     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16441       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16442       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16443       return true;
16444     }
16445   }
16446   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16447 }
16448
16449 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16450 /// same as extracting the high 128-bit part of 256-bit vector and then
16451 /// inserting the result into the low part of a new 256-bit vector
16452 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16453   EVT VT = SVOp->getValueType(0);
16454   unsigned NumElems = VT.getVectorNumElements();
16455
16456   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16457   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16458     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16459         SVOp->getMaskElt(j) >= 0)
16460       return false;
16461
16462   return true;
16463 }
16464
16465 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16466 /// same as extracting the low 128-bit part of 256-bit vector and then
16467 /// inserting the result into the high part of a new 256-bit vector
16468 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16469   EVT VT = SVOp->getValueType(0);
16470   unsigned NumElems = VT.getVectorNumElements();
16471
16472   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16473   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16474     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16475         SVOp->getMaskElt(j) >= 0)
16476       return false;
16477
16478   return true;
16479 }
16480
16481 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16482 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16483                                         TargetLowering::DAGCombinerInfo &DCI,
16484                                         const X86Subtarget* Subtarget) {
16485   SDLoc dl(N);
16486   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16487   SDValue V1 = SVOp->getOperand(0);
16488   SDValue V2 = SVOp->getOperand(1);
16489   EVT VT = SVOp->getValueType(0);
16490   unsigned NumElems = VT.getVectorNumElements();
16491
16492   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16493       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16494     //
16495     //                   0,0,0,...
16496     //                      |
16497     //    V      UNDEF    BUILD_VECTOR    UNDEF
16498     //     \      /           \           /
16499     //  CONCAT_VECTOR         CONCAT_VECTOR
16500     //         \                  /
16501     //          \                /
16502     //          RESULT: V + zero extended
16503     //
16504     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16505         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16506         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16507       return SDValue();
16508
16509     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16510       return SDValue();
16511
16512     // To match the shuffle mask, the first half of the mask should
16513     // be exactly the first vector, and all the rest a splat with the
16514     // first element of the second one.
16515     for (unsigned i = 0; i != NumElems/2; ++i)
16516       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16517           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16518         return SDValue();
16519
16520     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16521     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16522       if (Ld->hasNUsesOfValue(1, 0)) {
16523         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16524         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16525         SDValue ResNode =
16526           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16527                                   array_lengthof(Ops),
16528                                   Ld->getMemoryVT(),
16529                                   Ld->getPointerInfo(),
16530                                   Ld->getAlignment(),
16531                                   false/*isVolatile*/, true/*ReadMem*/,
16532                                   false/*WriteMem*/);
16533
16534         // Make sure the newly-created LOAD is in the same position as Ld in
16535         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16536         // and update uses of Ld's output chain to use the TokenFactor.
16537         if (Ld->hasAnyUseOfValue(1)) {
16538           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16539                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16540           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16541           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16542                                  SDValue(ResNode.getNode(), 1));
16543         }
16544
16545         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16546       }
16547     }
16548
16549     // Emit a zeroed vector and insert the desired subvector on its
16550     // first half.
16551     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16552     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16553     return DCI.CombineTo(N, InsV);
16554   }
16555
16556   //===--------------------------------------------------------------------===//
16557   // Combine some shuffles into subvector extracts and inserts:
16558   //
16559
16560   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16561   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16562     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16563     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16564     return DCI.CombineTo(N, InsV);
16565   }
16566
16567   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16568   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16569     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16570     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16571     return DCI.CombineTo(N, InsV);
16572   }
16573
16574   return SDValue();
16575 }
16576
16577 /// PerformShuffleCombine - Performs several different shuffle combines.
16578 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16579                                      TargetLowering::DAGCombinerInfo &DCI,
16580                                      const X86Subtarget *Subtarget) {
16581   SDLoc dl(N);
16582   EVT VT = N->getValueType(0);
16583
16584   // Don't create instructions with illegal types after legalize types has run.
16585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16586   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16587     return SDValue();
16588
16589   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16590   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16591       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16592     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16593
16594   // Only handle 128 wide vector from here on.
16595   if (!VT.is128BitVector())
16596     return SDValue();
16597
16598   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16599   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16600   // consecutive, non-overlapping, and in the right order.
16601   SmallVector<SDValue, 16> Elts;
16602   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16603     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16604
16605   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16606 }
16607
16608 /// PerformTruncateCombine - Converts truncate operation to
16609 /// a sequence of vector shuffle operations.
16610 /// It is possible when we truncate 256-bit vector to 128-bit vector
16611 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16612                                       TargetLowering::DAGCombinerInfo &DCI,
16613                                       const X86Subtarget *Subtarget)  {
16614   return SDValue();
16615 }
16616
16617 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16618 /// specific shuffle of a load can be folded into a single element load.
16619 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16620 /// shuffles have been customed lowered so we need to handle those here.
16621 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16622                                          TargetLowering::DAGCombinerInfo &DCI) {
16623   if (DCI.isBeforeLegalizeOps())
16624     return SDValue();
16625
16626   SDValue InVec = N->getOperand(0);
16627   SDValue EltNo = N->getOperand(1);
16628
16629   if (!isa<ConstantSDNode>(EltNo))
16630     return SDValue();
16631
16632   EVT VT = InVec.getValueType();
16633
16634   bool HasShuffleIntoBitcast = false;
16635   if (InVec.getOpcode() == ISD::BITCAST) {
16636     // Don't duplicate a load with other uses.
16637     if (!InVec.hasOneUse())
16638       return SDValue();
16639     EVT BCVT = InVec.getOperand(0).getValueType();
16640     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16641       return SDValue();
16642     InVec = InVec.getOperand(0);
16643     HasShuffleIntoBitcast = true;
16644   }
16645
16646   if (!isTargetShuffle(InVec.getOpcode()))
16647     return SDValue();
16648
16649   // Don't duplicate a load with other uses.
16650   if (!InVec.hasOneUse())
16651     return SDValue();
16652
16653   SmallVector<int, 16> ShuffleMask;
16654   bool UnaryShuffle;
16655   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16656                             UnaryShuffle))
16657     return SDValue();
16658
16659   // Select the input vector, guarding against out of range extract vector.
16660   unsigned NumElems = VT.getVectorNumElements();
16661   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16662   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16663   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16664                                          : InVec.getOperand(1);
16665
16666   // If inputs to shuffle are the same for both ops, then allow 2 uses
16667   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16668
16669   if (LdNode.getOpcode() == ISD::BITCAST) {
16670     // Don't duplicate a load with other uses.
16671     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16672       return SDValue();
16673
16674     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16675     LdNode = LdNode.getOperand(0);
16676   }
16677
16678   if (!ISD::isNormalLoad(LdNode.getNode()))
16679     return SDValue();
16680
16681   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16682
16683   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16684     return SDValue();
16685
16686   if (HasShuffleIntoBitcast) {
16687     // If there's a bitcast before the shuffle, check if the load type and
16688     // alignment is valid.
16689     unsigned Align = LN0->getAlignment();
16690     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16691     unsigned NewAlign = TLI.getDataLayout()->
16692       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16693
16694     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16695       return SDValue();
16696   }
16697
16698   // All checks match so transform back to vector_shuffle so that DAG combiner
16699   // can finish the job
16700   SDLoc dl(N);
16701
16702   // Create shuffle node taking into account the case that its a unary shuffle
16703   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16704   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16705                                  InVec.getOperand(0), Shuffle,
16706                                  &ShuffleMask[0]);
16707   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16708   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16709                      EltNo);
16710 }
16711
16712 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16713 /// generation and convert it from being a bunch of shuffles and extracts
16714 /// to a simple store and scalar loads to extract the elements.
16715 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16716                                          TargetLowering::DAGCombinerInfo &DCI) {
16717   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16718   if (NewOp.getNode())
16719     return NewOp;
16720
16721   SDValue InputVector = N->getOperand(0);
16722
16723   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16724   // from mmx to v2i32 has a single usage.
16725   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16726       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16727       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16728     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16729                        N->getValueType(0),
16730                        InputVector.getNode()->getOperand(0));
16731
16732   // Only operate on vectors of 4 elements, where the alternative shuffling
16733   // gets to be more expensive.
16734   if (InputVector.getValueType() != MVT::v4i32)
16735     return SDValue();
16736
16737   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16738   // single use which is a sign-extend or zero-extend, and all elements are
16739   // used.
16740   SmallVector<SDNode *, 4> Uses;
16741   unsigned ExtractedElements = 0;
16742   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16743        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16744     if (UI.getUse().getResNo() != InputVector.getResNo())
16745       return SDValue();
16746
16747     SDNode *Extract = *UI;
16748     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16749       return SDValue();
16750
16751     if (Extract->getValueType(0) != MVT::i32)
16752       return SDValue();
16753     if (!Extract->hasOneUse())
16754       return SDValue();
16755     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16756         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16757       return SDValue();
16758     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16759       return SDValue();
16760
16761     // Record which element was extracted.
16762     ExtractedElements |=
16763       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16764
16765     Uses.push_back(Extract);
16766   }
16767
16768   // If not all the elements were used, this may not be worthwhile.
16769   if (ExtractedElements != 15)
16770     return SDValue();
16771
16772   // Ok, we've now decided to do the transformation.
16773   SDLoc dl(InputVector);
16774
16775   // Store the value to a temporary stack slot.
16776   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16777   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16778                             MachinePointerInfo(), false, false, 0);
16779
16780   // Replace each use (extract) with a load of the appropriate element.
16781   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16782        UE = Uses.end(); UI != UE; ++UI) {
16783     SDNode *Extract = *UI;
16784
16785     // cOMpute the element's address.
16786     SDValue Idx = Extract->getOperand(1);
16787     unsigned EltSize =
16788         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16789     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16790     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16791     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16792
16793     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16794                                      StackPtr, OffsetVal);
16795
16796     // Load the scalar.
16797     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16798                                      ScalarAddr, MachinePointerInfo(),
16799                                      false, false, false, 0);
16800
16801     // Replace the exact with the load.
16802     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16803   }
16804
16805   // The replacement was made in place; don't return anything.
16806   return SDValue();
16807 }
16808
16809 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16810 static std::pair<unsigned, bool>
16811 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16812                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16813   if (!VT.isVector())
16814     return std::make_pair(0, false);
16815
16816   bool NeedSplit = false;
16817   switch (VT.getSimpleVT().SimpleTy) {
16818   default: return std::make_pair(0, false);
16819   case MVT::v32i8:
16820   case MVT::v16i16:
16821   case MVT::v8i32:
16822     if (!Subtarget->hasAVX2())
16823       NeedSplit = true;
16824     if (!Subtarget->hasAVX())
16825       return std::make_pair(0, false);
16826     break;
16827   case MVT::v16i8:
16828   case MVT::v8i16:
16829   case MVT::v4i32:
16830     if (!Subtarget->hasSSE2())
16831       return std::make_pair(0, false);
16832   }
16833
16834   // SSE2 has only a small subset of the operations.
16835   bool hasUnsigned = Subtarget->hasSSE41() ||
16836                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16837   bool hasSigned = Subtarget->hasSSE41() ||
16838                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16839
16840   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16841
16842   unsigned Opc = 0;
16843   // Check for x CC y ? x : y.
16844   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16845       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16846     switch (CC) {
16847     default: break;
16848     case ISD::SETULT:
16849     case ISD::SETULE:
16850       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16851     case ISD::SETUGT:
16852     case ISD::SETUGE:
16853       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16854     case ISD::SETLT:
16855     case ISD::SETLE:
16856       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16857     case ISD::SETGT:
16858     case ISD::SETGE:
16859       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16860     }
16861   // Check for x CC y ? y : x -- a min/max with reversed arms.
16862   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16863              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16864     switch (CC) {
16865     default: break;
16866     case ISD::SETULT:
16867     case ISD::SETULE:
16868       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16869     case ISD::SETUGT:
16870     case ISD::SETUGE:
16871       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16872     case ISD::SETLT:
16873     case ISD::SETLE:
16874       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16875     case ISD::SETGT:
16876     case ISD::SETGE:
16877       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16878     }
16879   }
16880
16881   return std::make_pair(Opc, NeedSplit);
16882 }
16883
16884 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16885 /// nodes.
16886 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16887                                     TargetLowering::DAGCombinerInfo &DCI,
16888                                     const X86Subtarget *Subtarget) {
16889   SDLoc DL(N);
16890   SDValue Cond = N->getOperand(0);
16891   // Get the LHS/RHS of the select.
16892   SDValue LHS = N->getOperand(1);
16893   SDValue RHS = N->getOperand(2);
16894   EVT VT = LHS.getValueType();
16895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16896
16897   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16898   // instructions match the semantics of the common C idiom x<y?x:y but not
16899   // x<=y?x:y, because of how they handle negative zero (which can be
16900   // ignored in unsafe-math mode).
16901   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16902       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16903       (Subtarget->hasSSE2() ||
16904        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16905     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16906
16907     unsigned Opcode = 0;
16908     // Check for x CC y ? x : y.
16909     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16910         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16911       switch (CC) {
16912       default: break;
16913       case ISD::SETULT:
16914         // Converting this to a min would handle NaNs incorrectly, and swapping
16915         // the operands would cause it to handle comparisons between positive
16916         // and negative zero incorrectly.
16917         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16918           if (!DAG.getTarget().Options.UnsafeFPMath &&
16919               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16920             break;
16921           std::swap(LHS, RHS);
16922         }
16923         Opcode = X86ISD::FMIN;
16924         break;
16925       case ISD::SETOLE:
16926         // Converting this to a min would handle comparisons between positive
16927         // and negative zero incorrectly.
16928         if (!DAG.getTarget().Options.UnsafeFPMath &&
16929             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16930           break;
16931         Opcode = X86ISD::FMIN;
16932         break;
16933       case ISD::SETULE:
16934         // Converting this to a min would handle both negative zeros and NaNs
16935         // incorrectly, but we can swap the operands to fix both.
16936         std::swap(LHS, RHS);
16937       case ISD::SETOLT:
16938       case ISD::SETLT:
16939       case ISD::SETLE:
16940         Opcode = X86ISD::FMIN;
16941         break;
16942
16943       case ISD::SETOGE:
16944         // Converting this to a max would handle comparisons between positive
16945         // and negative zero incorrectly.
16946         if (!DAG.getTarget().Options.UnsafeFPMath &&
16947             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16948           break;
16949         Opcode = X86ISD::FMAX;
16950         break;
16951       case ISD::SETUGT:
16952         // Converting this to a max would handle NaNs incorrectly, and swapping
16953         // the operands would cause it to handle comparisons between positive
16954         // and negative zero incorrectly.
16955         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16956           if (!DAG.getTarget().Options.UnsafeFPMath &&
16957               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16958             break;
16959           std::swap(LHS, RHS);
16960         }
16961         Opcode = X86ISD::FMAX;
16962         break;
16963       case ISD::SETUGE:
16964         // Converting this to a max would handle both negative zeros and NaNs
16965         // incorrectly, but we can swap the operands to fix both.
16966         std::swap(LHS, RHS);
16967       case ISD::SETOGT:
16968       case ISD::SETGT:
16969       case ISD::SETGE:
16970         Opcode = X86ISD::FMAX;
16971         break;
16972       }
16973     // Check for x CC y ? y : x -- a min/max with reversed arms.
16974     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16975                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16976       switch (CC) {
16977       default: break;
16978       case ISD::SETOGE:
16979         // Converting this to a min would handle comparisons between positive
16980         // and negative zero incorrectly, and swapping the operands would
16981         // cause it to handle NaNs incorrectly.
16982         if (!DAG.getTarget().Options.UnsafeFPMath &&
16983             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16984           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16985             break;
16986           std::swap(LHS, RHS);
16987         }
16988         Opcode = X86ISD::FMIN;
16989         break;
16990       case ISD::SETUGT:
16991         // Converting this to a min would handle NaNs incorrectly.
16992         if (!DAG.getTarget().Options.UnsafeFPMath &&
16993             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16994           break;
16995         Opcode = X86ISD::FMIN;
16996         break;
16997       case ISD::SETUGE:
16998         // Converting this to a min would handle both negative zeros and NaNs
16999         // incorrectly, but we can swap the operands to fix both.
17000         std::swap(LHS, RHS);
17001       case ISD::SETOGT:
17002       case ISD::SETGT:
17003       case ISD::SETGE:
17004         Opcode = X86ISD::FMIN;
17005         break;
17006
17007       case ISD::SETULT:
17008         // Converting this to a max would handle NaNs incorrectly.
17009         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17010           break;
17011         Opcode = X86ISD::FMAX;
17012         break;
17013       case ISD::SETOLE:
17014         // Converting this to a max would handle comparisons between positive
17015         // and negative zero incorrectly, and swapping the operands would
17016         // cause it to handle NaNs incorrectly.
17017         if (!DAG.getTarget().Options.UnsafeFPMath &&
17018             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17019           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17020             break;
17021           std::swap(LHS, RHS);
17022         }
17023         Opcode = X86ISD::FMAX;
17024         break;
17025       case ISD::SETULE:
17026         // Converting this to a max would handle both negative zeros and NaNs
17027         // incorrectly, but we can swap the operands to fix both.
17028         std::swap(LHS, RHS);
17029       case ISD::SETOLT:
17030       case ISD::SETLT:
17031       case ISD::SETLE:
17032         Opcode = X86ISD::FMAX;
17033         break;
17034       }
17035     }
17036
17037     if (Opcode)
17038       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17039   }
17040
17041   EVT CondVT = Cond.getValueType();
17042   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17043       CondVT.getVectorElementType() == MVT::i1) {
17044     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17045     // lowering on AVX-512. In this case we convert it to
17046     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17047     // The same situation for all 128 and 256-bit vectors of i8 and i16
17048     EVT OpVT = LHS.getValueType();
17049     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17050         (OpVT.getVectorElementType() == MVT::i8 ||
17051          OpVT.getVectorElementType() == MVT::i16)) {
17052       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17053       DCI.AddToWorklist(Cond.getNode());
17054       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17055     }
17056   }
17057   // If this is a select between two integer constants, try to do some
17058   // optimizations.
17059   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17060     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17061       // Don't do this for crazy integer types.
17062       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17063         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17064         // so that TrueC (the true value) is larger than FalseC.
17065         bool NeedsCondInvert = false;
17066
17067         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17068             // Efficiently invertible.
17069             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17070              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17071               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17072           NeedsCondInvert = true;
17073           std::swap(TrueC, FalseC);
17074         }
17075
17076         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17077         if (FalseC->getAPIntValue() == 0 &&
17078             TrueC->getAPIntValue().isPowerOf2()) {
17079           if (NeedsCondInvert) // Invert the condition if needed.
17080             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17081                                DAG.getConstant(1, Cond.getValueType()));
17082
17083           // Zero extend the condition if needed.
17084           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17085
17086           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17087           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17088                              DAG.getConstant(ShAmt, MVT::i8));
17089         }
17090
17091         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17092         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17093           if (NeedsCondInvert) // Invert the condition if needed.
17094             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17095                                DAG.getConstant(1, Cond.getValueType()));
17096
17097           // Zero extend the condition if needed.
17098           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17099                              FalseC->getValueType(0), Cond);
17100           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17101                              SDValue(FalseC, 0));
17102         }
17103
17104         // Optimize cases that will turn into an LEA instruction.  This requires
17105         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17106         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17107           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17108           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17109
17110           bool isFastMultiplier = false;
17111           if (Diff < 10) {
17112             switch ((unsigned char)Diff) {
17113               default: break;
17114               case 1:  // result = add base, cond
17115               case 2:  // result = lea base(    , cond*2)
17116               case 3:  // result = lea base(cond, cond*2)
17117               case 4:  // result = lea base(    , cond*4)
17118               case 5:  // result = lea base(cond, cond*4)
17119               case 8:  // result = lea base(    , cond*8)
17120               case 9:  // result = lea base(cond, cond*8)
17121                 isFastMultiplier = true;
17122                 break;
17123             }
17124           }
17125
17126           if (isFastMultiplier) {
17127             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17128             if (NeedsCondInvert) // Invert the condition if needed.
17129               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17130                                  DAG.getConstant(1, Cond.getValueType()));
17131
17132             // Zero extend the condition if needed.
17133             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17134                                Cond);
17135             // Scale the condition by the difference.
17136             if (Diff != 1)
17137               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17138                                  DAG.getConstant(Diff, Cond.getValueType()));
17139
17140             // Add the base if non-zero.
17141             if (FalseC->getAPIntValue() != 0)
17142               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17143                                  SDValue(FalseC, 0));
17144             return Cond;
17145           }
17146         }
17147       }
17148   }
17149
17150   // Canonicalize max and min:
17151   // (x > y) ? x : y -> (x >= y) ? x : y
17152   // (x < y) ? x : y -> (x <= y) ? x : y
17153   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17154   // the need for an extra compare
17155   // against zero. e.g.
17156   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17157   // subl   %esi, %edi
17158   // testl  %edi, %edi
17159   // movl   $0, %eax
17160   // cmovgl %edi, %eax
17161   // =>
17162   // xorl   %eax, %eax
17163   // subl   %esi, $edi
17164   // cmovsl %eax, %edi
17165   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17166       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17167       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17168     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17169     switch (CC) {
17170     default: break;
17171     case ISD::SETLT:
17172     case ISD::SETGT: {
17173       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17174       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17175                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17176       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17177     }
17178     }
17179   }
17180
17181   // Early exit check
17182   if (!TLI.isTypeLegal(VT))
17183     return SDValue();
17184
17185   // Match VSELECTs into subs with unsigned saturation.
17186   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17187       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17188       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17189        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17190     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17191
17192     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17193     // left side invert the predicate to simplify logic below.
17194     SDValue Other;
17195     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17196       Other = RHS;
17197       CC = ISD::getSetCCInverse(CC, true);
17198     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17199       Other = LHS;
17200     }
17201
17202     if (Other.getNode() && Other->getNumOperands() == 2 &&
17203         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17204       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17205       SDValue CondRHS = Cond->getOperand(1);
17206
17207       // Look for a general sub with unsigned saturation first.
17208       // x >= y ? x-y : 0 --> subus x, y
17209       // x >  y ? x-y : 0 --> subus x, y
17210       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17211           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17212         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17213
17214       // If the RHS is a constant we have to reverse the const canonicalization.
17215       // x > C-1 ? x+-C : 0 --> subus x, C
17216       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17217           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17218         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17219         if (CondRHS.getConstantOperandVal(0) == -A-1)
17220           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17221                              DAG.getConstant(-A, VT));
17222       }
17223
17224       // Another special case: If C was a sign bit, the sub has been
17225       // canonicalized into a xor.
17226       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17227       //        it's safe to decanonicalize the xor?
17228       // x s< 0 ? x^C : 0 --> subus x, C
17229       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17230           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17231           isSplatVector(OpRHS.getNode())) {
17232         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17233         if (A.isSignBit())
17234           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17235       }
17236     }
17237   }
17238
17239   // Try to match a min/max vector operation.
17240   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17241     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17242     unsigned Opc = ret.first;
17243     bool NeedSplit = ret.second;
17244
17245     if (Opc && NeedSplit) {
17246       unsigned NumElems = VT.getVectorNumElements();
17247       // Extract the LHS vectors
17248       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17249       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17250
17251       // Extract the RHS vectors
17252       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17253       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17254
17255       // Create min/max for each subvector
17256       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17257       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17258
17259       // Merge the result
17260       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17261     } else if (Opc)
17262       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17263   }
17264
17265   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17266   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17267       // Check if SETCC has already been promoted
17268       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17269       // Check that condition value type matches vselect operand type
17270       CondVT == VT) { 
17271
17272     assert(Cond.getValueType().isVector() &&
17273            "vector select expects a vector selector!");
17274
17275     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17276     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17277
17278     if (!TValIsAllOnes && !FValIsAllZeros) {
17279       // Try invert the condition if true value is not all 1s and false value
17280       // is not all 0s.
17281       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17282       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17283
17284       if (TValIsAllZeros || FValIsAllOnes) {
17285         SDValue CC = Cond.getOperand(2);
17286         ISD::CondCode NewCC =
17287           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17288                                Cond.getOperand(0).getValueType().isInteger());
17289         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17290         std::swap(LHS, RHS);
17291         TValIsAllOnes = FValIsAllOnes;
17292         FValIsAllZeros = TValIsAllZeros;
17293       }
17294     }
17295
17296     if (TValIsAllOnes || FValIsAllZeros) {
17297       SDValue Ret;
17298
17299       if (TValIsAllOnes && FValIsAllZeros)
17300         Ret = Cond;
17301       else if (TValIsAllOnes)
17302         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17303                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17304       else if (FValIsAllZeros)
17305         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17306                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17307
17308       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17309     }
17310   }
17311
17312   // Try to fold this VSELECT into a MOVSS/MOVSD
17313   if (N->getOpcode() == ISD::VSELECT &&
17314       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17315     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17316         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17317       bool CanFold = false;
17318       unsigned NumElems = Cond.getNumOperands();
17319       SDValue A = LHS;
17320       SDValue B = RHS;
17321       
17322       if (isZero(Cond.getOperand(0))) {
17323         CanFold = true;
17324
17325         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17326         // fold (vselect <0,-1> -> (movsd A, B)
17327         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17328           CanFold = isAllOnes(Cond.getOperand(i));
17329       } else if (isAllOnes(Cond.getOperand(0))) {
17330         CanFold = true;
17331         std::swap(A, B);
17332
17333         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17334         // fold (vselect <-1,0> -> (movsd B, A)
17335         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17336           CanFold = isZero(Cond.getOperand(i));
17337       }
17338
17339       if (CanFold) {
17340         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17341           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17342         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17343       }
17344
17345       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17346         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17347         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17348         //                             (v2i64 (bitcast B)))))
17349         //
17350         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17351         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17352         //                             (v2f64 (bitcast B)))))
17353         //
17354         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17355         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17356         //                             (v2i64 (bitcast A)))))
17357         //
17358         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17359         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17360         //                             (v2f64 (bitcast A)))))
17361
17362         CanFold = (isZero(Cond.getOperand(0)) &&
17363                    isZero(Cond.getOperand(1)) &&
17364                    isAllOnes(Cond.getOperand(2)) &&
17365                    isAllOnes(Cond.getOperand(3)));
17366
17367         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17368             isAllOnes(Cond.getOperand(1)) &&
17369             isZero(Cond.getOperand(2)) &&
17370             isZero(Cond.getOperand(3))) {
17371           CanFold = true;
17372           std::swap(LHS, RHS);
17373         }
17374
17375         if (CanFold) {
17376           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17377           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17378           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17379           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17380                                                 NewB, DAG);
17381           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17382         }
17383       }
17384     }
17385   }
17386
17387   // If we know that this node is legal then we know that it is going to be
17388   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17389   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17390   // to simplify previous instructions.
17391   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17392       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17393     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17394
17395     // Don't optimize vector selects that map to mask-registers.
17396     if (BitWidth == 1)
17397       return SDValue();
17398
17399     // Check all uses of that condition operand to check whether it will be
17400     // consumed by non-BLEND instructions, which may depend on all bits are set
17401     // properly.
17402     for (SDNode::use_iterator I = Cond->use_begin(),
17403                               E = Cond->use_end(); I != E; ++I)
17404       if (I->getOpcode() != ISD::VSELECT)
17405         // TODO: Add other opcodes eventually lowered into BLEND.
17406         return SDValue();
17407
17408     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17409     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17410
17411     APInt KnownZero, KnownOne;
17412     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17413                                           DCI.isBeforeLegalizeOps());
17414     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17415         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17416       DCI.CommitTargetLoweringOpt(TLO);
17417   }
17418
17419   return SDValue();
17420 }
17421
17422 // Check whether a boolean test is testing a boolean value generated by
17423 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17424 // code.
17425 //
17426 // Simplify the following patterns:
17427 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17428 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17429 // to (Op EFLAGS Cond)
17430 //
17431 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17432 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17433 // to (Op EFLAGS !Cond)
17434 //
17435 // where Op could be BRCOND or CMOV.
17436 //
17437 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17438   // Quit if not CMP and SUB with its value result used.
17439   if (Cmp.getOpcode() != X86ISD::CMP &&
17440       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17441       return SDValue();
17442
17443   // Quit if not used as a boolean value.
17444   if (CC != X86::COND_E && CC != X86::COND_NE)
17445     return SDValue();
17446
17447   // Check CMP operands. One of them should be 0 or 1 and the other should be
17448   // an SetCC or extended from it.
17449   SDValue Op1 = Cmp.getOperand(0);
17450   SDValue Op2 = Cmp.getOperand(1);
17451
17452   SDValue SetCC;
17453   const ConstantSDNode* C = 0;
17454   bool needOppositeCond = (CC == X86::COND_E);
17455   bool checkAgainstTrue = false; // Is it a comparison against 1?
17456
17457   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17458     SetCC = Op2;
17459   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17460     SetCC = Op1;
17461   else // Quit if all operands are not constants.
17462     return SDValue();
17463
17464   if (C->getZExtValue() == 1) {
17465     needOppositeCond = !needOppositeCond;
17466     checkAgainstTrue = true;
17467   } else if (C->getZExtValue() != 0)
17468     // Quit if the constant is neither 0 or 1.
17469     return SDValue();
17470
17471   bool truncatedToBoolWithAnd = false;
17472   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17473   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17474          SetCC.getOpcode() == ISD::TRUNCATE ||
17475          SetCC.getOpcode() == ISD::AND) {
17476     if (SetCC.getOpcode() == ISD::AND) {
17477       int OpIdx = -1;
17478       ConstantSDNode *CS;
17479       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17480           CS->getZExtValue() == 1)
17481         OpIdx = 1;
17482       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17483           CS->getZExtValue() == 1)
17484         OpIdx = 0;
17485       if (OpIdx == -1)
17486         break;
17487       SetCC = SetCC.getOperand(OpIdx);
17488       truncatedToBoolWithAnd = true;
17489     } else
17490       SetCC = SetCC.getOperand(0);
17491   }
17492
17493   switch (SetCC.getOpcode()) {
17494   case X86ISD::SETCC_CARRY:
17495     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17496     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17497     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17498     // truncated to i1 using 'and'.
17499     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17500       break;
17501     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17502            "Invalid use of SETCC_CARRY!");
17503     // FALL THROUGH
17504   case X86ISD::SETCC:
17505     // Set the condition code or opposite one if necessary.
17506     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17507     if (needOppositeCond)
17508       CC = X86::GetOppositeBranchCondition(CC);
17509     return SetCC.getOperand(1);
17510   case X86ISD::CMOV: {
17511     // Check whether false/true value has canonical one, i.e. 0 or 1.
17512     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17513     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17514     // Quit if true value is not a constant.
17515     if (!TVal)
17516       return SDValue();
17517     // Quit if false value is not a constant.
17518     if (!FVal) {
17519       SDValue Op = SetCC.getOperand(0);
17520       // Skip 'zext' or 'trunc' node.
17521       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17522           Op.getOpcode() == ISD::TRUNCATE)
17523         Op = Op.getOperand(0);
17524       // A special case for rdrand/rdseed, where 0 is set if false cond is
17525       // found.
17526       if ((Op.getOpcode() != X86ISD::RDRAND &&
17527            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17528         return SDValue();
17529     }
17530     // Quit if false value is not the constant 0 or 1.
17531     bool FValIsFalse = true;
17532     if (FVal && FVal->getZExtValue() != 0) {
17533       if (FVal->getZExtValue() != 1)
17534         return SDValue();
17535       // If FVal is 1, opposite cond is needed.
17536       needOppositeCond = !needOppositeCond;
17537       FValIsFalse = false;
17538     }
17539     // Quit if TVal is not the constant opposite of FVal.
17540     if (FValIsFalse && TVal->getZExtValue() != 1)
17541       return SDValue();
17542     if (!FValIsFalse && TVal->getZExtValue() != 0)
17543       return SDValue();
17544     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17545     if (needOppositeCond)
17546       CC = X86::GetOppositeBranchCondition(CC);
17547     return SetCC.getOperand(3);
17548   }
17549   }
17550
17551   return SDValue();
17552 }
17553
17554 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17555 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17556                                   TargetLowering::DAGCombinerInfo &DCI,
17557                                   const X86Subtarget *Subtarget) {
17558   SDLoc DL(N);
17559
17560   // If the flag operand isn't dead, don't touch this CMOV.
17561   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17562     return SDValue();
17563
17564   SDValue FalseOp = N->getOperand(0);
17565   SDValue TrueOp = N->getOperand(1);
17566   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17567   SDValue Cond = N->getOperand(3);
17568
17569   if (CC == X86::COND_E || CC == X86::COND_NE) {
17570     switch (Cond.getOpcode()) {
17571     default: break;
17572     case X86ISD::BSR:
17573     case X86ISD::BSF:
17574       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17575       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17576         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17577     }
17578   }
17579
17580   SDValue Flags;
17581
17582   Flags = checkBoolTestSetCCCombine(Cond, CC);
17583   if (Flags.getNode() &&
17584       // Extra check as FCMOV only supports a subset of X86 cond.
17585       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17586     SDValue Ops[] = { FalseOp, TrueOp,
17587                       DAG.getConstant(CC, MVT::i8), Flags };
17588     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17589                        Ops, array_lengthof(Ops));
17590   }
17591
17592   // If this is a select between two integer constants, try to do some
17593   // optimizations.  Note that the operands are ordered the opposite of SELECT
17594   // operands.
17595   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17596     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17597       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17598       // larger than FalseC (the false value).
17599       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17600         CC = X86::GetOppositeBranchCondition(CC);
17601         std::swap(TrueC, FalseC);
17602         std::swap(TrueOp, FalseOp);
17603       }
17604
17605       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17606       // This is efficient for any integer data type (including i8/i16) and
17607       // shift amount.
17608       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17609         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17610                            DAG.getConstant(CC, MVT::i8), Cond);
17611
17612         // Zero extend the condition if needed.
17613         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17614
17615         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17616         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17617                            DAG.getConstant(ShAmt, MVT::i8));
17618         if (N->getNumValues() == 2)  // Dead flag value?
17619           return DCI.CombineTo(N, Cond, SDValue());
17620         return Cond;
17621       }
17622
17623       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17624       // for any integer data type, including i8/i16.
17625       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17626         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17627                            DAG.getConstant(CC, MVT::i8), Cond);
17628
17629         // Zero extend the condition if needed.
17630         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17631                            FalseC->getValueType(0), Cond);
17632         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17633                            SDValue(FalseC, 0));
17634
17635         if (N->getNumValues() == 2)  // Dead flag value?
17636           return DCI.CombineTo(N, Cond, SDValue());
17637         return Cond;
17638       }
17639
17640       // Optimize cases that will turn into an LEA instruction.  This requires
17641       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17642       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17643         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17644         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17645
17646         bool isFastMultiplier = false;
17647         if (Diff < 10) {
17648           switch ((unsigned char)Diff) {
17649           default: break;
17650           case 1:  // result = add base, cond
17651           case 2:  // result = lea base(    , cond*2)
17652           case 3:  // result = lea base(cond, cond*2)
17653           case 4:  // result = lea base(    , cond*4)
17654           case 5:  // result = lea base(cond, cond*4)
17655           case 8:  // result = lea base(    , cond*8)
17656           case 9:  // result = lea base(cond, cond*8)
17657             isFastMultiplier = true;
17658             break;
17659           }
17660         }
17661
17662         if (isFastMultiplier) {
17663           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17664           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17665                              DAG.getConstant(CC, MVT::i8), Cond);
17666           // Zero extend the condition if needed.
17667           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17668                              Cond);
17669           // Scale the condition by the difference.
17670           if (Diff != 1)
17671             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17672                                DAG.getConstant(Diff, Cond.getValueType()));
17673
17674           // Add the base if non-zero.
17675           if (FalseC->getAPIntValue() != 0)
17676             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17677                                SDValue(FalseC, 0));
17678           if (N->getNumValues() == 2)  // Dead flag value?
17679             return DCI.CombineTo(N, Cond, SDValue());
17680           return Cond;
17681         }
17682       }
17683     }
17684   }
17685
17686   // Handle these cases:
17687   //   (select (x != c), e, c) -> select (x != c), e, x),
17688   //   (select (x == c), c, e) -> select (x == c), x, e)
17689   // where the c is an integer constant, and the "select" is the combination
17690   // of CMOV and CMP.
17691   //
17692   // The rationale for this change is that the conditional-move from a constant
17693   // needs two instructions, however, conditional-move from a register needs
17694   // only one instruction.
17695   //
17696   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17697   //  some instruction-combining opportunities. This opt needs to be
17698   //  postponed as late as possible.
17699   //
17700   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17701     // the DCI.xxxx conditions are provided to postpone the optimization as
17702     // late as possible.
17703
17704     ConstantSDNode *CmpAgainst = 0;
17705     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17706         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17707         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17708
17709       if (CC == X86::COND_NE &&
17710           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17711         CC = X86::GetOppositeBranchCondition(CC);
17712         std::swap(TrueOp, FalseOp);
17713       }
17714
17715       if (CC == X86::COND_E &&
17716           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17717         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17718                           DAG.getConstant(CC, MVT::i8), Cond };
17719         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17720                            array_lengthof(Ops));
17721       }
17722     }
17723   }
17724
17725   return SDValue();
17726 }
17727
17728 /// PerformMulCombine - Optimize a single multiply with constant into two
17729 /// in order to implement it with two cheaper instructions, e.g.
17730 /// LEA + SHL, LEA + LEA.
17731 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17732                                  TargetLowering::DAGCombinerInfo &DCI) {
17733   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17734     return SDValue();
17735
17736   EVT VT = N->getValueType(0);
17737   if (VT != MVT::i64)
17738     return SDValue();
17739
17740   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17741   if (!C)
17742     return SDValue();
17743   uint64_t MulAmt = C->getZExtValue();
17744   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17745     return SDValue();
17746
17747   uint64_t MulAmt1 = 0;
17748   uint64_t MulAmt2 = 0;
17749   if ((MulAmt % 9) == 0) {
17750     MulAmt1 = 9;
17751     MulAmt2 = MulAmt / 9;
17752   } else if ((MulAmt % 5) == 0) {
17753     MulAmt1 = 5;
17754     MulAmt2 = MulAmt / 5;
17755   } else if ((MulAmt % 3) == 0) {
17756     MulAmt1 = 3;
17757     MulAmt2 = MulAmt / 3;
17758   }
17759   if (MulAmt2 &&
17760       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17761     SDLoc DL(N);
17762
17763     if (isPowerOf2_64(MulAmt2) &&
17764         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17765       // If second multiplifer is pow2, issue it first. We want the multiply by
17766       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17767       // is an add.
17768       std::swap(MulAmt1, MulAmt2);
17769
17770     SDValue NewMul;
17771     if (isPowerOf2_64(MulAmt1))
17772       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17773                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17774     else
17775       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17776                            DAG.getConstant(MulAmt1, VT));
17777
17778     if (isPowerOf2_64(MulAmt2))
17779       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17780                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17781     else
17782       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17783                            DAG.getConstant(MulAmt2, VT));
17784
17785     // Do not add new nodes to DAG combiner worklist.
17786     DCI.CombineTo(N, NewMul, false);
17787   }
17788   return SDValue();
17789 }
17790
17791 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17792   SDValue N0 = N->getOperand(0);
17793   SDValue N1 = N->getOperand(1);
17794   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17795   EVT VT = N0.getValueType();
17796
17797   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17798   // since the result of setcc_c is all zero's or all ones.
17799   if (VT.isInteger() && !VT.isVector() &&
17800       N1C && N0.getOpcode() == ISD::AND &&
17801       N0.getOperand(1).getOpcode() == ISD::Constant) {
17802     SDValue N00 = N0.getOperand(0);
17803     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17804         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17805           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17806          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17807       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17808       APInt ShAmt = N1C->getAPIntValue();
17809       Mask = Mask.shl(ShAmt);
17810       if (Mask != 0)
17811         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17812                            N00, DAG.getConstant(Mask, VT));
17813     }
17814   }
17815
17816   // Hardware support for vector shifts is sparse which makes us scalarize the
17817   // vector operations in many cases. Also, on sandybridge ADD is faster than
17818   // shl.
17819   // (shl V, 1) -> add V,V
17820   if (isSplatVector(N1.getNode())) {
17821     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17822     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17823     // We shift all of the values by one. In many cases we do not have
17824     // hardware support for this operation. This is better expressed as an ADD
17825     // of two values.
17826     if (N1C && (1 == N1C->getZExtValue())) {
17827       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17828     }
17829   }
17830
17831   return SDValue();
17832 }
17833
17834 /// \brief Returns a vector of 0s if the node in input is a vector logical
17835 /// shift by a constant amount which is known to be bigger than or equal
17836 /// to the vector element size in bits.
17837 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17838                                       const X86Subtarget *Subtarget) {
17839   EVT VT = N->getValueType(0);
17840
17841   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17842       (!Subtarget->hasInt256() ||
17843        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17844     return SDValue();
17845
17846   SDValue Amt = N->getOperand(1);
17847   SDLoc DL(N);
17848   if (isSplatVector(Amt.getNode())) {
17849     SDValue SclrAmt = Amt->getOperand(0);
17850     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17851       APInt ShiftAmt = C->getAPIntValue();
17852       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17853
17854       // SSE2/AVX2 logical shifts always return a vector of 0s
17855       // if the shift amount is bigger than or equal to
17856       // the element size. The constant shift amount will be
17857       // encoded as a 8-bit immediate.
17858       if (ShiftAmt.trunc(8).uge(MaxAmount))
17859         return getZeroVector(VT, Subtarget, DAG, DL);
17860     }
17861   }
17862
17863   return SDValue();
17864 }
17865
17866 /// PerformShiftCombine - Combine shifts.
17867 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17868                                    TargetLowering::DAGCombinerInfo &DCI,
17869                                    const X86Subtarget *Subtarget) {
17870   if (N->getOpcode() == ISD::SHL) {
17871     SDValue V = PerformSHLCombine(N, DAG);
17872     if (V.getNode()) return V;
17873   }
17874
17875   if (N->getOpcode() != ISD::SRA) {
17876     // Try to fold this logical shift into a zero vector.
17877     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17878     if (V.getNode()) return V;
17879   }
17880
17881   return SDValue();
17882 }
17883
17884 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17885 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17886 // and friends.  Likewise for OR -> CMPNEQSS.
17887 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17888                             TargetLowering::DAGCombinerInfo &DCI,
17889                             const X86Subtarget *Subtarget) {
17890   unsigned opcode;
17891
17892   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17893   // we're requiring SSE2 for both.
17894   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17895     SDValue N0 = N->getOperand(0);
17896     SDValue N1 = N->getOperand(1);
17897     SDValue CMP0 = N0->getOperand(1);
17898     SDValue CMP1 = N1->getOperand(1);
17899     SDLoc DL(N);
17900
17901     // The SETCCs should both refer to the same CMP.
17902     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17903       return SDValue();
17904
17905     SDValue CMP00 = CMP0->getOperand(0);
17906     SDValue CMP01 = CMP0->getOperand(1);
17907     EVT     VT    = CMP00.getValueType();
17908
17909     if (VT == MVT::f32 || VT == MVT::f64) {
17910       bool ExpectingFlags = false;
17911       // Check for any users that want flags:
17912       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17913            !ExpectingFlags && UI != UE; ++UI)
17914         switch (UI->getOpcode()) {
17915         default:
17916         case ISD::BR_CC:
17917         case ISD::BRCOND:
17918         case ISD::SELECT:
17919           ExpectingFlags = true;
17920           break;
17921         case ISD::CopyToReg:
17922         case ISD::SIGN_EXTEND:
17923         case ISD::ZERO_EXTEND:
17924         case ISD::ANY_EXTEND:
17925           break;
17926         }
17927
17928       if (!ExpectingFlags) {
17929         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17930         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17931
17932         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17933           X86::CondCode tmp = cc0;
17934           cc0 = cc1;
17935           cc1 = tmp;
17936         }
17937
17938         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17939             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17940           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17941           // FIXME: need symbolic constants for these magic numbers.
17942           // See X86ATTInstPrinter.cpp:printSSECC().
17943           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17944           if (Subtarget->hasAVX512()) {
17945             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
17946                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
17947             if (N->getValueType(0) != MVT::i1)
17948               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
17949                                  FSetCC);
17950             return FSetCC;
17951           }
17952           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
17953                                               CMP00.getValueType(), CMP00, CMP01,
17954                                               DAG.getConstant(x86cc, MVT::i8));
17955           MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32); 
17956           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17957                                               OnesOrZeroesF);
17958           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17959                                       DAG.getConstant(1, IntVT));
17960           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17961           return OneBitOfTruth;
17962         }
17963       }
17964     }
17965   }
17966   return SDValue();
17967 }
17968
17969 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17970 /// so it can be folded inside ANDNP.
17971 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17972   EVT VT = N->getValueType(0);
17973
17974   // Match direct AllOnes for 128 and 256-bit vectors
17975   if (ISD::isBuildVectorAllOnes(N))
17976     return true;
17977
17978   // Look through a bit convert.
17979   if (N->getOpcode() == ISD::BITCAST)
17980     N = N->getOperand(0).getNode();
17981
17982   // Sometimes the operand may come from a insert_subvector building a 256-bit
17983   // allones vector
17984   if (VT.is256BitVector() &&
17985       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17986     SDValue V1 = N->getOperand(0);
17987     SDValue V2 = N->getOperand(1);
17988
17989     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17990         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17991         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17992         ISD::isBuildVectorAllOnes(V2.getNode()))
17993       return true;
17994   }
17995
17996   return false;
17997 }
17998
17999 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18000 // register. In most cases we actually compare or select YMM-sized registers
18001 // and mixing the two types creates horrible code. This method optimizes
18002 // some of the transition sequences.
18003 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18004                                  TargetLowering::DAGCombinerInfo &DCI,
18005                                  const X86Subtarget *Subtarget) {
18006   EVT VT = N->getValueType(0);
18007   if (!VT.is256BitVector())
18008     return SDValue();
18009
18010   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18011           N->getOpcode() == ISD::ZERO_EXTEND ||
18012           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18013
18014   SDValue Narrow = N->getOperand(0);
18015   EVT NarrowVT = Narrow->getValueType(0);
18016   if (!NarrowVT.is128BitVector())
18017     return SDValue();
18018
18019   if (Narrow->getOpcode() != ISD::XOR &&
18020       Narrow->getOpcode() != ISD::AND &&
18021       Narrow->getOpcode() != ISD::OR)
18022     return SDValue();
18023
18024   SDValue N0  = Narrow->getOperand(0);
18025   SDValue N1  = Narrow->getOperand(1);
18026   SDLoc DL(Narrow);
18027
18028   // The Left side has to be a trunc.
18029   if (N0.getOpcode() != ISD::TRUNCATE)
18030     return SDValue();
18031
18032   // The type of the truncated inputs.
18033   EVT WideVT = N0->getOperand(0)->getValueType(0);
18034   if (WideVT != VT)
18035     return SDValue();
18036
18037   // The right side has to be a 'trunc' or a constant vector.
18038   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18039   bool RHSConst = (isSplatVector(N1.getNode()) &&
18040                    isa<ConstantSDNode>(N1->getOperand(0)));
18041   if (!RHSTrunc && !RHSConst)
18042     return SDValue();
18043
18044   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18045
18046   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18047     return SDValue();
18048
18049   // Set N0 and N1 to hold the inputs to the new wide operation.
18050   N0 = N0->getOperand(0);
18051   if (RHSConst) {
18052     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18053                      N1->getOperand(0));
18054     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18055     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18056   } else if (RHSTrunc) {
18057     N1 = N1->getOperand(0);
18058   }
18059
18060   // Generate the wide operation.
18061   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18062   unsigned Opcode = N->getOpcode();
18063   switch (Opcode) {
18064   case ISD::ANY_EXTEND:
18065     return Op;
18066   case ISD::ZERO_EXTEND: {
18067     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18068     APInt Mask = APInt::getAllOnesValue(InBits);
18069     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18070     return DAG.getNode(ISD::AND, DL, VT,
18071                        Op, DAG.getConstant(Mask, VT));
18072   }
18073   case ISD::SIGN_EXTEND:
18074     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18075                        Op, DAG.getValueType(NarrowVT));
18076   default:
18077     llvm_unreachable("Unexpected opcode");
18078   }
18079 }
18080
18081 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18082                                  TargetLowering::DAGCombinerInfo &DCI,
18083                                  const X86Subtarget *Subtarget) {
18084   EVT VT = N->getValueType(0);
18085   if (DCI.isBeforeLegalizeOps())
18086     return SDValue();
18087
18088   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18089   if (R.getNode())
18090     return R;
18091
18092   // Create BLSI, BLSR, and BZHI instructions
18093   // BLSI is X & (-X)
18094   // BLSR is X & (X-1)
18095   // BZHI is X & ((1 << Y) - 1)
18096   // BEXTR is ((X >> imm) & (2**size-1))
18097   if (VT == MVT::i32 || VT == MVT::i64) {
18098     SDValue N0 = N->getOperand(0);
18099     SDValue N1 = N->getOperand(1);
18100     SDLoc DL(N);
18101
18102     if (Subtarget->hasBMI()) {
18103       // Check LHS for neg
18104       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
18105           isZero(N0.getOperand(0)))
18106         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
18107
18108       // Check RHS for neg
18109       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
18110           isZero(N1.getOperand(0)))
18111         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
18112
18113       // Check LHS for X-1
18114       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18115           isAllOnes(N0.getOperand(1)))
18116         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
18117
18118       // Check RHS for X-1
18119       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18120           isAllOnes(N1.getOperand(1)))
18121         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
18122     }
18123
18124     if (Subtarget->hasBMI2()) {
18125       // Check for (and (add (shl 1, Y), -1), X)
18126       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18127         SDValue N00 = N0.getOperand(0);
18128         if (N00.getOpcode() == ISD::SHL) {
18129           SDValue N001 = N00.getOperand(1);
18130           assert(N001.getValueType() == MVT::i8 && "unexpected type");
18131           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18132           if (C && C->getZExtValue() == 1)
18133             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18134         }
18135       }
18136
18137       // Check for (and X, (add (shl 1, Y), -1))
18138       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18139         SDValue N10 = N1.getOperand(0);
18140         if (N10.getOpcode() == ISD::SHL) {
18141           SDValue N101 = N10.getOperand(1);
18142           assert(N101.getValueType() == MVT::i8 && "unexpected type");
18143           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18144           if (C && C->getZExtValue() == 1)
18145             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18146         }
18147       }
18148     }
18149
18150     // Check for BEXTR.
18151     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18152         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18153       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18154       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18155       if (MaskNode && ShiftNode) {
18156         uint64_t Mask = MaskNode->getZExtValue();
18157         uint64_t Shift = ShiftNode->getZExtValue();
18158         if (isMask_64(Mask)) {
18159           uint64_t MaskSize = CountPopulation_64(Mask);
18160           if (Shift + MaskSize <= VT.getSizeInBits())
18161             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18162                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18163         }
18164       }
18165     } // BEXTR
18166
18167     return SDValue();
18168   }
18169
18170   // Want to form ANDNP nodes:
18171   // 1) In the hopes of then easily combining them with OR and AND nodes
18172   //    to form PBLEND/PSIGN.
18173   // 2) To match ANDN packed intrinsics
18174   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18175     return SDValue();
18176
18177   SDValue N0 = N->getOperand(0);
18178   SDValue N1 = N->getOperand(1);
18179   SDLoc DL(N);
18180
18181   // Check LHS for vnot
18182   if (N0.getOpcode() == ISD::XOR &&
18183       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18184       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18185     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18186
18187   // Check RHS for vnot
18188   if (N1.getOpcode() == ISD::XOR &&
18189       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18190       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18191     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18192
18193   return SDValue();
18194 }
18195
18196 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18197                                 TargetLowering::DAGCombinerInfo &DCI,
18198                                 const X86Subtarget *Subtarget) {
18199   if (DCI.isBeforeLegalizeOps())
18200     return SDValue();
18201
18202   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18203   if (R.getNode())
18204     return R;
18205
18206   SDValue N0 = N->getOperand(0);
18207   SDValue N1 = N->getOperand(1);
18208   EVT VT = N->getValueType(0);
18209
18210   // look for psign/blend
18211   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18212     if (!Subtarget->hasSSSE3() ||
18213         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18214       return SDValue();
18215
18216     // Canonicalize pandn to RHS
18217     if (N0.getOpcode() == X86ISD::ANDNP)
18218       std::swap(N0, N1);
18219     // or (and (m, y), (pandn m, x))
18220     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18221       SDValue Mask = N1.getOperand(0);
18222       SDValue X    = N1.getOperand(1);
18223       SDValue Y;
18224       if (N0.getOperand(0) == Mask)
18225         Y = N0.getOperand(1);
18226       if (N0.getOperand(1) == Mask)
18227         Y = N0.getOperand(0);
18228
18229       // Check to see if the mask appeared in both the AND and ANDNP and
18230       if (!Y.getNode())
18231         return SDValue();
18232
18233       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18234       // Look through mask bitcast.
18235       if (Mask.getOpcode() == ISD::BITCAST)
18236         Mask = Mask.getOperand(0);
18237       if (X.getOpcode() == ISD::BITCAST)
18238         X = X.getOperand(0);
18239       if (Y.getOpcode() == ISD::BITCAST)
18240         Y = Y.getOperand(0);
18241
18242       EVT MaskVT = Mask.getValueType();
18243
18244       // Validate that the Mask operand is a vector sra node.
18245       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18246       // there is no psrai.b
18247       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18248       unsigned SraAmt = ~0;
18249       if (Mask.getOpcode() == ISD::SRA) {
18250         SDValue Amt = Mask.getOperand(1);
18251         if (isSplatVector(Amt.getNode())) {
18252           SDValue SclrAmt = Amt->getOperand(0);
18253           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18254             SraAmt = C->getZExtValue();
18255         }
18256       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18257         SDValue SraC = Mask.getOperand(1);
18258         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18259       }
18260       if ((SraAmt + 1) != EltBits)
18261         return SDValue();
18262
18263       SDLoc DL(N);
18264
18265       // Now we know we at least have a plendvb with the mask val.  See if
18266       // we can form a psignb/w/d.
18267       // psign = x.type == y.type == mask.type && y = sub(0, x);
18268       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18269           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18270           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18271         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18272                "Unsupported VT for PSIGN");
18273         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18274         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18275       }
18276       // PBLENDVB only available on SSE 4.1
18277       if (!Subtarget->hasSSE41())
18278         return SDValue();
18279
18280       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18281
18282       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18283       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18284       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18285       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18286       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18287     }
18288   }
18289
18290   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18291     return SDValue();
18292
18293   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18294   MachineFunction &MF = DAG.getMachineFunction();
18295   bool OptForSize = MF.getFunction()->getAttributes().
18296     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18297
18298   // SHLD/SHRD instructions have lower register pressure, but on some
18299   // platforms they have higher latency than the equivalent
18300   // series of shifts/or that would otherwise be generated.
18301   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18302   // have higher latencies and we are not optimizing for size.
18303   if (!OptForSize && Subtarget->isSHLDSlow())
18304     return SDValue();
18305
18306   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18307     std::swap(N0, N1);
18308   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18309     return SDValue();
18310   if (!N0.hasOneUse() || !N1.hasOneUse())
18311     return SDValue();
18312
18313   SDValue ShAmt0 = N0.getOperand(1);
18314   if (ShAmt0.getValueType() != MVT::i8)
18315     return SDValue();
18316   SDValue ShAmt1 = N1.getOperand(1);
18317   if (ShAmt1.getValueType() != MVT::i8)
18318     return SDValue();
18319   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18320     ShAmt0 = ShAmt0.getOperand(0);
18321   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18322     ShAmt1 = ShAmt1.getOperand(0);
18323
18324   SDLoc DL(N);
18325   unsigned Opc = X86ISD::SHLD;
18326   SDValue Op0 = N0.getOperand(0);
18327   SDValue Op1 = N1.getOperand(0);
18328   if (ShAmt0.getOpcode() == ISD::SUB) {
18329     Opc = X86ISD::SHRD;
18330     std::swap(Op0, Op1);
18331     std::swap(ShAmt0, ShAmt1);
18332   }
18333
18334   unsigned Bits = VT.getSizeInBits();
18335   if (ShAmt1.getOpcode() == ISD::SUB) {
18336     SDValue Sum = ShAmt1.getOperand(0);
18337     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18338       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18339       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18340         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18341       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18342         return DAG.getNode(Opc, DL, VT,
18343                            Op0, Op1,
18344                            DAG.getNode(ISD::TRUNCATE, DL,
18345                                        MVT::i8, ShAmt0));
18346     }
18347   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18348     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18349     if (ShAmt0C &&
18350         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18351       return DAG.getNode(Opc, DL, VT,
18352                          N0.getOperand(0), N1.getOperand(0),
18353                          DAG.getNode(ISD::TRUNCATE, DL,
18354                                        MVT::i8, ShAmt0));
18355   }
18356
18357   return SDValue();
18358 }
18359
18360 // Generate NEG and CMOV for integer abs.
18361 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18362   EVT VT = N->getValueType(0);
18363
18364   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18365   // 8-bit integer abs to NEG and CMOV.
18366   if (VT.isInteger() && VT.getSizeInBits() == 8)
18367     return SDValue();
18368
18369   SDValue N0 = N->getOperand(0);
18370   SDValue N1 = N->getOperand(1);
18371   SDLoc DL(N);
18372
18373   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18374   // and change it to SUB and CMOV.
18375   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18376       N0.getOpcode() == ISD::ADD &&
18377       N0.getOperand(1) == N1 &&
18378       N1.getOpcode() == ISD::SRA &&
18379       N1.getOperand(0) == N0.getOperand(0))
18380     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18381       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18382         // Generate SUB & CMOV.
18383         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18384                                   DAG.getConstant(0, VT), N0.getOperand(0));
18385
18386         SDValue Ops[] = { N0.getOperand(0), Neg,
18387                           DAG.getConstant(X86::COND_GE, MVT::i8),
18388                           SDValue(Neg.getNode(), 1) };
18389         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18390                            Ops, array_lengthof(Ops));
18391       }
18392   return SDValue();
18393 }
18394
18395 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18396 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18397                                  TargetLowering::DAGCombinerInfo &DCI,
18398                                  const X86Subtarget *Subtarget) {
18399   EVT VT = N->getValueType(0);
18400   if (DCI.isBeforeLegalizeOps())
18401     return SDValue();
18402
18403   if (Subtarget->hasCMov()) {
18404     SDValue RV = performIntegerAbsCombine(N, DAG);
18405     if (RV.getNode())
18406       return RV;
18407   }
18408
18409   // Try forming BMI if it is available.
18410   if (!Subtarget->hasBMI())
18411     return SDValue();
18412
18413   if (VT != MVT::i32 && VT != MVT::i64)
18414     return SDValue();
18415
18416   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18417
18418   // Create BLSMSK instructions by finding X ^ (X-1)
18419   SDValue N0 = N->getOperand(0);
18420   SDValue N1 = N->getOperand(1);
18421   SDLoc DL(N);
18422
18423   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18424       isAllOnes(N0.getOperand(1)))
18425     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18426
18427   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18428       isAllOnes(N1.getOperand(1)))
18429     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18430
18431   return SDValue();
18432 }
18433
18434 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18435 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18436                                   TargetLowering::DAGCombinerInfo &DCI,
18437                                   const X86Subtarget *Subtarget) {
18438   LoadSDNode *Ld = cast<LoadSDNode>(N);
18439   EVT RegVT = Ld->getValueType(0);
18440   EVT MemVT = Ld->getMemoryVT();
18441   SDLoc dl(Ld);
18442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18443   unsigned RegSz = RegVT.getSizeInBits();
18444
18445   // On Sandybridge unaligned 256bit loads are inefficient.
18446   ISD::LoadExtType Ext = Ld->getExtensionType();
18447   unsigned Alignment = Ld->getAlignment();
18448   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18449   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18450       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18451     unsigned NumElems = RegVT.getVectorNumElements();
18452     if (NumElems < 2)
18453       return SDValue();
18454
18455     SDValue Ptr = Ld->getBasePtr();
18456     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18457
18458     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18459                                   NumElems/2);
18460     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18461                                 Ld->getPointerInfo(), Ld->isVolatile(),
18462                                 Ld->isNonTemporal(), Ld->isInvariant(),
18463                                 Alignment);
18464     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18465     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18466                                 Ld->getPointerInfo(), Ld->isVolatile(),
18467                                 Ld->isNonTemporal(), Ld->isInvariant(),
18468                                 std::min(16U, Alignment));
18469     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18470                              Load1.getValue(1),
18471                              Load2.getValue(1));
18472
18473     SDValue NewVec = DAG.getUNDEF(RegVT);
18474     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18475     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18476     return DCI.CombineTo(N, NewVec, TF, true);
18477   }
18478
18479   // If this is a vector EXT Load then attempt to optimize it using a
18480   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18481   // expansion is still better than scalar code.
18482   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18483   // emit a shuffle and a arithmetic shift.
18484   // TODO: It is possible to support ZExt by zeroing the undef values
18485   // during the shuffle phase or after the shuffle.
18486   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18487       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18488     assert(MemVT != RegVT && "Cannot extend to the same type");
18489     assert(MemVT.isVector() && "Must load a vector from memory");
18490
18491     unsigned NumElems = RegVT.getVectorNumElements();
18492     unsigned MemSz = MemVT.getSizeInBits();
18493     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18494
18495     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18496       return SDValue();
18497
18498     // All sizes must be a power of two.
18499     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18500       return SDValue();
18501
18502     // Attempt to load the original value using scalar loads.
18503     // Find the largest scalar type that divides the total loaded size.
18504     MVT SclrLoadTy = MVT::i8;
18505     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18506          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18507       MVT Tp = (MVT::SimpleValueType)tp;
18508       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18509         SclrLoadTy = Tp;
18510       }
18511     }
18512
18513     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18514     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18515         (64 <= MemSz))
18516       SclrLoadTy = MVT::f64;
18517
18518     // Calculate the number of scalar loads that we need to perform
18519     // in order to load our vector from memory.
18520     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18521     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18522       return SDValue();
18523
18524     unsigned loadRegZize = RegSz;
18525     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18526       loadRegZize /= 2;
18527
18528     // Represent our vector as a sequence of elements which are the
18529     // largest scalar that we can load.
18530     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18531       loadRegZize/SclrLoadTy.getSizeInBits());
18532
18533     // Represent the data using the same element type that is stored in
18534     // memory. In practice, we ''widen'' MemVT.
18535     EVT WideVecVT =
18536           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18537                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18538
18539     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18540       "Invalid vector type");
18541
18542     // We can't shuffle using an illegal type.
18543     if (!TLI.isTypeLegal(WideVecVT))
18544       return SDValue();
18545
18546     SmallVector<SDValue, 8> Chains;
18547     SDValue Ptr = Ld->getBasePtr();
18548     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18549                                         TLI.getPointerTy());
18550     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18551
18552     for (unsigned i = 0; i < NumLoads; ++i) {
18553       // Perform a single load.
18554       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18555                                        Ptr, Ld->getPointerInfo(),
18556                                        Ld->isVolatile(), Ld->isNonTemporal(),
18557                                        Ld->isInvariant(), Ld->getAlignment());
18558       Chains.push_back(ScalarLoad.getValue(1));
18559       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18560       // another round of DAGCombining.
18561       if (i == 0)
18562         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18563       else
18564         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18565                           ScalarLoad, DAG.getIntPtrConstant(i));
18566
18567       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18568     }
18569
18570     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18571                                Chains.size());
18572
18573     // Bitcast the loaded value to a vector of the original element type, in
18574     // the size of the target vector type.
18575     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18576     unsigned SizeRatio = RegSz/MemSz;
18577
18578     if (Ext == ISD::SEXTLOAD) {
18579       // If we have SSE4.1 we can directly emit a VSEXT node.
18580       if (Subtarget->hasSSE41()) {
18581         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18582         return DCI.CombineTo(N, Sext, TF, true);
18583       }
18584
18585       // Otherwise we'll shuffle the small elements in the high bits of the
18586       // larger type and perform an arithmetic shift. If the shift is not legal
18587       // it's better to scalarize.
18588       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18589         return SDValue();
18590
18591       // Redistribute the loaded elements into the different locations.
18592       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18593       for (unsigned i = 0; i != NumElems; ++i)
18594         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18595
18596       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18597                                            DAG.getUNDEF(WideVecVT),
18598                                            &ShuffleVec[0]);
18599
18600       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18601
18602       // Build the arithmetic shift.
18603       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18604                      MemVT.getVectorElementType().getSizeInBits();
18605       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18606                           DAG.getConstant(Amt, RegVT));
18607
18608       return DCI.CombineTo(N, Shuff, TF, true);
18609     }
18610
18611     // Redistribute the loaded elements into the different locations.
18612     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18613     for (unsigned i = 0; i != NumElems; ++i)
18614       ShuffleVec[i*SizeRatio] = i;
18615
18616     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18617                                          DAG.getUNDEF(WideVecVT),
18618                                          &ShuffleVec[0]);
18619
18620     // Bitcast to the requested type.
18621     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18622     // Replace the original load with the new sequence
18623     // and return the new chain.
18624     return DCI.CombineTo(N, Shuff, TF, true);
18625   }
18626
18627   return SDValue();
18628 }
18629
18630 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18631 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18632                                    const X86Subtarget *Subtarget) {
18633   StoreSDNode *St = cast<StoreSDNode>(N);
18634   EVT VT = St->getValue().getValueType();
18635   EVT StVT = St->getMemoryVT();
18636   SDLoc dl(St);
18637   SDValue StoredVal = St->getOperand(1);
18638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18639
18640   // If we are saving a concatenation of two XMM registers, perform two stores.
18641   // On Sandy Bridge, 256-bit memory operations are executed by two
18642   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18643   // memory  operation.
18644   unsigned Alignment = St->getAlignment();
18645   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18646   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18647       StVT == VT && !IsAligned) {
18648     unsigned NumElems = VT.getVectorNumElements();
18649     if (NumElems < 2)
18650       return SDValue();
18651
18652     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18653     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18654
18655     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18656     SDValue Ptr0 = St->getBasePtr();
18657     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18658
18659     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18660                                 St->getPointerInfo(), St->isVolatile(),
18661                                 St->isNonTemporal(), Alignment);
18662     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18663                                 St->getPointerInfo(), St->isVolatile(),
18664                                 St->isNonTemporal(),
18665                                 std::min(16U, Alignment));
18666     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18667   }
18668
18669   // Optimize trunc store (of multiple scalars) to shuffle and store.
18670   // First, pack all of the elements in one place. Next, store to memory
18671   // in fewer chunks.
18672   if (St->isTruncatingStore() && VT.isVector()) {
18673     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18674     unsigned NumElems = VT.getVectorNumElements();
18675     assert(StVT != VT && "Cannot truncate to the same type");
18676     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18677     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18678
18679     // From, To sizes and ElemCount must be pow of two
18680     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18681     // We are going to use the original vector elt for storing.
18682     // Accumulated smaller vector elements must be a multiple of the store size.
18683     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18684
18685     unsigned SizeRatio  = FromSz / ToSz;
18686
18687     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18688
18689     // Create a type on which we perform the shuffle
18690     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18691             StVT.getScalarType(), NumElems*SizeRatio);
18692
18693     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18694
18695     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18696     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18697     for (unsigned i = 0; i != NumElems; ++i)
18698       ShuffleVec[i] = i * SizeRatio;
18699
18700     // Can't shuffle using an illegal type.
18701     if (!TLI.isTypeLegal(WideVecVT))
18702       return SDValue();
18703
18704     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18705                                          DAG.getUNDEF(WideVecVT),
18706                                          &ShuffleVec[0]);
18707     // At this point all of the data is stored at the bottom of the
18708     // register. We now need to save it to mem.
18709
18710     // Find the largest store unit
18711     MVT StoreType = MVT::i8;
18712     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18713          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18714       MVT Tp = (MVT::SimpleValueType)tp;
18715       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18716         StoreType = Tp;
18717     }
18718
18719     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18720     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18721         (64 <= NumElems * ToSz))
18722       StoreType = MVT::f64;
18723
18724     // Bitcast the original vector into a vector of store-size units
18725     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18726             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18727     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18728     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18729     SmallVector<SDValue, 8> Chains;
18730     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18731                                         TLI.getPointerTy());
18732     SDValue Ptr = St->getBasePtr();
18733
18734     // Perform one or more big stores into memory.
18735     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18736       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18737                                    StoreType, ShuffWide,
18738                                    DAG.getIntPtrConstant(i));
18739       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18740                                 St->getPointerInfo(), St->isVolatile(),
18741                                 St->isNonTemporal(), St->getAlignment());
18742       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18743       Chains.push_back(Ch);
18744     }
18745
18746     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18747                                Chains.size());
18748   }
18749
18750   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18751   // the FP state in cases where an emms may be missing.
18752   // A preferable solution to the general problem is to figure out the right
18753   // places to insert EMMS.  This qualifies as a quick hack.
18754
18755   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18756   if (VT.getSizeInBits() != 64)
18757     return SDValue();
18758
18759   const Function *F = DAG.getMachineFunction().getFunction();
18760   bool NoImplicitFloatOps = F->getAttributes().
18761     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18762   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18763                      && Subtarget->hasSSE2();
18764   if ((VT.isVector() ||
18765        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18766       isa<LoadSDNode>(St->getValue()) &&
18767       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18768       St->getChain().hasOneUse() && !St->isVolatile()) {
18769     SDNode* LdVal = St->getValue().getNode();
18770     LoadSDNode *Ld = 0;
18771     int TokenFactorIndex = -1;
18772     SmallVector<SDValue, 8> Ops;
18773     SDNode* ChainVal = St->getChain().getNode();
18774     // Must be a store of a load.  We currently handle two cases:  the load
18775     // is a direct child, and it's under an intervening TokenFactor.  It is
18776     // possible to dig deeper under nested TokenFactors.
18777     if (ChainVal == LdVal)
18778       Ld = cast<LoadSDNode>(St->getChain());
18779     else if (St->getValue().hasOneUse() &&
18780              ChainVal->getOpcode() == ISD::TokenFactor) {
18781       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18782         if (ChainVal->getOperand(i).getNode() == LdVal) {
18783           TokenFactorIndex = i;
18784           Ld = cast<LoadSDNode>(St->getValue());
18785         } else
18786           Ops.push_back(ChainVal->getOperand(i));
18787       }
18788     }
18789
18790     if (!Ld || !ISD::isNormalLoad(Ld))
18791       return SDValue();
18792
18793     // If this is not the MMX case, i.e. we are just turning i64 load/store
18794     // into f64 load/store, avoid the transformation if there are multiple
18795     // uses of the loaded value.
18796     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18797       return SDValue();
18798
18799     SDLoc LdDL(Ld);
18800     SDLoc StDL(N);
18801     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18802     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18803     // pair instead.
18804     if (Subtarget->is64Bit() || F64IsLegal) {
18805       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18806       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18807                                   Ld->getPointerInfo(), Ld->isVolatile(),
18808                                   Ld->isNonTemporal(), Ld->isInvariant(),
18809                                   Ld->getAlignment());
18810       SDValue NewChain = NewLd.getValue(1);
18811       if (TokenFactorIndex != -1) {
18812         Ops.push_back(NewChain);
18813         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18814                                Ops.size());
18815       }
18816       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18817                           St->getPointerInfo(),
18818                           St->isVolatile(), St->isNonTemporal(),
18819                           St->getAlignment());
18820     }
18821
18822     // Otherwise, lower to two pairs of 32-bit loads / stores.
18823     SDValue LoAddr = Ld->getBasePtr();
18824     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18825                                  DAG.getConstant(4, MVT::i32));
18826
18827     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18828                                Ld->getPointerInfo(),
18829                                Ld->isVolatile(), Ld->isNonTemporal(),
18830                                Ld->isInvariant(), Ld->getAlignment());
18831     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18832                                Ld->getPointerInfo().getWithOffset(4),
18833                                Ld->isVolatile(), Ld->isNonTemporal(),
18834                                Ld->isInvariant(),
18835                                MinAlign(Ld->getAlignment(), 4));
18836
18837     SDValue NewChain = LoLd.getValue(1);
18838     if (TokenFactorIndex != -1) {
18839       Ops.push_back(LoLd);
18840       Ops.push_back(HiLd);
18841       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18842                              Ops.size());
18843     }
18844
18845     LoAddr = St->getBasePtr();
18846     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18847                          DAG.getConstant(4, MVT::i32));
18848
18849     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18850                                 St->getPointerInfo(),
18851                                 St->isVolatile(), St->isNonTemporal(),
18852                                 St->getAlignment());
18853     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18854                                 St->getPointerInfo().getWithOffset(4),
18855                                 St->isVolatile(),
18856                                 St->isNonTemporal(),
18857                                 MinAlign(St->getAlignment(), 4));
18858     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18859   }
18860   return SDValue();
18861 }
18862
18863 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18864 /// and return the operands for the horizontal operation in LHS and RHS.  A
18865 /// horizontal operation performs the binary operation on successive elements
18866 /// of its first operand, then on successive elements of its second operand,
18867 /// returning the resulting values in a vector.  For example, if
18868 ///   A = < float a0, float a1, float a2, float a3 >
18869 /// and
18870 ///   B = < float b0, float b1, float b2, float b3 >
18871 /// then the result of doing a horizontal operation on A and B is
18872 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18873 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18874 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18875 /// set to A, RHS to B, and the routine returns 'true'.
18876 /// Note that the binary operation should have the property that if one of the
18877 /// operands is UNDEF then the result is UNDEF.
18878 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18879   // Look for the following pattern: if
18880   //   A = < float a0, float a1, float a2, float a3 >
18881   //   B = < float b0, float b1, float b2, float b3 >
18882   // and
18883   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18884   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18885   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18886   // which is A horizontal-op B.
18887
18888   // At least one of the operands should be a vector shuffle.
18889   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18890       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18891     return false;
18892
18893   MVT VT = LHS.getSimpleValueType();
18894
18895   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18896          "Unsupported vector type for horizontal add/sub");
18897
18898   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18899   // operate independently on 128-bit lanes.
18900   unsigned NumElts = VT.getVectorNumElements();
18901   unsigned NumLanes = VT.getSizeInBits()/128;
18902   unsigned NumLaneElts = NumElts / NumLanes;
18903   assert((NumLaneElts % 2 == 0) &&
18904          "Vector type should have an even number of elements in each lane");
18905   unsigned HalfLaneElts = NumLaneElts/2;
18906
18907   // View LHS in the form
18908   //   LHS = VECTOR_SHUFFLE A, B, LMask
18909   // If LHS is not a shuffle then pretend it is the shuffle
18910   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18911   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18912   // type VT.
18913   SDValue A, B;
18914   SmallVector<int, 16> LMask(NumElts);
18915   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18916     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18917       A = LHS.getOperand(0);
18918     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18919       B = LHS.getOperand(1);
18920     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18921     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18922   } else {
18923     if (LHS.getOpcode() != ISD::UNDEF)
18924       A = LHS;
18925     for (unsigned i = 0; i != NumElts; ++i)
18926       LMask[i] = i;
18927   }
18928
18929   // Likewise, view RHS in the form
18930   //   RHS = VECTOR_SHUFFLE C, D, RMask
18931   SDValue C, D;
18932   SmallVector<int, 16> RMask(NumElts);
18933   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18934     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18935       C = RHS.getOperand(0);
18936     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18937       D = RHS.getOperand(1);
18938     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18939     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18940   } else {
18941     if (RHS.getOpcode() != ISD::UNDEF)
18942       C = RHS;
18943     for (unsigned i = 0; i != NumElts; ++i)
18944       RMask[i] = i;
18945   }
18946
18947   // Check that the shuffles are both shuffling the same vectors.
18948   if (!(A == C && B == D) && !(A == D && B == C))
18949     return false;
18950
18951   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18952   if (!A.getNode() && !B.getNode())
18953     return false;
18954
18955   // If A and B occur in reverse order in RHS, then "swap" them (which means
18956   // rewriting the mask).
18957   if (A != C)
18958     CommuteVectorShuffleMask(RMask, NumElts);
18959
18960   // At this point LHS and RHS are equivalent to
18961   //   LHS = VECTOR_SHUFFLE A, B, LMask
18962   //   RHS = VECTOR_SHUFFLE A, B, RMask
18963   // Check that the masks correspond to performing a horizontal operation.
18964   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18965     for (unsigned i = 0; i != NumLaneElts; ++i) {
18966       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18967
18968       // Ignore any UNDEF components.
18969       if (LIdx < 0 || RIdx < 0 ||
18970           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18971           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18972         continue;
18973
18974       // Check that successive elements are being operated on.  If not, this is
18975       // not a horizontal operation.
18976       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18977       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18978       if (!(LIdx == Index && RIdx == Index + 1) &&
18979           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18980         return false;
18981     }
18982   }
18983
18984   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18985   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18986   return true;
18987 }
18988
18989 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18990 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18991                                   const X86Subtarget *Subtarget) {
18992   EVT VT = N->getValueType(0);
18993   SDValue LHS = N->getOperand(0);
18994   SDValue RHS = N->getOperand(1);
18995
18996   // Try to synthesize horizontal adds from adds of shuffles.
18997   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18998        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18999       isHorizontalBinOp(LHS, RHS, true))
19000     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19001   return SDValue();
19002 }
19003
19004 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19005 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19006                                   const X86Subtarget *Subtarget) {
19007   EVT VT = N->getValueType(0);
19008   SDValue LHS = N->getOperand(0);
19009   SDValue RHS = N->getOperand(1);
19010
19011   // Try to synthesize horizontal subs from subs of shuffles.
19012   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19013        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19014       isHorizontalBinOp(LHS, RHS, false))
19015     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19016   return SDValue();
19017 }
19018
19019 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19020 /// X86ISD::FXOR nodes.
19021 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19022   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19023   // F[X]OR(0.0, x) -> x
19024   // F[X]OR(x, 0.0) -> x
19025   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19026     if (C->getValueAPF().isPosZero())
19027       return N->getOperand(1);
19028   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19029     if (C->getValueAPF().isPosZero())
19030       return N->getOperand(0);
19031   return SDValue();
19032 }
19033
19034 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19035 /// X86ISD::FMAX nodes.
19036 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19037   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19038
19039   // Only perform optimizations if UnsafeMath is used.
19040   if (!DAG.getTarget().Options.UnsafeFPMath)
19041     return SDValue();
19042
19043   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19044   // into FMINC and FMAXC, which are Commutative operations.
19045   unsigned NewOp = 0;
19046   switch (N->getOpcode()) {
19047     default: llvm_unreachable("unknown opcode");
19048     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19049     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19050   }
19051
19052   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19053                      N->getOperand(0), N->getOperand(1));
19054 }
19055
19056 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19057 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19058   // FAND(0.0, x) -> 0.0
19059   // FAND(x, 0.0) -> 0.0
19060   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19061     if (C->getValueAPF().isPosZero())
19062       return N->getOperand(0);
19063   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19064     if (C->getValueAPF().isPosZero())
19065       return N->getOperand(1);
19066   return SDValue();
19067 }
19068
19069 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19070 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19071   // FANDN(x, 0.0) -> 0.0
19072   // FANDN(0.0, x) -> x
19073   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19074     if (C->getValueAPF().isPosZero())
19075       return N->getOperand(1);
19076   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19077     if (C->getValueAPF().isPosZero())
19078       return N->getOperand(1);
19079   return SDValue();
19080 }
19081
19082 static SDValue PerformBTCombine(SDNode *N,
19083                                 SelectionDAG &DAG,
19084                                 TargetLowering::DAGCombinerInfo &DCI) {
19085   // BT ignores high bits in the bit index operand.
19086   SDValue Op1 = N->getOperand(1);
19087   if (Op1.hasOneUse()) {
19088     unsigned BitWidth = Op1.getValueSizeInBits();
19089     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19090     APInt KnownZero, KnownOne;
19091     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19092                                           !DCI.isBeforeLegalizeOps());
19093     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19094     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19095         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19096       DCI.CommitTargetLoweringOpt(TLO);
19097   }
19098   return SDValue();
19099 }
19100
19101 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19102   SDValue Op = N->getOperand(0);
19103   if (Op.getOpcode() == ISD::BITCAST)
19104     Op = Op.getOperand(0);
19105   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19106   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19107       VT.getVectorElementType().getSizeInBits() ==
19108       OpVT.getVectorElementType().getSizeInBits()) {
19109     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19110   }
19111   return SDValue();
19112 }
19113
19114 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19115                                                const X86Subtarget *Subtarget) {
19116   EVT VT = N->getValueType(0);
19117   if (!VT.isVector())
19118     return SDValue();
19119
19120   SDValue N0 = N->getOperand(0);
19121   SDValue N1 = N->getOperand(1);
19122   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19123   SDLoc dl(N);
19124
19125   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19126   // both SSE and AVX2 since there is no sign-extended shift right
19127   // operation on a vector with 64-bit elements.
19128   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19129   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19130   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19131       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19132     SDValue N00 = N0.getOperand(0);
19133
19134     // EXTLOAD has a better solution on AVX2,
19135     // it may be replaced with X86ISD::VSEXT node.
19136     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19137       if (!ISD::isNormalLoad(N00.getNode()))
19138         return SDValue();
19139
19140     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19141         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19142                                   N00, N1);
19143       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19144     }
19145   }
19146   return SDValue();
19147 }
19148
19149 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19150                                   TargetLowering::DAGCombinerInfo &DCI,
19151                                   const X86Subtarget *Subtarget) {
19152   if (!DCI.isBeforeLegalizeOps())
19153     return SDValue();
19154
19155   if (!Subtarget->hasFp256())
19156     return SDValue();
19157
19158   EVT VT = N->getValueType(0);
19159   if (VT.isVector() && VT.getSizeInBits() == 256) {
19160     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19161     if (R.getNode())
19162       return R;
19163   }
19164
19165   return SDValue();
19166 }
19167
19168 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19169                                  const X86Subtarget* Subtarget) {
19170   SDLoc dl(N);
19171   EVT VT = N->getValueType(0);
19172
19173   // Let legalize expand this if it isn't a legal type yet.
19174   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19175     return SDValue();
19176
19177   EVT ScalarVT = VT.getScalarType();
19178   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19179       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19180     return SDValue();
19181
19182   SDValue A = N->getOperand(0);
19183   SDValue B = N->getOperand(1);
19184   SDValue C = N->getOperand(2);
19185
19186   bool NegA = (A.getOpcode() == ISD::FNEG);
19187   bool NegB = (B.getOpcode() == ISD::FNEG);
19188   bool NegC = (C.getOpcode() == ISD::FNEG);
19189
19190   // Negative multiplication when NegA xor NegB
19191   bool NegMul = (NegA != NegB);
19192   if (NegA)
19193     A = A.getOperand(0);
19194   if (NegB)
19195     B = B.getOperand(0);
19196   if (NegC)
19197     C = C.getOperand(0);
19198
19199   unsigned Opcode;
19200   if (!NegMul)
19201     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19202   else
19203     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19204
19205   return DAG.getNode(Opcode, dl, VT, A, B, C);
19206 }
19207
19208 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19209                                   TargetLowering::DAGCombinerInfo &DCI,
19210                                   const X86Subtarget *Subtarget) {
19211   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19212   //           (and (i32 x86isd::setcc_carry), 1)
19213   // This eliminates the zext. This transformation is necessary because
19214   // ISD::SETCC is always legalized to i8.
19215   SDLoc dl(N);
19216   SDValue N0 = N->getOperand(0);
19217   EVT VT = N->getValueType(0);
19218
19219   if (N0.getOpcode() == ISD::AND &&
19220       N0.hasOneUse() &&
19221       N0.getOperand(0).hasOneUse()) {
19222     SDValue N00 = N0.getOperand(0);
19223     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19224       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19225       if (!C || C->getZExtValue() != 1)
19226         return SDValue();
19227       return DAG.getNode(ISD::AND, dl, VT,
19228                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19229                                      N00.getOperand(0), N00.getOperand(1)),
19230                          DAG.getConstant(1, VT));
19231     }
19232   }
19233
19234   if (N0.getOpcode() == ISD::TRUNCATE &&
19235       N0.hasOneUse() &&
19236       N0.getOperand(0).hasOneUse()) {
19237     SDValue N00 = N0.getOperand(0);
19238     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19239       return DAG.getNode(ISD::AND, dl, VT,
19240                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19241                                      N00.getOperand(0), N00.getOperand(1)),
19242                          DAG.getConstant(1, VT));
19243     }
19244   }
19245   if (VT.is256BitVector()) {
19246     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19247     if (R.getNode())
19248       return R;
19249   }
19250
19251   return SDValue();
19252 }
19253
19254 // Optimize x == -y --> x+y == 0
19255 //          x != -y --> x+y != 0
19256 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
19257   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19258   SDValue LHS = N->getOperand(0);
19259   SDValue RHS = N->getOperand(1);
19260
19261   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19263       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19264         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19265                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19266         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19267                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19268       }
19269   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19270     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19271       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19272         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19273                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19274         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19275                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19276       }
19277   return SDValue();
19278 }
19279
19280 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19281 // as "sbb reg,reg", since it can be extended without zext and produces
19282 // an all-ones bit which is more useful than 0/1 in some cases.
19283 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19284                                MVT VT) {
19285   if (VT == MVT::i8)
19286     return DAG.getNode(ISD::AND, DL, VT,
19287                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19288                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19289                        DAG.getConstant(1, VT));
19290   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19291   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19292                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19293                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19294 }
19295
19296 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19297 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19298                                    TargetLowering::DAGCombinerInfo &DCI,
19299                                    const X86Subtarget *Subtarget) {
19300   SDLoc DL(N);
19301   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19302   SDValue EFLAGS = N->getOperand(1);
19303
19304   if (CC == X86::COND_A) {
19305     // Try to convert COND_A into COND_B in an attempt to facilitate
19306     // materializing "setb reg".
19307     //
19308     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19309     // cannot take an immediate as its first operand.
19310     //
19311     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19312         EFLAGS.getValueType().isInteger() &&
19313         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19314       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19315                                    EFLAGS.getNode()->getVTList(),
19316                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19317       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19318       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19319     }
19320   }
19321
19322   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19323   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19324   // cases.
19325   if (CC == X86::COND_B)
19326     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19327
19328   SDValue Flags;
19329
19330   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19331   if (Flags.getNode()) {
19332     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19333     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19334   }
19335
19336   return SDValue();
19337 }
19338
19339 // Optimize branch condition evaluation.
19340 //
19341 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19342                                     TargetLowering::DAGCombinerInfo &DCI,
19343                                     const X86Subtarget *Subtarget) {
19344   SDLoc DL(N);
19345   SDValue Chain = N->getOperand(0);
19346   SDValue Dest = N->getOperand(1);
19347   SDValue EFLAGS = N->getOperand(3);
19348   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19349
19350   SDValue Flags;
19351
19352   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19353   if (Flags.getNode()) {
19354     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19355     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19356                        Flags);
19357   }
19358
19359   return SDValue();
19360 }
19361
19362 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19363                                         const X86TargetLowering *XTLI) {
19364   SDValue Op0 = N->getOperand(0);
19365   EVT InVT = Op0->getValueType(0);
19366
19367   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19368   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19369     SDLoc dl(N);
19370     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19371     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19372     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19373   }
19374
19375   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19376   // a 32-bit target where SSE doesn't support i64->FP operations.
19377   if (Op0.getOpcode() == ISD::LOAD) {
19378     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19379     EVT VT = Ld->getValueType(0);
19380     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19381         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19382         !XTLI->getSubtarget()->is64Bit() &&
19383         VT == MVT::i64) {
19384       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19385                                           Ld->getChain(), Op0, DAG);
19386       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19387       return FILDChain;
19388     }
19389   }
19390   return SDValue();
19391 }
19392
19393 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19394 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19395                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19396   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19397   // the result is either zero or one (depending on the input carry bit).
19398   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19399   if (X86::isZeroNode(N->getOperand(0)) &&
19400       X86::isZeroNode(N->getOperand(1)) &&
19401       // We don't have a good way to replace an EFLAGS use, so only do this when
19402       // dead right now.
19403       SDValue(N, 1).use_empty()) {
19404     SDLoc DL(N);
19405     EVT VT = N->getValueType(0);
19406     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19407     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19408                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19409                                            DAG.getConstant(X86::COND_B,MVT::i8),
19410                                            N->getOperand(2)),
19411                                DAG.getConstant(1, VT));
19412     return DCI.CombineTo(N, Res1, CarryOut);
19413   }
19414
19415   return SDValue();
19416 }
19417
19418 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19419 //      (add Y, (setne X, 0)) -> sbb -1, Y
19420 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19421 //      (sub (setne X, 0), Y) -> adc -1, Y
19422 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19423   SDLoc DL(N);
19424
19425   // Look through ZExts.
19426   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19427   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19428     return SDValue();
19429
19430   SDValue SetCC = Ext.getOperand(0);
19431   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19432     return SDValue();
19433
19434   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19435   if (CC != X86::COND_E && CC != X86::COND_NE)
19436     return SDValue();
19437
19438   SDValue Cmp = SetCC.getOperand(1);
19439   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19440       !X86::isZeroNode(Cmp.getOperand(1)) ||
19441       !Cmp.getOperand(0).getValueType().isInteger())
19442     return SDValue();
19443
19444   SDValue CmpOp0 = Cmp.getOperand(0);
19445   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19446                                DAG.getConstant(1, CmpOp0.getValueType()));
19447
19448   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19449   if (CC == X86::COND_NE)
19450     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19451                        DL, OtherVal.getValueType(), OtherVal,
19452                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19453   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19454                      DL, OtherVal.getValueType(), OtherVal,
19455                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19456 }
19457
19458 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19459 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19460                                  const X86Subtarget *Subtarget) {
19461   EVT VT = N->getValueType(0);
19462   SDValue Op0 = N->getOperand(0);
19463   SDValue Op1 = N->getOperand(1);
19464
19465   // Try to synthesize horizontal adds from adds of shuffles.
19466   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19467        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19468       isHorizontalBinOp(Op0, Op1, true))
19469     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19470
19471   return OptimizeConditionalInDecrement(N, DAG);
19472 }
19473
19474 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19475                                  const X86Subtarget *Subtarget) {
19476   SDValue Op0 = N->getOperand(0);
19477   SDValue Op1 = N->getOperand(1);
19478
19479   // X86 can't encode an immediate LHS of a sub. See if we can push the
19480   // negation into a preceding instruction.
19481   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19482     // If the RHS of the sub is a XOR with one use and a constant, invert the
19483     // immediate. Then add one to the LHS of the sub so we can turn
19484     // X-Y -> X+~Y+1, saving one register.
19485     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19486         isa<ConstantSDNode>(Op1.getOperand(1))) {
19487       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19488       EVT VT = Op0.getValueType();
19489       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19490                                    Op1.getOperand(0),
19491                                    DAG.getConstant(~XorC, VT));
19492       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19493                          DAG.getConstant(C->getAPIntValue()+1, VT));
19494     }
19495   }
19496
19497   // Try to synthesize horizontal adds from adds of shuffles.
19498   EVT VT = N->getValueType(0);
19499   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19500        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19501       isHorizontalBinOp(Op0, Op1, true))
19502     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19503
19504   return OptimizeConditionalInDecrement(N, DAG);
19505 }
19506
19507 /// performVZEXTCombine - Performs build vector combines
19508 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19509                                         TargetLowering::DAGCombinerInfo &DCI,
19510                                         const X86Subtarget *Subtarget) {
19511   // (vzext (bitcast (vzext (x)) -> (vzext x)
19512   SDValue In = N->getOperand(0);
19513   while (In.getOpcode() == ISD::BITCAST)
19514     In = In.getOperand(0);
19515
19516   if (In.getOpcode() != X86ISD::VZEXT)
19517     return SDValue();
19518
19519   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19520                      In.getOperand(0));
19521 }
19522
19523 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19524                                              DAGCombinerInfo &DCI) const {
19525   SelectionDAG &DAG = DCI.DAG;
19526   switch (N->getOpcode()) {
19527   default: break;
19528   case ISD::EXTRACT_VECTOR_ELT:
19529     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19530   case ISD::VSELECT:
19531   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19532   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19533   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19534   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19535   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19536   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19537   case ISD::SHL:
19538   case ISD::SRA:
19539   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19540   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19541   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19542   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19543   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19544   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19545   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19546   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19547   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19548   case X86ISD::FXOR:
19549   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19550   case X86ISD::FMIN:
19551   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19552   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19553   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19554   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19555   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19556   case ISD::ANY_EXTEND:
19557   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19558   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19559   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19560   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19561   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
19562   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19563   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19564   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19565   case X86ISD::SHUFP:       // Handle all target specific shuffles
19566   case X86ISD::PALIGNR:
19567   case X86ISD::UNPCKH:
19568   case X86ISD::UNPCKL:
19569   case X86ISD::MOVHLPS:
19570   case X86ISD::MOVLHPS:
19571   case X86ISD::PSHUFD:
19572   case X86ISD::PSHUFHW:
19573   case X86ISD::PSHUFLW:
19574   case X86ISD::MOVSS:
19575   case X86ISD::MOVSD:
19576   case X86ISD::VPERMILP:
19577   case X86ISD::VPERM2X128:
19578   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19579   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19580   }
19581
19582   return SDValue();
19583 }
19584
19585 /// isTypeDesirableForOp - Return true if the target has native support for
19586 /// the specified value type and it is 'desirable' to use the type for the
19587 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19588 /// instruction encodings are longer and some i16 instructions are slow.
19589 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19590   if (!isTypeLegal(VT))
19591     return false;
19592   if (VT != MVT::i16)
19593     return true;
19594
19595   switch (Opc) {
19596   default:
19597     return true;
19598   case ISD::LOAD:
19599   case ISD::SIGN_EXTEND:
19600   case ISD::ZERO_EXTEND:
19601   case ISD::ANY_EXTEND:
19602   case ISD::SHL:
19603   case ISD::SRL:
19604   case ISD::SUB:
19605   case ISD::ADD:
19606   case ISD::MUL:
19607   case ISD::AND:
19608   case ISD::OR:
19609   case ISD::XOR:
19610     return false;
19611   }
19612 }
19613
19614 /// IsDesirableToPromoteOp - This method query the target whether it is
19615 /// beneficial for dag combiner to promote the specified node. If true, it
19616 /// should return the desired promotion type by reference.
19617 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19618   EVT VT = Op.getValueType();
19619   if (VT != MVT::i16)
19620     return false;
19621
19622   bool Promote = false;
19623   bool Commute = false;
19624   switch (Op.getOpcode()) {
19625   default: break;
19626   case ISD::LOAD: {
19627     LoadSDNode *LD = cast<LoadSDNode>(Op);
19628     // If the non-extending load has a single use and it's not live out, then it
19629     // might be folded.
19630     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19631                                                      Op.hasOneUse()*/) {
19632       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19633              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19634         // The only case where we'd want to promote LOAD (rather then it being
19635         // promoted as an operand is when it's only use is liveout.
19636         if (UI->getOpcode() != ISD::CopyToReg)
19637           return false;
19638       }
19639     }
19640     Promote = true;
19641     break;
19642   }
19643   case ISD::SIGN_EXTEND:
19644   case ISD::ZERO_EXTEND:
19645   case ISD::ANY_EXTEND:
19646     Promote = true;
19647     break;
19648   case ISD::SHL:
19649   case ISD::SRL: {
19650     SDValue N0 = Op.getOperand(0);
19651     // Look out for (store (shl (load), x)).
19652     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19653       return false;
19654     Promote = true;
19655     break;
19656   }
19657   case ISD::ADD:
19658   case ISD::MUL:
19659   case ISD::AND:
19660   case ISD::OR:
19661   case ISD::XOR:
19662     Commute = true;
19663     // fallthrough
19664   case ISD::SUB: {
19665     SDValue N0 = Op.getOperand(0);
19666     SDValue N1 = Op.getOperand(1);
19667     if (!Commute && MayFoldLoad(N1))
19668       return false;
19669     // Avoid disabling potential load folding opportunities.
19670     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19671       return false;
19672     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19673       return false;
19674     Promote = true;
19675   }
19676   }
19677
19678   PVT = MVT::i32;
19679   return Promote;
19680 }
19681
19682 //===----------------------------------------------------------------------===//
19683 //                           X86 Inline Assembly Support
19684 //===----------------------------------------------------------------------===//
19685
19686 namespace {
19687   // Helper to match a string separated by whitespace.
19688   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19689     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19690
19691     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19692       StringRef piece(*args[i]);
19693       if (!s.startswith(piece)) // Check if the piece matches.
19694         return false;
19695
19696       s = s.substr(piece.size());
19697       StringRef::size_type pos = s.find_first_not_of(" \t");
19698       if (pos == 0) // We matched a prefix.
19699         return false;
19700
19701       s = s.substr(pos);
19702     }
19703
19704     return s.empty();
19705   }
19706   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19707 }
19708
19709 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19710
19711   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19712     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19713         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19714         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19715
19716       if (AsmPieces.size() == 3)
19717         return true;
19718       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19719         return true;
19720     }
19721   }
19722   return false;
19723 }
19724
19725 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19726   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19727
19728   std::string AsmStr = IA->getAsmString();
19729
19730   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19731   if (!Ty || Ty->getBitWidth() % 16 != 0)
19732     return false;
19733
19734   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19735   SmallVector<StringRef, 4> AsmPieces;
19736   SplitString(AsmStr, AsmPieces, ";\n");
19737
19738   switch (AsmPieces.size()) {
19739   default: return false;
19740   case 1:
19741     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19742     // we will turn this bswap into something that will be lowered to logical
19743     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19744     // lower so don't worry about this.
19745     // bswap $0
19746     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19747         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19748         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19749         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19750         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19751         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19752       // No need to check constraints, nothing other than the equivalent of
19753       // "=r,0" would be valid here.
19754       return IntrinsicLowering::LowerToByteSwap(CI);
19755     }
19756
19757     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19758     if (CI->getType()->isIntegerTy(16) &&
19759         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19760         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19761          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19762       AsmPieces.clear();
19763       const std::string &ConstraintsStr = IA->getConstraintString();
19764       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19765       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19766       if (clobbersFlagRegisters(AsmPieces))
19767         return IntrinsicLowering::LowerToByteSwap(CI);
19768     }
19769     break;
19770   case 3:
19771     if (CI->getType()->isIntegerTy(32) &&
19772         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19773         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19774         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19775         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19776       AsmPieces.clear();
19777       const std::string &ConstraintsStr = IA->getConstraintString();
19778       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19779       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19780       if (clobbersFlagRegisters(AsmPieces))
19781         return IntrinsicLowering::LowerToByteSwap(CI);
19782     }
19783
19784     if (CI->getType()->isIntegerTy(64)) {
19785       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19786       if (Constraints.size() >= 2 &&
19787           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19788           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19789         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19790         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19791             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19792             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19793           return IntrinsicLowering::LowerToByteSwap(CI);
19794       }
19795     }
19796     break;
19797   }
19798   return false;
19799 }
19800
19801 /// getConstraintType - Given a constraint letter, return the type of
19802 /// constraint it is for this target.
19803 X86TargetLowering::ConstraintType
19804 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19805   if (Constraint.size() == 1) {
19806     switch (Constraint[0]) {
19807     case 'R':
19808     case 'q':
19809     case 'Q':
19810     case 'f':
19811     case 't':
19812     case 'u':
19813     case 'y':
19814     case 'x':
19815     case 'Y':
19816     case 'l':
19817       return C_RegisterClass;
19818     case 'a':
19819     case 'b':
19820     case 'c':
19821     case 'd':
19822     case 'S':
19823     case 'D':
19824     case 'A':
19825       return C_Register;
19826     case 'I':
19827     case 'J':
19828     case 'K':
19829     case 'L':
19830     case 'M':
19831     case 'N':
19832     case 'G':
19833     case 'C':
19834     case 'e':
19835     case 'Z':
19836       return C_Other;
19837     default:
19838       break;
19839     }
19840   }
19841   return TargetLowering::getConstraintType(Constraint);
19842 }
19843
19844 /// Examine constraint type and operand type and determine a weight value.
19845 /// This object must already have been set up with the operand type
19846 /// and the current alternative constraint selected.
19847 TargetLowering::ConstraintWeight
19848   X86TargetLowering::getSingleConstraintMatchWeight(
19849     AsmOperandInfo &info, const char *constraint) const {
19850   ConstraintWeight weight = CW_Invalid;
19851   Value *CallOperandVal = info.CallOperandVal;
19852     // If we don't have a value, we can't do a match,
19853     // but allow it at the lowest weight.
19854   if (CallOperandVal == NULL)
19855     return CW_Default;
19856   Type *type = CallOperandVal->getType();
19857   // Look at the constraint type.
19858   switch (*constraint) {
19859   default:
19860     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19861   case 'R':
19862   case 'q':
19863   case 'Q':
19864   case 'a':
19865   case 'b':
19866   case 'c':
19867   case 'd':
19868   case 'S':
19869   case 'D':
19870   case 'A':
19871     if (CallOperandVal->getType()->isIntegerTy())
19872       weight = CW_SpecificReg;
19873     break;
19874   case 'f':
19875   case 't':
19876   case 'u':
19877     if (type->isFloatingPointTy())
19878       weight = CW_SpecificReg;
19879     break;
19880   case 'y':
19881     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19882       weight = CW_SpecificReg;
19883     break;
19884   case 'x':
19885   case 'Y':
19886     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19887         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19888       weight = CW_Register;
19889     break;
19890   case 'I':
19891     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19892       if (C->getZExtValue() <= 31)
19893         weight = CW_Constant;
19894     }
19895     break;
19896   case 'J':
19897     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19898       if (C->getZExtValue() <= 63)
19899         weight = CW_Constant;
19900     }
19901     break;
19902   case 'K':
19903     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19904       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19905         weight = CW_Constant;
19906     }
19907     break;
19908   case 'L':
19909     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19910       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19911         weight = CW_Constant;
19912     }
19913     break;
19914   case 'M':
19915     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19916       if (C->getZExtValue() <= 3)
19917         weight = CW_Constant;
19918     }
19919     break;
19920   case 'N':
19921     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19922       if (C->getZExtValue() <= 0xff)
19923         weight = CW_Constant;
19924     }
19925     break;
19926   case 'G':
19927   case 'C':
19928     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19929       weight = CW_Constant;
19930     }
19931     break;
19932   case 'e':
19933     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19934       if ((C->getSExtValue() >= -0x80000000LL) &&
19935           (C->getSExtValue() <= 0x7fffffffLL))
19936         weight = CW_Constant;
19937     }
19938     break;
19939   case 'Z':
19940     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19941       if (C->getZExtValue() <= 0xffffffff)
19942         weight = CW_Constant;
19943     }
19944     break;
19945   }
19946   return weight;
19947 }
19948
19949 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19950 /// with another that has more specific requirements based on the type of the
19951 /// corresponding operand.
19952 const char *X86TargetLowering::
19953 LowerXConstraint(EVT ConstraintVT) const {
19954   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19955   // 'f' like normal targets.
19956   if (ConstraintVT.isFloatingPoint()) {
19957     if (Subtarget->hasSSE2())
19958       return "Y";
19959     if (Subtarget->hasSSE1())
19960       return "x";
19961   }
19962
19963   return TargetLowering::LowerXConstraint(ConstraintVT);
19964 }
19965
19966 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19967 /// vector.  If it is invalid, don't add anything to Ops.
19968 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19969                                                      std::string &Constraint,
19970                                                      std::vector<SDValue>&Ops,
19971                                                      SelectionDAG &DAG) const {
19972   SDValue Result(0, 0);
19973
19974   // Only support length 1 constraints for now.
19975   if (Constraint.length() > 1) return;
19976
19977   char ConstraintLetter = Constraint[0];
19978   switch (ConstraintLetter) {
19979   default: break;
19980   case 'I':
19981     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19982       if (C->getZExtValue() <= 31) {
19983         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19984         break;
19985       }
19986     }
19987     return;
19988   case 'J':
19989     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19990       if (C->getZExtValue() <= 63) {
19991         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19992         break;
19993       }
19994     }
19995     return;
19996   case 'K':
19997     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19998       if (isInt<8>(C->getSExtValue())) {
19999         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20000         break;
20001       }
20002     }
20003     return;
20004   case 'N':
20005     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20006       if (C->getZExtValue() <= 255) {
20007         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20008         break;
20009       }
20010     }
20011     return;
20012   case 'e': {
20013     // 32-bit signed value
20014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20015       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20016                                            C->getSExtValue())) {
20017         // Widen to 64 bits here to get it sign extended.
20018         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20019         break;
20020       }
20021     // FIXME gcc accepts some relocatable values here too, but only in certain
20022     // memory models; it's complicated.
20023     }
20024     return;
20025   }
20026   case 'Z': {
20027     // 32-bit unsigned value
20028     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20029       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20030                                            C->getZExtValue())) {
20031         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20032         break;
20033       }
20034     }
20035     // FIXME gcc accepts some relocatable values here too, but only in certain
20036     // memory models; it's complicated.
20037     return;
20038   }
20039   case 'i': {
20040     // Literal immediates are always ok.
20041     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20042       // Widen to 64 bits here to get it sign extended.
20043       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20044       break;
20045     }
20046
20047     // In any sort of PIC mode addresses need to be computed at runtime by
20048     // adding in a register or some sort of table lookup.  These can't
20049     // be used as immediates.
20050     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20051       return;
20052
20053     // If we are in non-pic codegen mode, we allow the address of a global (with
20054     // an optional displacement) to be used with 'i'.
20055     GlobalAddressSDNode *GA = 0;
20056     int64_t Offset = 0;
20057
20058     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20059     while (1) {
20060       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20061         Offset += GA->getOffset();
20062         break;
20063       } else if (Op.getOpcode() == ISD::ADD) {
20064         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20065           Offset += C->getZExtValue();
20066           Op = Op.getOperand(0);
20067           continue;
20068         }
20069       } else if (Op.getOpcode() == ISD::SUB) {
20070         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20071           Offset += -C->getZExtValue();
20072           Op = Op.getOperand(0);
20073           continue;
20074         }
20075       }
20076
20077       // Otherwise, this isn't something we can handle, reject it.
20078       return;
20079     }
20080
20081     const GlobalValue *GV = GA->getGlobal();
20082     // If we require an extra load to get this address, as in PIC mode, we
20083     // can't accept it.
20084     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20085                                                         getTargetMachine())))
20086       return;
20087
20088     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20089                                         GA->getValueType(0), Offset);
20090     break;
20091   }
20092   }
20093
20094   if (Result.getNode()) {
20095     Ops.push_back(Result);
20096     return;
20097   }
20098   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20099 }
20100
20101 std::pair<unsigned, const TargetRegisterClass*>
20102 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20103                                                 MVT VT) const {
20104   // First, see if this is a constraint that directly corresponds to an LLVM
20105   // register class.
20106   if (Constraint.size() == 1) {
20107     // GCC Constraint Letters
20108     switch (Constraint[0]) {
20109     default: break;
20110       // TODO: Slight differences here in allocation order and leaving
20111       // RIP in the class. Do they matter any more here than they do
20112       // in the normal allocation?
20113     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20114       if (Subtarget->is64Bit()) {
20115         if (VT == MVT::i32 || VT == MVT::f32)
20116           return std::make_pair(0U, &X86::GR32RegClass);
20117         if (VT == MVT::i16)
20118           return std::make_pair(0U, &X86::GR16RegClass);
20119         if (VT == MVT::i8 || VT == MVT::i1)
20120           return std::make_pair(0U, &X86::GR8RegClass);
20121         if (VT == MVT::i64 || VT == MVT::f64)
20122           return std::make_pair(0U, &X86::GR64RegClass);
20123         break;
20124       }
20125       // 32-bit fallthrough
20126     case 'Q':   // Q_REGS
20127       if (VT == MVT::i32 || VT == MVT::f32)
20128         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20129       if (VT == MVT::i16)
20130         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20131       if (VT == MVT::i8 || VT == MVT::i1)
20132         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20133       if (VT == MVT::i64)
20134         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20135       break;
20136     case 'r':   // GENERAL_REGS
20137     case 'l':   // INDEX_REGS
20138       if (VT == MVT::i8 || VT == MVT::i1)
20139         return std::make_pair(0U, &X86::GR8RegClass);
20140       if (VT == MVT::i16)
20141         return std::make_pair(0U, &X86::GR16RegClass);
20142       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20143         return std::make_pair(0U, &X86::GR32RegClass);
20144       return std::make_pair(0U, &X86::GR64RegClass);
20145     case 'R':   // LEGACY_REGS
20146       if (VT == MVT::i8 || VT == MVT::i1)
20147         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20148       if (VT == MVT::i16)
20149         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20150       if (VT == MVT::i32 || !Subtarget->is64Bit())
20151         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20152       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20153     case 'f':  // FP Stack registers.
20154       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20155       // value to the correct fpstack register class.
20156       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20157         return std::make_pair(0U, &X86::RFP32RegClass);
20158       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20159         return std::make_pair(0U, &X86::RFP64RegClass);
20160       return std::make_pair(0U, &X86::RFP80RegClass);
20161     case 'y':   // MMX_REGS if MMX allowed.
20162       if (!Subtarget->hasMMX()) break;
20163       return std::make_pair(0U, &X86::VR64RegClass);
20164     case 'Y':   // SSE_REGS if SSE2 allowed
20165       if (!Subtarget->hasSSE2()) break;
20166       // FALL THROUGH.
20167     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20168       if (!Subtarget->hasSSE1()) break;
20169
20170       switch (VT.SimpleTy) {
20171       default: break;
20172       // Scalar SSE types.
20173       case MVT::f32:
20174       case MVT::i32:
20175         return std::make_pair(0U, &X86::FR32RegClass);
20176       case MVT::f64:
20177       case MVT::i64:
20178         return std::make_pair(0U, &X86::FR64RegClass);
20179       // Vector types.
20180       case MVT::v16i8:
20181       case MVT::v8i16:
20182       case MVT::v4i32:
20183       case MVT::v2i64:
20184       case MVT::v4f32:
20185       case MVT::v2f64:
20186         return std::make_pair(0U, &X86::VR128RegClass);
20187       // AVX types.
20188       case MVT::v32i8:
20189       case MVT::v16i16:
20190       case MVT::v8i32:
20191       case MVT::v4i64:
20192       case MVT::v8f32:
20193       case MVT::v4f64:
20194         return std::make_pair(0U, &X86::VR256RegClass);
20195       case MVT::v8f64:
20196       case MVT::v16f32:
20197       case MVT::v16i32:
20198       case MVT::v8i64:
20199         return std::make_pair(0U, &X86::VR512RegClass);
20200       }
20201       break;
20202     }
20203   }
20204
20205   // Use the default implementation in TargetLowering to convert the register
20206   // constraint into a member of a register class.
20207   std::pair<unsigned, const TargetRegisterClass*> Res;
20208   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20209
20210   // Not found as a standard register?
20211   if (Res.second == 0) {
20212     // Map st(0) -> st(7) -> ST0
20213     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20214         tolower(Constraint[1]) == 's' &&
20215         tolower(Constraint[2]) == 't' &&
20216         Constraint[3] == '(' &&
20217         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20218         Constraint[5] == ')' &&
20219         Constraint[6] == '}') {
20220
20221       Res.first = X86::ST0+Constraint[4]-'0';
20222       Res.second = &X86::RFP80RegClass;
20223       return Res;
20224     }
20225
20226     // GCC allows "st(0)" to be called just plain "st".
20227     if (StringRef("{st}").equals_lower(Constraint)) {
20228       Res.first = X86::ST0;
20229       Res.second = &X86::RFP80RegClass;
20230       return Res;
20231     }
20232
20233     // flags -> EFLAGS
20234     if (StringRef("{flags}").equals_lower(Constraint)) {
20235       Res.first = X86::EFLAGS;
20236       Res.second = &X86::CCRRegClass;
20237       return Res;
20238     }
20239
20240     // 'A' means EAX + EDX.
20241     if (Constraint == "A") {
20242       Res.first = X86::EAX;
20243       Res.second = &X86::GR32_ADRegClass;
20244       return Res;
20245     }
20246     return Res;
20247   }
20248
20249   // Otherwise, check to see if this is a register class of the wrong value
20250   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20251   // turn into {ax},{dx}.
20252   if (Res.second->hasType(VT))
20253     return Res;   // Correct type already, nothing to do.
20254
20255   // All of the single-register GCC register classes map their values onto
20256   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20257   // really want an 8-bit or 32-bit register, map to the appropriate register
20258   // class and return the appropriate register.
20259   if (Res.second == &X86::GR16RegClass) {
20260     if (VT == MVT::i8 || VT == MVT::i1) {
20261       unsigned DestReg = 0;
20262       switch (Res.first) {
20263       default: break;
20264       case X86::AX: DestReg = X86::AL; break;
20265       case X86::DX: DestReg = X86::DL; break;
20266       case X86::CX: DestReg = X86::CL; break;
20267       case X86::BX: DestReg = X86::BL; break;
20268       }
20269       if (DestReg) {
20270         Res.first = DestReg;
20271         Res.second = &X86::GR8RegClass;
20272       }
20273     } else if (VT == MVT::i32 || VT == MVT::f32) {
20274       unsigned DestReg = 0;
20275       switch (Res.first) {
20276       default: break;
20277       case X86::AX: DestReg = X86::EAX; break;
20278       case X86::DX: DestReg = X86::EDX; break;
20279       case X86::CX: DestReg = X86::ECX; break;
20280       case X86::BX: DestReg = X86::EBX; break;
20281       case X86::SI: DestReg = X86::ESI; break;
20282       case X86::DI: DestReg = X86::EDI; break;
20283       case X86::BP: DestReg = X86::EBP; break;
20284       case X86::SP: DestReg = X86::ESP; break;
20285       }
20286       if (DestReg) {
20287         Res.first = DestReg;
20288         Res.second = &X86::GR32RegClass;
20289       }
20290     } else if (VT == MVT::i64 || VT == MVT::f64) {
20291       unsigned DestReg = 0;
20292       switch (Res.first) {
20293       default: break;
20294       case X86::AX: DestReg = X86::RAX; break;
20295       case X86::DX: DestReg = X86::RDX; break;
20296       case X86::CX: DestReg = X86::RCX; break;
20297       case X86::BX: DestReg = X86::RBX; break;
20298       case X86::SI: DestReg = X86::RSI; break;
20299       case X86::DI: DestReg = X86::RDI; break;
20300       case X86::BP: DestReg = X86::RBP; break;
20301       case X86::SP: DestReg = X86::RSP; break;
20302       }
20303       if (DestReg) {
20304         Res.first = DestReg;
20305         Res.second = &X86::GR64RegClass;
20306       }
20307     }
20308   } else if (Res.second == &X86::FR32RegClass ||
20309              Res.second == &X86::FR64RegClass ||
20310              Res.second == &X86::VR128RegClass ||
20311              Res.second == &X86::VR256RegClass ||
20312              Res.second == &X86::FR32XRegClass ||
20313              Res.second == &X86::FR64XRegClass ||
20314              Res.second == &X86::VR128XRegClass ||
20315              Res.second == &X86::VR256XRegClass ||
20316              Res.second == &X86::VR512RegClass) {
20317     // Handle references to XMM physical registers that got mapped into the
20318     // wrong class.  This can happen with constraints like {xmm0} where the
20319     // target independent register mapper will just pick the first match it can
20320     // find, ignoring the required type.
20321
20322     if (VT == MVT::f32 || VT == MVT::i32)
20323       Res.second = &X86::FR32RegClass;
20324     else if (VT == MVT::f64 || VT == MVT::i64)
20325       Res.second = &X86::FR64RegClass;
20326     else if (X86::VR128RegClass.hasType(VT))
20327       Res.second = &X86::VR128RegClass;
20328     else if (X86::VR256RegClass.hasType(VT))
20329       Res.second = &X86::VR256RegClass;
20330     else if (X86::VR512RegClass.hasType(VT))
20331       Res.second = &X86::VR512RegClass;
20332   }
20333
20334   return Res;
20335 }