Revert "SelectionDAG: Teach the legalizer to split SETCC if VSELECT needs splitting...
[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 "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.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->isTargetEnvMacho()) {
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->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193     return new TargetLoweringObjectFileCOFF();
194   llvm_unreachable("unknown subtarget type");
195 }
196
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198   : TargetLowering(TM, createTLOF(TM)) {
199   Subtarget = &TM.getSubtarget<X86Subtarget>();
200   X86ScalarSSEf64 = Subtarget->hasSSE2();
201   X86ScalarSSEf32 = Subtarget->hasSSE1();
202   TD = getDataLayout();
203
204   resetOperationActions();
205 }
206
207 void X86TargetLowering::resetOperationActions() {
208   const TargetMachine &TM = getTargetMachine();
209   static bool FirstTimeThrough = true;
210
211   // If none of the target options have changed, then we don't need to reset the
212   // operation actions.
213   if (!FirstTimeThrough && TO == TM.Options) return;
214
215   if (!FirstTimeThrough) {
216     // Reinitialize the actions.
217     initActions();
218     FirstTimeThrough = false;
219   }
220
221   TO = TM.Options;
222
223   // Set up the TargetLowering object.
224   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
225
226   // X86 is weird, it always uses i8 for shift amounts and setcc results.
227   setBooleanContents(ZeroOrOneBooleanContent);
228   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
230
231   // For 64-bit since we have so many registers use the ILP scheduler, for
232   // 32-bit code use the register pressure specific scheduling.
233   // For Atom, always use ILP scheduling.
234   if (Subtarget->isAtom())
235     setSchedulingPreference(Sched::ILP);
236   else if (Subtarget->is64Bit())
237     setSchedulingPreference(Sched::ILP);
238   else
239     setSchedulingPreference(Sched::RegPressure);
240   const X86RegisterInfo *RegInfo =
241     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
243
244   // Bypass expensive divides on Atom when compiling with O2
245   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246     addBypassSlowDiv(32, 8);
247     if (Subtarget->is64Bit())
248       addBypassSlowDiv(64, 16);
249   }
250
251   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252     // Setup Windows compiler runtime calls.
253     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255     setLibcallName(RTLIB::SREM_I64, "_allrem");
256     setLibcallName(RTLIB::UREM_I64, "_aullrem");
257     setLibcallName(RTLIB::MUL_I64, "_allmul");
258     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
263
264     // The _ftol2 runtime function has an unusual calling conv, which
265     // is modeled by a special pseudo-instruction.
266     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
270   }
271
272   if (Subtarget->isTargetDarwin()) {
273     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274     setUseUnderscoreSetJmp(false);
275     setUseUnderscoreLongJmp(false);
276   } else if (Subtarget->isTargetMingw()) {
277     // MS runtime is weird: it exports _setjmp, but longjmp!
278     setUseUnderscoreSetJmp(true);
279     setUseUnderscoreLongJmp(false);
280   } else {
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(true);
283   }
284
285   // Set up the register classes.
286   addRegisterClass(MVT::i8, &X86::GR8RegClass);
287   addRegisterClass(MVT::i16, &X86::GR16RegClass);
288   addRegisterClass(MVT::i32, &X86::GR32RegClass);
289   if (Subtarget->is64Bit())
290     addRegisterClass(MVT::i64, &X86::GR64RegClass);
291
292   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
293
294   // We don't accept any truncstore of integer registers.
295   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
301
302   // SETOEQ and SETUNE require checking two conditions.
303   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
309
310   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
311   // operation.
312   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
315
316   if (Subtarget->is64Bit()) {
317     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
318     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
319   } else if (!TM.Options.UseSoftFloat) {
320     // We have an algorithm for SSE2->double, and we turn this into a
321     // 64-bit FILD followed by conditional FADD for other targets.
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
323     // We have an algorithm for SSE2, and we turn this into a 64-bit
324     // FILD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
326   }
327
328   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
329   // this operation.
330   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
332
333   if (!TM.Options.UseSoftFloat) {
334     // SSE has no i16 to fp conversion, only i32
335     if (X86ScalarSSEf32) {
336       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
337       // f32 and f64 cases are Legal, f80 case is not
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
339     } else {
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     }
343   } else {
344     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
345     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
346   }
347
348   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
349   // are Legal, f80 is custom lowered.
350   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
351   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
352
353   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
354   // this operation.
355   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
356   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
357
358   if (X86ScalarSSEf32) {
359     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
360     // f32 and f64 cases are Legal, f80 case is not
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
362   } else {
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   }
366
367   // Handle FP_TO_UINT by promoting the destination to a larger signed
368   // conversion.
369   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
372
373   if (Subtarget->is64Bit()) {
374     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
375     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
376   } else if (!TM.Options.UseSoftFloat) {
377     // Since AVX is a superset of SSE3, only check for SSE here.
378     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379       // Expand FP_TO_UINT into a select.
380       // FIXME: We would like to use a Custom expander here eventually to do
381       // the optimal thing for SSE vs. the default expansion in the legalizer.
382       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
383     else
384       // With SSE3 we can use fisttpll to convert to a signed i64; without
385       // SSE, we're stuck with a fistpll.
386       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
387   }
388
389   if (isTargetFTOL()) {
390     // Use the _ftol2 runtime function, which has a pseudo-instruction
391     // to handle its weird calling convention.
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
393   }
394
395   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396   if (!X86ScalarSSEf64) {
397     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
398     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
399     if (Subtarget->is64Bit()) {
400       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
401       // Without SSE, i64->f64 goes through memory.
402       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
403     }
404   }
405
406   // Scalar integer divide and remainder are lowered to use operations that
407   // produce two results, to match the available instructions. This exposes
408   // the two-result form to trivial CSE, which is able to combine x/y and x%y
409   // into a single instruction.
410   //
411   // Scalar integer multiply-high is also lowered to use two-result
412   // operations, to match the available instructions. However, plain multiply
413   // (low) operations are left as Legal, as there are single-result
414   // instructions for this in x86. Using the two-result multiply instructions
415   // when both high and low results are needed must be arranged by dagcombine.
416   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
417     MVT VT = IntVTs[i];
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::SDIV, VT, Expand);
421     setOperationAction(ISD::UDIV, VT, Expand);
422     setOperationAction(ISD::SREM, VT, Expand);
423     setOperationAction(ISD::UREM, VT, Expand);
424
425     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426     setOperationAction(ISD::ADDC, VT, Custom);
427     setOperationAction(ISD::ADDE, VT, Custom);
428     setOperationAction(ISD::SUBC, VT, Custom);
429     setOperationAction(ISD::SUBE, VT, Custom);
430   }
431
432   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
433   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
434   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
435   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
441   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
442   if (Subtarget->is64Bit())
443     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
447   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
448   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
451   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
452
453   // Promote the i8 variants and force them on up to i32 which has a shorter
454   // encoding.
455   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
456   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
457   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
459   if (Subtarget->hasBMI()) {
460     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
461     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
462     if (Subtarget->is64Bit())
463       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
464   } else {
465     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
466     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
469   }
470
471   if (Subtarget->hasLZCNT()) {
472     // When promoting the i8 variants, force them to i32 for a shorter
473     // encoding.
474     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
475     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
480     if (Subtarget->is64Bit())
481       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
482   } else {
483     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
484     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
485     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
489     if (Subtarget->is64Bit()) {
490       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
491       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
492     }
493   }
494
495   if (Subtarget->hasPOPCNT()) {
496     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
497   } else {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
499     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
500     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
501     if (Subtarget->is64Bit())
502       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
503   }
504
505   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
506   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
507
508   // These should be promoted to a larger select which is supported.
509   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
510   // X86 wants to expand cmov itself.
511   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
512   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
513   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
517   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
523   if (Subtarget->is64Bit()) {
524     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
525     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
526   }
527   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
528   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530   // support continuation, user-level threading, and etc.. As a result, no
531   // other SjLj exception interfaces are implemented and please don't build
532   // your own exception handling based on them.
533   // LLVM/Clang supports zero-cost DWARF exception handling.
534   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
536
537   // Darwin ABI issue.
538   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
539   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
540   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
541   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
542   if (Subtarget->is64Bit())
543     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
545   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
546   if (Subtarget->is64Bit()) {
547     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
548     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
549     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
550     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
551     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
552   }
553   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
555   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
556   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
557   if (Subtarget->is64Bit()) {
558     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
559     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
560     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
561   }
562
563   if (Subtarget->hasSSE1())
564     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
565
566   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
567
568   // Expand certain atomics
569   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
570     MVT VT = IntVTs[i];
571     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
574   }
575
576   if (!Subtarget->is64Bit()) {
577     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
589   }
590
591   if (Subtarget->hasCmpxchg16b()) {
592     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
593   }
594
595   // FIXME - use subtarget debug flags
596   if (!Subtarget->isTargetDarwin() &&
597       !Subtarget->isTargetELF() &&
598       !Subtarget->isTargetCygMing()) {
599     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
600   }
601
602   if (Subtarget->is64Bit()) {
603     setExceptionPointerRegister(X86::RAX);
604     setExceptionSelectorRegister(X86::RDX);
605   } else {
606     setExceptionPointerRegister(X86::EAX);
607     setExceptionSelectorRegister(X86::EDX);
608   }
609   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
611
612   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
614
615   setOperationAction(ISD::TRAP, MVT::Other, Legal);
616   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
617
618   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
620   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
621   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622     // TargetInfo::X86_64ABIBuiltinVaList
623     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
624     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
625   } else {
626     // TargetInfo::CharPtrBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
629   }
630
631   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
632   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
633
634   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636                        MVT::i64 : MVT::i32, Custom);
637   else if (TM.Options.EnableSegmentedStacks)
638     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                        MVT::i64 : MVT::i32, Custom);
640   else
641     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                        MVT::i64 : MVT::i32, Expand);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::SDIVREM, VT, Expand);
833     setOperationAction(ISD::UDIVREM, VT, Expand);
834     setOperationAction(ISD::FPOW, VT, Expand);
835     setOperationAction(ISD::CTPOP, VT, Expand);
836     setOperationAction(ISD::CTTZ, VT, Expand);
837     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::CTLZ, VT, Expand);
839     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::SHL, VT, Expand);
841     setOperationAction(ISD::SRA, VT, Expand);
842     setOperationAction(ISD::SRL, VT, Expand);
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845     setOperationAction(ISD::BSWAP, VT, Expand);
846     setOperationAction(ISD::SETCC, VT, Expand);
847     setOperationAction(ISD::FLOG, VT, Expand);
848     setOperationAction(ISD::FLOG2, VT, Expand);
849     setOperationAction(ISD::FLOG10, VT, Expand);
850     setOperationAction(ISD::FEXP, VT, Expand);
851     setOperationAction(ISD::FEXP2, VT, Expand);
852     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857     setOperationAction(ISD::TRUNCATE, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861     setOperationAction(ISD::VSELECT, VT, Expand);
862     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864       setTruncStoreAction(VT,
865                           (MVT::SimpleValueType)InnerVT, Expand);
866     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869   }
870
871   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872   // with -msoft-float, disable use of MMX as well.
873   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875     // No operations on x86mmx supported, everything uses intrinsics.
876   }
877
878   // MMX-sized vectors (other than x86mmx) are expected to be expanded
879   // into smaller operations.
880   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
881   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
884   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
885   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
886   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
887   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
888   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
889   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
890   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
891   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
892   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
894   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
895   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
900   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
902   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
909
910   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912
913     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
919     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
920     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
922     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
925   }
926
927   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929
930     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931     // registers cannot be used even for integer operations.
932     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936
937     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
938     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
939     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
940     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
941     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
942     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
943     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
944     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
945     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
946     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
947     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
948     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
953     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
954     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
955
956     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
960
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969       MVT VT = (MVT::SimpleValueType)i;
970       // Do not attempt to custom lower non-power-of-2 vectors
971       if (!isPowerOf2_32(VT.getVectorNumElements()))
972         continue;
973       // Do not attempt to custom lower non-128-bit vectors
974       if (!VT.is128BitVector())
975         continue;
976       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
977       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979     }
980
981     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
983     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
987
988     if (Subtarget->is64Bit()) {
989       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991     }
992
993     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995       MVT VT = (MVT::SimpleValueType)i;
996
997       // Do not attempt to promote non-128-bit vectors
998       if (!VT.is128BitVector())
999         continue;
1000
1001       setOperationAction(ISD::AND,    VT, Promote);
1002       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1003       setOperationAction(ISD::OR,     VT, Promote);
1004       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1005       setOperationAction(ISD::XOR,    VT, Promote);
1006       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1007       setOperationAction(ISD::LOAD,   VT, Promote);
1008       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1009       setOperationAction(ISD::SELECT, VT, Promote);
1010       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011     }
1012
1013     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014
1015     // Custom lower v2i64 and v2f64 selects.
1016     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1017     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1018     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1019     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1020
1021     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1022     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1023
1024     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1026     // As there is no 64-bit GPR available, we need build a special custom
1027     // sequence to convert from v2i32 to v2f32.
1028     if (!Subtarget->is64Bit())
1029       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1030
1031     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1032     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1033
1034     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1035   }
1036
1037   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1041     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1042     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1043     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1046     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1047     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1048
1049     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1052     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1053     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1054     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1057     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1059
1060     // FIXME: Do we need to handle scalar-to-vector here?
1061     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1062
1063     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1068
1069     // i8 and i16 vectors are custom , because the source register and source
1070     // source memory operand types are not the same width.  f32 vectors are
1071     // custom since the immediate controlling the insert encodes additional
1072     // information.
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1077
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1082
1083     // FIXME: these should be Legal but thats only for the case where
1084     // the index is constant.  For now custom expand to deal with that.
1085     if (Subtarget->is64Bit()) {
1086       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1087       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1088     }
1089   }
1090
1091   if (Subtarget->hasSSE2()) {
1092     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1093     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1094
1095     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1096     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1097
1098     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1099     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1100
1101     // In the customized shift lowering, the legal cases in AVX2 will be
1102     // recognized.
1103     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1104     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1105
1106     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1107     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1112     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1113   }
1114
1115   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1122
1123     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1124     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1126
1127     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1138     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1139
1140     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1151     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1152
1153     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1154     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1155
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1157
1158     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1161     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1162
1163     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1166
1167     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1168
1169     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1179
1180     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1184
1185     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1187     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1193
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200
1201     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1203       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1204       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1206       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1208     }
1209
1210     if (Subtarget->hasInt256()) {
1211       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1212       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1213       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1215
1216       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1217       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1218       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1220
1221       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1224       // Don't lower v32i8 because there is no 128-bit byte mul
1225
1226       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1227
1228       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1229     } else {
1230       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1232       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1234
1235       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1236       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1237       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1239
1240       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1242       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1243       // Don't lower v32i8 because there is no 128-bit byte mul
1244     }
1245
1246     // In the customized shift lowering, the legal cases in AVX2 will be
1247     // recognized.
1248     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1255
1256     // Custom lower several nodes for 256-bit types.
1257     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259       MVT VT = (MVT::SimpleValueType)i;
1260
1261       // Extract subvector is special because the value type
1262       // (result) is 128-bit but the source is 256-bit wide.
1263       if (VT.is128BitVector())
1264         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1265
1266       // Do not attempt to custom lower other non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1271       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281       MVT VT = (MVT::SimpleValueType)i;
1282
1283       // Do not attempt to promote non-256-bit vectors
1284       if (!VT.is256BitVector())
1285         continue;
1286
1287       setOperationAction(ISD::AND,    VT, Promote);
1288       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1289       setOperationAction(ISD::OR,     VT, Promote);
1290       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1291       setOperationAction(ISD::XOR,    VT, Promote);
1292       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1293       setOperationAction(ISD::LOAD,   VT, Promote);
1294       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1295       setOperationAction(ISD::SELECT, VT, Promote);
1296       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1297     }
1298   }
1299
1300   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1304     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1305
1306     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1307     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1308
1309     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1315
1316     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1321     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1322
1323     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1329     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1330     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1331     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1332
1333
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1340     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1341     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1342
1343     setOperationAction(ISD::TRUNCATE,           MVT::i1, Legal);
1344     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1345     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1346     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1347     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1348     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1349     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1353     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1354     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1355
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1357     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1358     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1359     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1360     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1361
1362     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1363     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1364
1365     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1366
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1368     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1371     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1372
1373     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1374     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1375
1376     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1377     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1380
1381     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1382     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1383
1384     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1385     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1386
1387     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1388     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1389
1390     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1392     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1393     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1394     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1395     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1396
1397     // Custom lower several nodes.
1398     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1399              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1400       MVT VT = (MVT::SimpleValueType)i;
1401
1402       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1403       // Extract subvector is special because the value type
1404       // (result) is 256/128-bit but the source is 512-bit wide.
1405       if (VT.is128BitVector() || VT.is256BitVector())
1406         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1407
1408       if (VT.getVectorElementType() == MVT::i1)
1409         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1410
1411       // Do not attempt to custom lower other non-512-bit vectors
1412       if (!VT.is512BitVector())
1413         continue;
1414
1415       if ( EltSize >= 32) {
1416         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1417         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1418         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1419         setOperationAction(ISD::VSELECT,             VT, Legal);
1420         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1421         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1422         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1423       }
1424     }
1425     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1426       MVT VT = (MVT::SimpleValueType)i;
1427
1428       // Do not attempt to promote non-256-bit vectors
1429       if (!VT.is512BitVector())
1430         continue;
1431
1432       setOperationAction(ISD::SELECT, VT, Promote);
1433       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1434     }
1435   }// has  AVX-512
1436
1437   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1438   // of this type with custom code.
1439   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1440            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1441     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1442                        Custom);
1443   }
1444
1445   // We want to custom lower some of our intrinsics.
1446   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1447   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1448   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1449
1450   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1451   // handle type legalization for these operations here.
1452   //
1453   // FIXME: We really should do custom legalization for addition and
1454   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1455   // than generic legalization for 64-bit multiplication-with-overflow, though.
1456   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1457     // Add/Sub/Mul with overflow operations are custom lowered.
1458     MVT VT = IntVTs[i];
1459     setOperationAction(ISD::SADDO, VT, Custom);
1460     setOperationAction(ISD::UADDO, VT, Custom);
1461     setOperationAction(ISD::SSUBO, VT, Custom);
1462     setOperationAction(ISD::USUBO, VT, Custom);
1463     setOperationAction(ISD::SMULO, VT, Custom);
1464     setOperationAction(ISD::UMULO, VT, Custom);
1465   }
1466
1467   // There are no 8-bit 3-address imul/mul instructions
1468   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1469   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1470
1471   if (!Subtarget->is64Bit()) {
1472     // These libcalls are not available in 32-bit.
1473     setLibcallName(RTLIB::SHL_I128, 0);
1474     setLibcallName(RTLIB::SRL_I128, 0);
1475     setLibcallName(RTLIB::SRA_I128, 0);
1476   }
1477
1478   // Combine sin / cos into one node or libcall if possible.
1479   if (Subtarget->hasSinCos()) {
1480     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1481     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1482     if (Subtarget->isTargetDarwin()) {
1483       // For MacOSX, we don't want to the normal expansion of a libcall to
1484       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1485       // traffic.
1486       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1487       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1488     }
1489   }
1490
1491   // We have target-specific dag combine patterns for the following nodes:
1492   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1493   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1494   setTargetDAGCombine(ISD::VSELECT);
1495   setTargetDAGCombine(ISD::SELECT);
1496   setTargetDAGCombine(ISD::SHL);
1497   setTargetDAGCombine(ISD::SRA);
1498   setTargetDAGCombine(ISD::SRL);
1499   setTargetDAGCombine(ISD::OR);
1500   setTargetDAGCombine(ISD::AND);
1501   setTargetDAGCombine(ISD::ADD);
1502   setTargetDAGCombine(ISD::FADD);
1503   setTargetDAGCombine(ISD::FSUB);
1504   setTargetDAGCombine(ISD::FMA);
1505   setTargetDAGCombine(ISD::SUB);
1506   setTargetDAGCombine(ISD::LOAD);
1507   setTargetDAGCombine(ISD::STORE);
1508   setTargetDAGCombine(ISD::ZERO_EXTEND);
1509   setTargetDAGCombine(ISD::ANY_EXTEND);
1510   setTargetDAGCombine(ISD::SIGN_EXTEND);
1511   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1512   setTargetDAGCombine(ISD::TRUNCATE);
1513   setTargetDAGCombine(ISD::SINT_TO_FP);
1514   setTargetDAGCombine(ISD::SETCC);
1515   if (Subtarget->is64Bit())
1516     setTargetDAGCombine(ISD::MUL);
1517   setTargetDAGCombine(ISD::XOR);
1518
1519   computeRegisterProperties();
1520
1521   // On Darwin, -Os means optimize for size without hurting performance,
1522   // do not reduce the limit.
1523   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1524   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1525   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1526   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1527   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1528   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1529   setPrefLoopAlignment(4); // 2^4 bytes.
1530
1531   // Predictable cmov don't hurt on atom because it's in-order.
1532   PredictableSelectIsExpensive = !Subtarget->isAtom();
1533
1534   setPrefFunctionAlignment(4); // 2^4 bytes.
1535 }
1536
1537 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1538   if (!VT.isVector()) return MVT::i8;
1539   return VT.changeVectorElementTypeToInteger();
1540 }
1541
1542 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1543 /// the desired ByVal argument alignment.
1544 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1545   if (MaxAlign == 16)
1546     return;
1547   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1548     if (VTy->getBitWidth() == 128)
1549       MaxAlign = 16;
1550   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1551     unsigned EltAlign = 0;
1552     getMaxByValAlign(ATy->getElementType(), EltAlign);
1553     if (EltAlign > MaxAlign)
1554       MaxAlign = EltAlign;
1555   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1556     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1557       unsigned EltAlign = 0;
1558       getMaxByValAlign(STy->getElementType(i), EltAlign);
1559       if (EltAlign > MaxAlign)
1560         MaxAlign = EltAlign;
1561       if (MaxAlign == 16)
1562         break;
1563     }
1564   }
1565 }
1566
1567 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1568 /// function arguments in the caller parameter area. For X86, aggregates
1569 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1570 /// are at 4-byte boundaries.
1571 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1572   if (Subtarget->is64Bit()) {
1573     // Max of 8 and alignment of type.
1574     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1575     if (TyAlign > 8)
1576       return TyAlign;
1577     return 8;
1578   }
1579
1580   unsigned Align = 4;
1581   if (Subtarget->hasSSE1())
1582     getMaxByValAlign(Ty, Align);
1583   return Align;
1584 }
1585
1586 /// getOptimalMemOpType - Returns the target specific optimal type for load
1587 /// and store operations as a result of memset, memcpy, and memmove
1588 /// lowering. If DstAlign is zero that means it's safe to destination
1589 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1590 /// means there isn't a need to check it against alignment requirement,
1591 /// probably because the source does not need to be loaded. If 'IsMemset' is
1592 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1593 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1594 /// source is constant so it does not need to be loaded.
1595 /// It returns EVT::Other if the type should be determined using generic
1596 /// target-independent logic.
1597 EVT
1598 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1599                                        unsigned DstAlign, unsigned SrcAlign,
1600                                        bool IsMemset, bool ZeroMemset,
1601                                        bool MemcpyStrSrc,
1602                                        MachineFunction &MF) const {
1603   const Function *F = MF.getFunction();
1604   if ((!IsMemset || ZeroMemset) &&
1605       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1606                                        Attribute::NoImplicitFloat)) {
1607     if (Size >= 16 &&
1608         (Subtarget->isUnalignedMemAccessFast() ||
1609          ((DstAlign == 0 || DstAlign >= 16) &&
1610           (SrcAlign == 0 || SrcAlign >= 16)))) {
1611       if (Size >= 32) {
1612         if (Subtarget->hasInt256())
1613           return MVT::v8i32;
1614         if (Subtarget->hasFp256())
1615           return MVT::v8f32;
1616       }
1617       if (Subtarget->hasSSE2())
1618         return MVT::v4i32;
1619       if (Subtarget->hasSSE1())
1620         return MVT::v4f32;
1621     } else if (!MemcpyStrSrc && Size >= 8 &&
1622                !Subtarget->is64Bit() &&
1623                Subtarget->hasSSE2()) {
1624       // Do not use f64 to lower memcpy if source is string constant. It's
1625       // better to use i32 to avoid the loads.
1626       return MVT::f64;
1627     }
1628   }
1629   if (Subtarget->is64Bit() && Size >= 8)
1630     return MVT::i64;
1631   return MVT::i32;
1632 }
1633
1634 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1635   if (VT == MVT::f32)
1636     return X86ScalarSSEf32;
1637   else if (VT == MVT::f64)
1638     return X86ScalarSSEf64;
1639   return true;
1640 }
1641
1642 bool
1643 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1644   if (Fast)
1645     *Fast = Subtarget->isUnalignedMemAccessFast();
1646   return true;
1647 }
1648
1649 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1650 /// current function.  The returned value is a member of the
1651 /// MachineJumpTableInfo::JTEntryKind enum.
1652 unsigned X86TargetLowering::getJumpTableEncoding() const {
1653   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1654   // symbol.
1655   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1656       Subtarget->isPICStyleGOT())
1657     return MachineJumpTableInfo::EK_Custom32;
1658
1659   // Otherwise, use the normal jump table encoding heuristics.
1660   return TargetLowering::getJumpTableEncoding();
1661 }
1662
1663 const MCExpr *
1664 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1665                                              const MachineBasicBlock *MBB,
1666                                              unsigned uid,MCContext &Ctx) const{
1667   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1668          Subtarget->isPICStyleGOT());
1669   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1670   // entries.
1671   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1672                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1673 }
1674
1675 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1676 /// jumptable.
1677 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1678                                                     SelectionDAG &DAG) const {
1679   if (!Subtarget->is64Bit())
1680     // This doesn't have SDLoc associated with it, but is not really the
1681     // same as a Register.
1682     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1683   return Table;
1684 }
1685
1686 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1687 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1688 /// MCExpr.
1689 const MCExpr *X86TargetLowering::
1690 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1691                              MCContext &Ctx) const {
1692   // X86-64 uses RIP relative addressing based on the jump table label.
1693   if (Subtarget->isPICStyleRIPRel())
1694     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1695
1696   // Otherwise, the reference is relative to the PIC base.
1697   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1698 }
1699
1700 // FIXME: Why this routine is here? Move to RegInfo!
1701 std::pair<const TargetRegisterClass*, uint8_t>
1702 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1703   const TargetRegisterClass *RRC = 0;
1704   uint8_t Cost = 1;
1705   switch (VT.SimpleTy) {
1706   default:
1707     return TargetLowering::findRepresentativeClass(VT);
1708   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1709     RRC = Subtarget->is64Bit() ?
1710       (const TargetRegisterClass*)&X86::GR64RegClass :
1711       (const TargetRegisterClass*)&X86::GR32RegClass;
1712     break;
1713   case MVT::x86mmx:
1714     RRC = &X86::VR64RegClass;
1715     break;
1716   case MVT::f32: case MVT::f64:
1717   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1718   case MVT::v4f32: case MVT::v2f64:
1719   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1720   case MVT::v4f64:
1721     RRC = &X86::VR128RegClass;
1722     break;
1723   }
1724   return std::make_pair(RRC, Cost);
1725 }
1726
1727 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1728                                                unsigned &Offset) const {
1729   if (!Subtarget->isTargetLinux())
1730     return false;
1731
1732   if (Subtarget->is64Bit()) {
1733     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1734     Offset = 0x28;
1735     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1736       AddressSpace = 256;
1737     else
1738       AddressSpace = 257;
1739   } else {
1740     // %gs:0x14 on i386
1741     Offset = 0x14;
1742     AddressSpace = 256;
1743   }
1744   return true;
1745 }
1746
1747 //===----------------------------------------------------------------------===//
1748 //               Return Value Calling Convention Implementation
1749 //===----------------------------------------------------------------------===//
1750
1751 #include "X86GenCallingConv.inc"
1752
1753 bool
1754 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1755                                   MachineFunction &MF, bool isVarArg,
1756                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1757                         LLVMContext &Context) const {
1758   SmallVector<CCValAssign, 16> RVLocs;
1759   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1760                  RVLocs, Context);
1761   return CCInfo.CheckReturn(Outs, RetCC_X86);
1762 }
1763
1764 SDValue
1765 X86TargetLowering::LowerReturn(SDValue Chain,
1766                                CallingConv::ID CallConv, bool isVarArg,
1767                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1768                                const SmallVectorImpl<SDValue> &OutVals,
1769                                SDLoc dl, SelectionDAG &DAG) const {
1770   MachineFunction &MF = DAG.getMachineFunction();
1771   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1772
1773   SmallVector<CCValAssign, 16> RVLocs;
1774   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1775                  RVLocs, *DAG.getContext());
1776   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1777
1778   SDValue Flag;
1779   SmallVector<SDValue, 6> RetOps;
1780   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1781   // Operand #1 = Bytes To Pop
1782   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1783                    MVT::i16));
1784
1785   // Copy the result values into the output registers.
1786   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1787     CCValAssign &VA = RVLocs[i];
1788     assert(VA.isRegLoc() && "Can only return in registers!");
1789     SDValue ValToCopy = OutVals[i];
1790     EVT ValVT = ValToCopy.getValueType();
1791
1792     // Promote values to the appropriate types
1793     if (VA.getLocInfo() == CCValAssign::SExt)
1794       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1795     else if (VA.getLocInfo() == CCValAssign::ZExt)
1796       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1797     else if (VA.getLocInfo() == CCValAssign::AExt)
1798       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1799     else if (VA.getLocInfo() == CCValAssign::BCvt)
1800       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1801
1802     // If this is x86-64, and we disabled SSE, we can't return FP values,
1803     // or SSE or MMX vectors.
1804     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1805          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1806           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1807       report_fatal_error("SSE register return with SSE disabled");
1808     }
1809     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1810     // llvm-gcc has never done it right and no one has noticed, so this
1811     // should be OK for now.
1812     if (ValVT == MVT::f64 &&
1813         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1814       report_fatal_error("SSE2 register return with SSE2 disabled");
1815
1816     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1817     // the RET instruction and handled by the FP Stackifier.
1818     if (VA.getLocReg() == X86::ST0 ||
1819         VA.getLocReg() == X86::ST1) {
1820       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1821       // change the value to the FP stack register class.
1822       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1823         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1824       RetOps.push_back(ValToCopy);
1825       // Don't emit a copytoreg.
1826       continue;
1827     }
1828
1829     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1830     // which is returned in RAX / RDX.
1831     if (Subtarget->is64Bit()) {
1832       if (ValVT == MVT::x86mmx) {
1833         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1834           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1835           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1836                                   ValToCopy);
1837           // If we don't have SSE2 available, convert to v4f32 so the generated
1838           // register is legal.
1839           if (!Subtarget->hasSSE2())
1840             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1841         }
1842       }
1843     }
1844
1845     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1846     Flag = Chain.getValue(1);
1847     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1848   }
1849
1850   // The x86-64 ABIs require that for returning structs by value we copy
1851   // the sret argument into %rax/%eax (depending on ABI) for the return.
1852   // Win32 requires us to put the sret argument to %eax as well.
1853   // We saved the argument into a virtual register in the entry block,
1854   // so now we copy the value out and into %rax/%eax.
1855   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1856       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1857     MachineFunction &MF = DAG.getMachineFunction();
1858     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1859     unsigned Reg = FuncInfo->getSRetReturnReg();
1860     assert(Reg &&
1861            "SRetReturnReg should have been set in LowerFormalArguments().");
1862     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1863
1864     unsigned RetValReg
1865         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1866           X86::RAX : X86::EAX;
1867     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1868     Flag = Chain.getValue(1);
1869
1870     // RAX/EAX now acts like a return value.
1871     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1872   }
1873
1874   RetOps[0] = Chain;  // Update chain.
1875
1876   // Add the flag if we have it.
1877   if (Flag.getNode())
1878     RetOps.push_back(Flag);
1879
1880   return DAG.getNode(X86ISD::RET_FLAG, dl,
1881                      MVT::Other, &RetOps[0], RetOps.size());
1882 }
1883
1884 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1885   if (N->getNumValues() != 1)
1886     return false;
1887   if (!N->hasNUsesOfValue(1, 0))
1888     return false;
1889
1890   SDValue TCChain = Chain;
1891   SDNode *Copy = *N->use_begin();
1892   if (Copy->getOpcode() == ISD::CopyToReg) {
1893     // If the copy has a glue operand, we conservatively assume it isn't safe to
1894     // perform a tail call.
1895     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1896       return false;
1897     TCChain = Copy->getOperand(0);
1898   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1899     return false;
1900
1901   bool HasRet = false;
1902   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1903        UI != UE; ++UI) {
1904     if (UI->getOpcode() != X86ISD::RET_FLAG)
1905       return false;
1906     HasRet = true;
1907   }
1908
1909   if (!HasRet)
1910     return false;
1911
1912   Chain = TCChain;
1913   return true;
1914 }
1915
1916 MVT
1917 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1918                                             ISD::NodeType ExtendKind) const {
1919   MVT ReturnMVT;
1920   // TODO: Is this also valid on 32-bit?
1921   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1922     ReturnMVT = MVT::i8;
1923   else
1924     ReturnMVT = MVT::i32;
1925
1926   MVT MinVT = getRegisterType(ReturnMVT);
1927   return VT.bitsLT(MinVT) ? MinVT : VT;
1928 }
1929
1930 /// LowerCallResult - Lower the result values of a call into the
1931 /// appropriate copies out of appropriate physical registers.
1932 ///
1933 SDValue
1934 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1935                                    CallingConv::ID CallConv, bool isVarArg,
1936                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1937                                    SDLoc dl, SelectionDAG &DAG,
1938                                    SmallVectorImpl<SDValue> &InVals) const {
1939
1940   // Assign locations to each value returned by this call.
1941   SmallVector<CCValAssign, 16> RVLocs;
1942   bool Is64Bit = Subtarget->is64Bit();
1943   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1944                  getTargetMachine(), RVLocs, *DAG.getContext());
1945   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1946
1947   // Copy all of the result registers out of their specified physreg.
1948   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1949     CCValAssign &VA = RVLocs[i];
1950     EVT CopyVT = VA.getValVT();
1951
1952     // If this is x86-64, and we disabled SSE, we can't return FP values
1953     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1954         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1955       report_fatal_error("SSE register return with SSE disabled");
1956     }
1957
1958     SDValue Val;
1959
1960     // If this is a call to a function that returns an fp value on the floating
1961     // point stack, we must guarantee the value is popped from the stack, so
1962     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1963     // if the return value is not used. We use the FpPOP_RETVAL instruction
1964     // instead.
1965     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1966       // If we prefer to use the value in xmm registers, copy it out as f80 and
1967       // use a truncate to move it from fp stack reg to xmm reg.
1968       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1969       SDValue Ops[] = { Chain, InFlag };
1970       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1971                                          MVT::Other, MVT::Glue, Ops), 1);
1972       Val = Chain.getValue(0);
1973
1974       // Round the f80 to the right size, which also moves it to the appropriate
1975       // xmm register.
1976       if (CopyVT != VA.getValVT())
1977         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1978                           // This truncation won't change the value.
1979                           DAG.getIntPtrConstant(1));
1980     } else {
1981       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1982                                  CopyVT, InFlag).getValue(1);
1983       Val = Chain.getValue(0);
1984     }
1985     InFlag = Chain.getValue(2);
1986     InVals.push_back(Val);
1987   }
1988
1989   return Chain;
1990 }
1991
1992 //===----------------------------------------------------------------------===//
1993 //                C & StdCall & Fast Calling Convention implementation
1994 //===----------------------------------------------------------------------===//
1995 //  StdCall calling convention seems to be standard for many Windows' API
1996 //  routines and around. It differs from C calling convention just a little:
1997 //  callee should clean up the stack, not caller. Symbols should be also
1998 //  decorated in some fancy way :) It doesn't support any vector arguments.
1999 //  For info on fast calling convention see Fast Calling Convention (tail call)
2000 //  implementation LowerX86_32FastCCCallTo.
2001
2002 /// CallIsStructReturn - Determines whether a call uses struct return
2003 /// semantics.
2004 enum StructReturnType {
2005   NotStructReturn,
2006   RegStructReturn,
2007   StackStructReturn
2008 };
2009 static StructReturnType
2010 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2011   if (Outs.empty())
2012     return NotStructReturn;
2013
2014   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2015   if (!Flags.isSRet())
2016     return NotStructReturn;
2017   if (Flags.isInReg())
2018     return RegStructReturn;
2019   return StackStructReturn;
2020 }
2021
2022 /// ArgsAreStructReturn - Determines whether a function uses struct
2023 /// return semantics.
2024 static StructReturnType
2025 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2026   if (Ins.empty())
2027     return NotStructReturn;
2028
2029   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2030   if (!Flags.isSRet())
2031     return NotStructReturn;
2032   if (Flags.isInReg())
2033     return RegStructReturn;
2034   return StackStructReturn;
2035 }
2036
2037 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2038 /// by "Src" to address "Dst" with size and alignment information specified by
2039 /// the specific parameter attribute. The copy will be passed as a byval
2040 /// function parameter.
2041 static SDValue
2042 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2043                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2044                           SDLoc dl) {
2045   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2046
2047   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2048                        /*isVolatile*/false, /*AlwaysInline=*/true,
2049                        MachinePointerInfo(), MachinePointerInfo());
2050 }
2051
2052 /// IsTailCallConvention - Return true if the calling convention is one that
2053 /// supports tail call optimization.
2054 static bool IsTailCallConvention(CallingConv::ID CC) {
2055   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2056           CC == CallingConv::HiPE);
2057 }
2058
2059 /// \brief Return true if the calling convention is a C calling convention.
2060 static bool IsCCallConvention(CallingConv::ID CC) {
2061   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2062           CC == CallingConv::X86_64_SysV);
2063 }
2064
2065 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2066   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2067     return false;
2068
2069   CallSite CS(CI);
2070   CallingConv::ID CalleeCC = CS.getCallingConv();
2071   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2072     return false;
2073
2074   return true;
2075 }
2076
2077 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2078 /// a tailcall target by changing its ABI.
2079 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2080                                    bool GuaranteedTailCallOpt) {
2081   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2082 }
2083
2084 SDValue
2085 X86TargetLowering::LowerMemArgument(SDValue Chain,
2086                                     CallingConv::ID CallConv,
2087                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2088                                     SDLoc dl, SelectionDAG &DAG,
2089                                     const CCValAssign &VA,
2090                                     MachineFrameInfo *MFI,
2091                                     unsigned i) const {
2092   // Create the nodes corresponding to a load from this parameter slot.
2093   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2094   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2095                               getTargetMachine().Options.GuaranteedTailCallOpt);
2096   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2097   EVT ValVT;
2098
2099   // If value is passed by pointer we have address passed instead of the value
2100   // itself.
2101   if (VA.getLocInfo() == CCValAssign::Indirect)
2102     ValVT = VA.getLocVT();
2103   else
2104     ValVT = VA.getValVT();
2105
2106   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2107   // changed with more analysis.
2108   // In case of tail call optimization mark all arguments mutable. Since they
2109   // could be overwritten by lowering of arguments in case of a tail call.
2110   if (Flags.isByVal()) {
2111     unsigned Bytes = Flags.getByValSize();
2112     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2113     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2114     return DAG.getFrameIndex(FI, getPointerTy());
2115   } else {
2116     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2117                                     VA.getLocMemOffset(), isImmutable);
2118     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2119     return DAG.getLoad(ValVT, dl, Chain, FIN,
2120                        MachinePointerInfo::getFixedStack(FI),
2121                        false, false, false, 0);
2122   }
2123 }
2124
2125 SDValue
2126 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2127                                         CallingConv::ID CallConv,
2128                                         bool isVarArg,
2129                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2130                                         SDLoc dl,
2131                                         SelectionDAG &DAG,
2132                                         SmallVectorImpl<SDValue> &InVals)
2133                                           const {
2134   MachineFunction &MF = DAG.getMachineFunction();
2135   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2136
2137   const Function* Fn = MF.getFunction();
2138   if (Fn->hasExternalLinkage() &&
2139       Subtarget->isTargetCygMing() &&
2140       Fn->getName() == "main")
2141     FuncInfo->setForceFramePointer(true);
2142
2143   MachineFrameInfo *MFI = MF.getFrameInfo();
2144   bool Is64Bit = Subtarget->is64Bit();
2145   bool IsWindows = Subtarget->isTargetWindows();
2146   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2147
2148   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2149          "Var args not supported with calling convention fastcc, ghc or hipe");
2150
2151   // Assign locations to all of the incoming arguments.
2152   SmallVector<CCValAssign, 16> ArgLocs;
2153   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2154                  ArgLocs, *DAG.getContext());
2155
2156   // Allocate shadow area for Win64
2157   if (IsWin64)
2158     CCInfo.AllocateStack(32, 8);
2159
2160   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2161
2162   unsigned LastVal = ~0U;
2163   SDValue ArgValue;
2164   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2165     CCValAssign &VA = ArgLocs[i];
2166     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2167     // places.
2168     assert(VA.getValNo() != LastVal &&
2169            "Don't support value assigned to multiple locs yet");
2170     (void)LastVal;
2171     LastVal = VA.getValNo();
2172
2173     if (VA.isRegLoc()) {
2174       EVT RegVT = VA.getLocVT();
2175       const TargetRegisterClass *RC;
2176       if (RegVT == MVT::i32)
2177         RC = &X86::GR32RegClass;
2178       else if (Is64Bit && RegVT == MVT::i64)
2179         RC = &X86::GR64RegClass;
2180       else if (RegVT == MVT::f32)
2181         RC = &X86::FR32RegClass;
2182       else if (RegVT == MVT::f64)
2183         RC = &X86::FR64RegClass;
2184       else if (RegVT.is512BitVector())
2185         RC = &X86::VR512RegClass;
2186       else if (RegVT.is256BitVector())
2187         RC = &X86::VR256RegClass;
2188       else if (RegVT.is128BitVector())
2189         RC = &X86::VR128RegClass;
2190       else if (RegVT == MVT::x86mmx)
2191         RC = &X86::VR64RegClass;
2192       else if (RegVT == MVT::v8i1)
2193         RC = &X86::VK8RegClass;
2194       else if (RegVT == MVT::v16i1)
2195         RC = &X86::VK16RegClass;
2196       else
2197         llvm_unreachable("Unknown argument type!");
2198
2199       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2200       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2201
2202       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2203       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2204       // right size.
2205       if (VA.getLocInfo() == CCValAssign::SExt)
2206         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2207                                DAG.getValueType(VA.getValVT()));
2208       else if (VA.getLocInfo() == CCValAssign::ZExt)
2209         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2210                                DAG.getValueType(VA.getValVT()));
2211       else if (VA.getLocInfo() == CCValAssign::BCvt)
2212         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2213
2214       if (VA.isExtInLoc()) {
2215         // Handle MMX values passed in XMM regs.
2216         if (RegVT.isVector())
2217           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2218         else
2219           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2220       }
2221     } else {
2222       assert(VA.isMemLoc());
2223       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2224     }
2225
2226     // If value is passed via pointer - do a load.
2227     if (VA.getLocInfo() == CCValAssign::Indirect)
2228       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2229                              MachinePointerInfo(), false, false, false, 0);
2230
2231     InVals.push_back(ArgValue);
2232   }
2233
2234   // The x86-64 ABIs require that for returning structs by value we copy
2235   // the sret argument into %rax/%eax (depending on ABI) for the return.
2236   // Win32 requires us to put the sret argument to %eax as well.
2237   // Save the argument into a virtual register so that we can access it
2238   // from the return points.
2239   if (MF.getFunction()->hasStructRetAttr() &&
2240       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2241     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2242     unsigned Reg = FuncInfo->getSRetReturnReg();
2243     if (!Reg) {
2244       MVT PtrTy = getPointerTy();
2245       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2246       FuncInfo->setSRetReturnReg(Reg);
2247     }
2248     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2249     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2250   }
2251
2252   unsigned StackSize = CCInfo.getNextStackOffset();
2253   // Align stack specially for tail calls.
2254   if (FuncIsMadeTailCallSafe(CallConv,
2255                              MF.getTarget().Options.GuaranteedTailCallOpt))
2256     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2257
2258   // If the function takes variable number of arguments, make a frame index for
2259   // the start of the first vararg value... for expansion of llvm.va_start.
2260   if (isVarArg) {
2261     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2262                     CallConv != CallingConv::X86_ThisCall)) {
2263       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2264     }
2265     if (Is64Bit) {
2266       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2267
2268       // FIXME: We should really autogenerate these arrays
2269       static const uint16_t GPR64ArgRegsWin64[] = {
2270         X86::RCX, X86::RDX, X86::R8,  X86::R9
2271       };
2272       static const uint16_t GPR64ArgRegs64Bit[] = {
2273         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2274       };
2275       static const uint16_t XMMArgRegs64Bit[] = {
2276         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2277         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2278       };
2279       const uint16_t *GPR64ArgRegs;
2280       unsigned NumXMMRegs = 0;
2281
2282       if (IsWin64) {
2283         // The XMM registers which might contain var arg parameters are shadowed
2284         // in their paired GPR.  So we only need to save the GPR to their home
2285         // slots.
2286         TotalNumIntRegs = 4;
2287         GPR64ArgRegs = GPR64ArgRegsWin64;
2288       } else {
2289         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2290         GPR64ArgRegs = GPR64ArgRegs64Bit;
2291
2292         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2293                                                 TotalNumXMMRegs);
2294       }
2295       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2296                                                        TotalNumIntRegs);
2297
2298       bool NoImplicitFloatOps = Fn->getAttributes().
2299         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2300       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2301              "SSE register cannot be used when SSE is disabled!");
2302       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2303                NoImplicitFloatOps) &&
2304              "SSE register cannot be used when SSE is disabled!");
2305       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2306           !Subtarget->hasSSE1())
2307         // Kernel mode asks for SSE to be disabled, so don't push them
2308         // on the stack.
2309         TotalNumXMMRegs = 0;
2310
2311       if (IsWin64) {
2312         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2313         // Get to the caller-allocated home save location.  Add 8 to account
2314         // for the return address.
2315         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2316         FuncInfo->setRegSaveFrameIndex(
2317           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2318         // Fixup to set vararg frame on shadow area (4 x i64).
2319         if (NumIntRegs < 4)
2320           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2321       } else {
2322         // For X86-64, if there are vararg parameters that are passed via
2323         // registers, then we must store them to their spots on the stack so
2324         // they may be loaded by deferencing the result of va_next.
2325         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2326         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2327         FuncInfo->setRegSaveFrameIndex(
2328           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2329                                false));
2330       }
2331
2332       // Store the integer parameter registers.
2333       SmallVector<SDValue, 8> MemOps;
2334       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2335                                         getPointerTy());
2336       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2337       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2338         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2339                                   DAG.getIntPtrConstant(Offset));
2340         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2341                                      &X86::GR64RegClass);
2342         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2343         SDValue Store =
2344           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2345                        MachinePointerInfo::getFixedStack(
2346                          FuncInfo->getRegSaveFrameIndex(), Offset),
2347                        false, false, 0);
2348         MemOps.push_back(Store);
2349         Offset += 8;
2350       }
2351
2352       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2353         // Now store the XMM (fp + vector) parameter registers.
2354         SmallVector<SDValue, 11> SaveXMMOps;
2355         SaveXMMOps.push_back(Chain);
2356
2357         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2358         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2359         SaveXMMOps.push_back(ALVal);
2360
2361         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2362                                FuncInfo->getRegSaveFrameIndex()));
2363         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2364                                FuncInfo->getVarArgsFPOffset()));
2365
2366         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2367           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2368                                        &X86::VR128RegClass);
2369           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2370           SaveXMMOps.push_back(Val);
2371         }
2372         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2373                                      MVT::Other,
2374                                      &SaveXMMOps[0], SaveXMMOps.size()));
2375       }
2376
2377       if (!MemOps.empty())
2378         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2379                             &MemOps[0], MemOps.size());
2380     }
2381   }
2382
2383   // Some CCs need callee pop.
2384   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2385                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2386     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2387   } else {
2388     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2389     // If this is an sret function, the return should pop the hidden pointer.
2390     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2391         argsAreStructReturn(Ins) == StackStructReturn)
2392       FuncInfo->setBytesToPopOnReturn(4);
2393   }
2394
2395   if (!Is64Bit) {
2396     // RegSaveFrameIndex is X86-64 only.
2397     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2398     if (CallConv == CallingConv::X86_FastCall ||
2399         CallConv == CallingConv::X86_ThisCall)
2400       // fastcc functions can't have varargs.
2401       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2402   }
2403
2404   FuncInfo->setArgumentStackSize(StackSize);
2405
2406   return Chain;
2407 }
2408
2409 SDValue
2410 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2411                                     SDValue StackPtr, SDValue Arg,
2412                                     SDLoc dl, SelectionDAG &DAG,
2413                                     const CCValAssign &VA,
2414                                     ISD::ArgFlagsTy Flags) const {
2415   unsigned LocMemOffset = VA.getLocMemOffset();
2416   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2417   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2418   if (Flags.isByVal())
2419     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2420
2421   return DAG.getStore(Chain, dl, Arg, PtrOff,
2422                       MachinePointerInfo::getStack(LocMemOffset),
2423                       false, false, 0);
2424 }
2425
2426 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2427 /// optimization is performed and it is required.
2428 SDValue
2429 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2430                                            SDValue &OutRetAddr, SDValue Chain,
2431                                            bool IsTailCall, bool Is64Bit,
2432                                            int FPDiff, SDLoc dl) const {
2433   // Adjust the Return address stack slot.
2434   EVT VT = getPointerTy();
2435   OutRetAddr = getReturnAddressFrameIndex(DAG);
2436
2437   // Load the "old" Return address.
2438   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2439                            false, false, false, 0);
2440   return SDValue(OutRetAddr.getNode(), 1);
2441 }
2442
2443 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2444 /// optimization is performed and it is required (FPDiff!=0).
2445 static SDValue
2446 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2447                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2448                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2449   // Store the return address to the appropriate stack slot.
2450   if (!FPDiff) return Chain;
2451   // Calculate the new stack slot for the return address.
2452   int NewReturnAddrFI =
2453     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2454                                          false);
2455   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2456   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2457                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2458                        false, false, 0);
2459   return Chain;
2460 }
2461
2462 SDValue
2463 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2464                              SmallVectorImpl<SDValue> &InVals) const {
2465   SelectionDAG &DAG                     = CLI.DAG;
2466   SDLoc &dl                             = CLI.DL;
2467   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2468   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2469   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2470   SDValue Chain                         = CLI.Chain;
2471   SDValue Callee                        = CLI.Callee;
2472   CallingConv::ID CallConv              = CLI.CallConv;
2473   bool &isTailCall                      = CLI.IsTailCall;
2474   bool isVarArg                         = CLI.IsVarArg;
2475
2476   MachineFunction &MF = DAG.getMachineFunction();
2477   bool Is64Bit        = Subtarget->is64Bit();
2478   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2479   bool IsWindows      = Subtarget->isTargetWindows();
2480   StructReturnType SR = callIsStructReturn(Outs);
2481   bool IsSibcall      = false;
2482
2483   if (MF.getTarget().Options.DisableTailCalls)
2484     isTailCall = false;
2485
2486   if (isTailCall) {
2487     // Check if it's really possible to do a tail call.
2488     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2489                     isVarArg, SR != NotStructReturn,
2490                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2491                     Outs, OutVals, Ins, DAG);
2492
2493     // Sibcalls are automatically detected tailcalls which do not require
2494     // ABI changes.
2495     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2496       IsSibcall = true;
2497
2498     if (isTailCall)
2499       ++NumTailCalls;
2500   }
2501
2502   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2503          "Var args not supported with calling convention fastcc, ghc or hipe");
2504
2505   // Analyze operands of the call, assigning locations to each operand.
2506   SmallVector<CCValAssign, 16> ArgLocs;
2507   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2508                  ArgLocs, *DAG.getContext());
2509
2510   // Allocate shadow area for Win64
2511   if (IsWin64)
2512     CCInfo.AllocateStack(32, 8);
2513
2514   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2515
2516   // Get a count of how many bytes are to be pushed on the stack.
2517   unsigned NumBytes = CCInfo.getNextStackOffset();
2518   if (IsSibcall)
2519     // This is a sibcall. The memory operands are available in caller's
2520     // own caller's stack.
2521     NumBytes = 0;
2522   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2523            IsTailCallConvention(CallConv))
2524     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2525
2526   int FPDiff = 0;
2527   if (isTailCall && !IsSibcall) {
2528     // Lower arguments at fp - stackoffset + fpdiff.
2529     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2530     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2531
2532     FPDiff = NumBytesCallerPushed - NumBytes;
2533
2534     // Set the delta of movement of the returnaddr stackslot.
2535     // But only set if delta is greater than previous delta.
2536     if (FPDiff < X86Info->getTCReturnAddrDelta())
2537       X86Info->setTCReturnAddrDelta(FPDiff);
2538   }
2539
2540   if (!IsSibcall)
2541     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2542                                  dl);
2543
2544   SDValue RetAddrFrIdx;
2545   // Load return address for tail calls.
2546   if (isTailCall && FPDiff)
2547     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2548                                     Is64Bit, FPDiff, dl);
2549
2550   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2551   SmallVector<SDValue, 8> MemOpChains;
2552   SDValue StackPtr;
2553
2554   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2555   // of tail call optimization arguments are handle later.
2556   const X86RegisterInfo *RegInfo =
2557     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2558   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2559     CCValAssign &VA = ArgLocs[i];
2560     EVT RegVT = VA.getLocVT();
2561     SDValue Arg = OutVals[i];
2562     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2563     bool isByVal = Flags.isByVal();
2564
2565     // Promote the value if needed.
2566     switch (VA.getLocInfo()) {
2567     default: llvm_unreachable("Unknown loc info!");
2568     case CCValAssign::Full: break;
2569     case CCValAssign::SExt:
2570       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2571       break;
2572     case CCValAssign::ZExt:
2573       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2574       break;
2575     case CCValAssign::AExt:
2576       if (RegVT.is128BitVector()) {
2577         // Special case: passing MMX values in XMM registers.
2578         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2579         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2580         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2581       } else
2582         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2583       break;
2584     case CCValAssign::BCvt:
2585       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2586       break;
2587     case CCValAssign::Indirect: {
2588       // Store the argument.
2589       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2590       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2591       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2592                            MachinePointerInfo::getFixedStack(FI),
2593                            false, false, 0);
2594       Arg = SpillSlot;
2595       break;
2596     }
2597     }
2598
2599     if (VA.isRegLoc()) {
2600       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2601       if (isVarArg && IsWin64) {
2602         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2603         // shadow reg if callee is a varargs function.
2604         unsigned ShadowReg = 0;
2605         switch (VA.getLocReg()) {
2606         case X86::XMM0: ShadowReg = X86::RCX; break;
2607         case X86::XMM1: ShadowReg = X86::RDX; break;
2608         case X86::XMM2: ShadowReg = X86::R8; break;
2609         case X86::XMM3: ShadowReg = X86::R9; break;
2610         }
2611         if (ShadowReg)
2612           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2613       }
2614     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2615       assert(VA.isMemLoc());
2616       if (StackPtr.getNode() == 0)
2617         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2618                                       getPointerTy());
2619       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2620                                              dl, DAG, VA, Flags));
2621     }
2622   }
2623
2624   if (!MemOpChains.empty())
2625     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2626                         &MemOpChains[0], MemOpChains.size());
2627
2628   if (Subtarget->isPICStyleGOT()) {
2629     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2630     // GOT pointer.
2631     if (!isTailCall) {
2632       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2633                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2634     } else {
2635       // If we are tail calling and generating PIC/GOT style code load the
2636       // address of the callee into ECX. The value in ecx is used as target of
2637       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2638       // for tail calls on PIC/GOT architectures. Normally we would just put the
2639       // address of GOT into ebx and then call target@PLT. But for tail calls
2640       // ebx would be restored (since ebx is callee saved) before jumping to the
2641       // target@PLT.
2642
2643       // Note: The actual moving to ECX is done further down.
2644       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2645       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2646           !G->getGlobal()->hasProtectedVisibility())
2647         Callee = LowerGlobalAddress(Callee, DAG);
2648       else if (isa<ExternalSymbolSDNode>(Callee))
2649         Callee = LowerExternalSymbol(Callee, DAG);
2650     }
2651   }
2652
2653   if (Is64Bit && isVarArg && !IsWin64) {
2654     // From AMD64 ABI document:
2655     // For calls that may call functions that use varargs or stdargs
2656     // (prototype-less calls or calls to functions containing ellipsis (...) in
2657     // the declaration) %al is used as hidden argument to specify the number
2658     // of SSE registers used. The contents of %al do not need to match exactly
2659     // the number of registers, but must be an ubound on the number of SSE
2660     // registers used and is in the range 0 - 8 inclusive.
2661
2662     // Count the number of XMM registers allocated.
2663     static const uint16_t XMMArgRegs[] = {
2664       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2665       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2666     };
2667     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2668     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2669            && "SSE registers cannot be used when SSE is disabled");
2670
2671     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2672                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2673   }
2674
2675   // For tail calls lower the arguments to the 'real' stack slot.
2676   if (isTailCall) {
2677     // Force all the incoming stack arguments to be loaded from the stack
2678     // before any new outgoing arguments are stored to the stack, because the
2679     // outgoing stack slots may alias the incoming argument stack slots, and
2680     // the alias isn't otherwise explicit. This is slightly more conservative
2681     // than necessary, because it means that each store effectively depends
2682     // on every argument instead of just those arguments it would clobber.
2683     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2684
2685     SmallVector<SDValue, 8> MemOpChains2;
2686     SDValue FIN;
2687     int FI = 0;
2688     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2689       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2690         CCValAssign &VA = ArgLocs[i];
2691         if (VA.isRegLoc())
2692           continue;
2693         assert(VA.isMemLoc());
2694         SDValue Arg = OutVals[i];
2695         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2696         // Create frame index.
2697         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2698         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2699         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2700         FIN = DAG.getFrameIndex(FI, getPointerTy());
2701
2702         if (Flags.isByVal()) {
2703           // Copy relative to framepointer.
2704           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2705           if (StackPtr.getNode() == 0)
2706             StackPtr = DAG.getCopyFromReg(Chain, dl,
2707                                           RegInfo->getStackRegister(),
2708                                           getPointerTy());
2709           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2710
2711           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2712                                                            ArgChain,
2713                                                            Flags, DAG, dl));
2714         } else {
2715           // Store relative to framepointer.
2716           MemOpChains2.push_back(
2717             DAG.getStore(ArgChain, dl, Arg, FIN,
2718                          MachinePointerInfo::getFixedStack(FI),
2719                          false, false, 0));
2720         }
2721       }
2722     }
2723
2724     if (!MemOpChains2.empty())
2725       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2726                           &MemOpChains2[0], MemOpChains2.size());
2727
2728     // Store the return address to the appropriate stack slot.
2729     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2730                                      getPointerTy(), RegInfo->getSlotSize(),
2731                                      FPDiff, dl);
2732   }
2733
2734   // Build a sequence of copy-to-reg nodes chained together with token chain
2735   // and flag operands which copy the outgoing args into registers.
2736   SDValue InFlag;
2737   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2738     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2739                              RegsToPass[i].second, InFlag);
2740     InFlag = Chain.getValue(1);
2741   }
2742
2743   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2744     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2745     // In the 64-bit large code model, we have to make all calls
2746     // through a register, since the call instruction's 32-bit
2747     // pc-relative offset may not be large enough to hold the whole
2748     // address.
2749   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2750     // If the callee is a GlobalAddress node (quite common, every direct call
2751     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2752     // it.
2753
2754     // We should use extra load for direct calls to dllimported functions in
2755     // non-JIT mode.
2756     const GlobalValue *GV = G->getGlobal();
2757     if (!GV->hasDLLImportLinkage()) {
2758       unsigned char OpFlags = 0;
2759       bool ExtraLoad = false;
2760       unsigned WrapperKind = ISD::DELETED_NODE;
2761
2762       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2763       // external symbols most go through the PLT in PIC mode.  If the symbol
2764       // has hidden or protected visibility, or if it is static or local, then
2765       // we don't need to use the PLT - we can directly call it.
2766       if (Subtarget->isTargetELF() &&
2767           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2768           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2769         OpFlags = X86II::MO_PLT;
2770       } else if (Subtarget->isPICStyleStubAny() &&
2771                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2772                  (!Subtarget->getTargetTriple().isMacOSX() ||
2773                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2774         // PC-relative references to external symbols should go through $stub,
2775         // unless we're building with the leopard linker or later, which
2776         // automatically synthesizes these stubs.
2777         OpFlags = X86II::MO_DARWIN_STUB;
2778       } else if (Subtarget->isPICStyleRIPRel() &&
2779                  isa<Function>(GV) &&
2780                  cast<Function>(GV)->getAttributes().
2781                    hasAttribute(AttributeSet::FunctionIndex,
2782                                 Attribute::NonLazyBind)) {
2783         // If the function is marked as non-lazy, generate an indirect call
2784         // which loads from the GOT directly. This avoids runtime overhead
2785         // at the cost of eager binding (and one extra byte of encoding).
2786         OpFlags = X86II::MO_GOTPCREL;
2787         WrapperKind = X86ISD::WrapperRIP;
2788         ExtraLoad = true;
2789       }
2790
2791       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2792                                           G->getOffset(), OpFlags);
2793
2794       // Add a wrapper if needed.
2795       if (WrapperKind != ISD::DELETED_NODE)
2796         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2797       // Add extra indirection if needed.
2798       if (ExtraLoad)
2799         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2800                              MachinePointerInfo::getGOT(),
2801                              false, false, false, 0);
2802     }
2803   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2804     unsigned char OpFlags = 0;
2805
2806     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2807     // external symbols should go through the PLT.
2808     if (Subtarget->isTargetELF() &&
2809         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2810       OpFlags = X86II::MO_PLT;
2811     } else if (Subtarget->isPICStyleStubAny() &&
2812                (!Subtarget->getTargetTriple().isMacOSX() ||
2813                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2814       // PC-relative references to external symbols should go through $stub,
2815       // unless we're building with the leopard linker or later, which
2816       // automatically synthesizes these stubs.
2817       OpFlags = X86II::MO_DARWIN_STUB;
2818     }
2819
2820     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2821                                          OpFlags);
2822   }
2823
2824   // Returns a chain & a flag for retval copy to use.
2825   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2826   SmallVector<SDValue, 8> Ops;
2827
2828   if (!IsSibcall && isTailCall) {
2829     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2830                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2831     InFlag = Chain.getValue(1);
2832   }
2833
2834   Ops.push_back(Chain);
2835   Ops.push_back(Callee);
2836
2837   if (isTailCall)
2838     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2839
2840   // Add argument registers to the end of the list so that they are known live
2841   // into the call.
2842   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2843     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2844                                   RegsToPass[i].second.getValueType()));
2845
2846   // Add a register mask operand representing the call-preserved registers.
2847   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2848   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2849   assert(Mask && "Missing call preserved mask for calling convention");
2850   Ops.push_back(DAG.getRegisterMask(Mask));
2851
2852   if (InFlag.getNode())
2853     Ops.push_back(InFlag);
2854
2855   if (isTailCall) {
2856     // We used to do:
2857     //// If this is the first return lowered for this function, add the regs
2858     //// to the liveout set for the function.
2859     // This isn't right, although it's probably harmless on x86; liveouts
2860     // should be computed from returns not tail calls.  Consider a void
2861     // function making a tail call to a function returning int.
2862     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2863   }
2864
2865   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2866   InFlag = Chain.getValue(1);
2867
2868   // Create the CALLSEQ_END node.
2869   unsigned NumBytesForCalleeToPush;
2870   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2871                        getTargetMachine().Options.GuaranteedTailCallOpt))
2872     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2873   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2874            SR == StackStructReturn)
2875     // If this is a call to a struct-return function, the callee
2876     // pops the hidden struct pointer, so we have to push it back.
2877     // This is common for Darwin/X86, Linux & Mingw32 targets.
2878     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2879     NumBytesForCalleeToPush = 4;
2880   else
2881     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2882
2883   // Returns a flag for retval copy to use.
2884   if (!IsSibcall) {
2885     Chain = DAG.getCALLSEQ_END(Chain,
2886                                DAG.getIntPtrConstant(NumBytes, true),
2887                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2888                                                      true),
2889                                InFlag, dl);
2890     InFlag = Chain.getValue(1);
2891   }
2892
2893   // Handle result values, copying them out of physregs into vregs that we
2894   // return.
2895   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2896                          Ins, dl, DAG, InVals);
2897 }
2898
2899 //===----------------------------------------------------------------------===//
2900 //                Fast Calling Convention (tail call) implementation
2901 //===----------------------------------------------------------------------===//
2902
2903 //  Like std call, callee cleans arguments, convention except that ECX is
2904 //  reserved for storing the tail called function address. Only 2 registers are
2905 //  free for argument passing (inreg). Tail call optimization is performed
2906 //  provided:
2907 //                * tailcallopt is enabled
2908 //                * caller/callee are fastcc
2909 //  On X86_64 architecture with GOT-style position independent code only local
2910 //  (within module) calls are supported at the moment.
2911 //  To keep the stack aligned according to platform abi the function
2912 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2913 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2914 //  If a tail called function callee has more arguments than the caller the
2915 //  caller needs to make sure that there is room to move the RETADDR to. This is
2916 //  achieved by reserving an area the size of the argument delta right after the
2917 //  original REtADDR, but before the saved framepointer or the spilled registers
2918 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2919 //  stack layout:
2920 //    arg1
2921 //    arg2
2922 //    RETADDR
2923 //    [ new RETADDR
2924 //      move area ]
2925 //    (possible EBP)
2926 //    ESI
2927 //    EDI
2928 //    local1 ..
2929
2930 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2931 /// for a 16 byte align requirement.
2932 unsigned
2933 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2934                                                SelectionDAG& DAG) const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   const TargetMachine &TM = MF.getTarget();
2937   const X86RegisterInfo *RegInfo =
2938     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2939   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2940   unsigned StackAlignment = TFI.getStackAlignment();
2941   uint64_t AlignMask = StackAlignment - 1;
2942   int64_t Offset = StackSize;
2943   unsigned SlotSize = RegInfo->getSlotSize();
2944   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2945     // Number smaller than 12 so just add the difference.
2946     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2947   } else {
2948     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2949     Offset = ((~AlignMask) & Offset) + StackAlignment +
2950       (StackAlignment-SlotSize);
2951   }
2952   return Offset;
2953 }
2954
2955 /// MatchingStackOffset - Return true if the given stack call argument is
2956 /// already available in the same position (relatively) of the caller's
2957 /// incoming argument stack.
2958 static
2959 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2960                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2961                          const X86InstrInfo *TII) {
2962   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2963   int FI = INT_MAX;
2964   if (Arg.getOpcode() == ISD::CopyFromReg) {
2965     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2966     if (!TargetRegisterInfo::isVirtualRegister(VR))
2967       return false;
2968     MachineInstr *Def = MRI->getVRegDef(VR);
2969     if (!Def)
2970       return false;
2971     if (!Flags.isByVal()) {
2972       if (!TII->isLoadFromStackSlot(Def, FI))
2973         return false;
2974     } else {
2975       unsigned Opcode = Def->getOpcode();
2976       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2977           Def->getOperand(1).isFI()) {
2978         FI = Def->getOperand(1).getIndex();
2979         Bytes = Flags.getByValSize();
2980       } else
2981         return false;
2982     }
2983   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2984     if (Flags.isByVal())
2985       // ByVal argument is passed in as a pointer but it's now being
2986       // dereferenced. e.g.
2987       // define @foo(%struct.X* %A) {
2988       //   tail call @bar(%struct.X* byval %A)
2989       // }
2990       return false;
2991     SDValue Ptr = Ld->getBasePtr();
2992     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2993     if (!FINode)
2994       return false;
2995     FI = FINode->getIndex();
2996   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2997     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2998     FI = FINode->getIndex();
2999     Bytes = Flags.getByValSize();
3000   } else
3001     return false;
3002
3003   assert(FI != INT_MAX);
3004   if (!MFI->isFixedObjectIndex(FI))
3005     return false;
3006   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3007 }
3008
3009 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3010 /// for tail call optimization. Targets which want to do tail call
3011 /// optimization should implement this function.
3012 bool
3013 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3014                                                      CallingConv::ID CalleeCC,
3015                                                      bool isVarArg,
3016                                                      bool isCalleeStructRet,
3017                                                      bool isCallerStructRet,
3018                                                      Type *RetTy,
3019                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3020                                     const SmallVectorImpl<SDValue> &OutVals,
3021                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3022                                                      SelectionDAG &DAG) const {
3023   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3024     return false;
3025
3026   // If -tailcallopt is specified, make fastcc functions tail-callable.
3027   const MachineFunction &MF = DAG.getMachineFunction();
3028   const Function *CallerF = MF.getFunction();
3029
3030   // If the function return type is x86_fp80 and the callee return type is not,
3031   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3032   // perform a tailcall optimization here.
3033   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3034     return false;
3035
3036   CallingConv::ID CallerCC = CallerF->getCallingConv();
3037   bool CCMatch = CallerCC == CalleeCC;
3038   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3039   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3040
3041   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3042     if (IsTailCallConvention(CalleeCC) && CCMatch)
3043       return true;
3044     return false;
3045   }
3046
3047   // Look for obvious safe cases to perform tail call optimization that do not
3048   // require ABI changes. This is what gcc calls sibcall.
3049
3050   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3051   // emit a special epilogue.
3052   const X86RegisterInfo *RegInfo =
3053     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3054   if (RegInfo->needsStackRealignment(MF))
3055     return false;
3056
3057   // Also avoid sibcall optimization if either caller or callee uses struct
3058   // return semantics.
3059   if (isCalleeStructRet || isCallerStructRet)
3060     return false;
3061
3062   // An stdcall caller is expected to clean up its arguments; the callee
3063   // isn't going to do that.
3064   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3065     return false;
3066
3067   // Do not sibcall optimize vararg calls unless all arguments are passed via
3068   // registers.
3069   if (isVarArg && !Outs.empty()) {
3070
3071     // Optimizing for varargs on Win64 is unlikely to be safe without
3072     // additional testing.
3073     if (IsCalleeWin64 || IsCallerWin64)
3074       return false;
3075
3076     SmallVector<CCValAssign, 16> ArgLocs;
3077     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3078                    getTargetMachine(), ArgLocs, *DAG.getContext());
3079
3080     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3081     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3082       if (!ArgLocs[i].isRegLoc())
3083         return false;
3084   }
3085
3086   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3087   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3088   // this into a sibcall.
3089   bool Unused = false;
3090   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3091     if (!Ins[i].Used) {
3092       Unused = true;
3093       break;
3094     }
3095   }
3096   if (Unused) {
3097     SmallVector<CCValAssign, 16> RVLocs;
3098     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3099                    getTargetMachine(), RVLocs, *DAG.getContext());
3100     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3101     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3102       CCValAssign &VA = RVLocs[i];
3103       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3104         return false;
3105     }
3106   }
3107
3108   // If the calling conventions do not match, then we'd better make sure the
3109   // results are returned in the same way as what the caller expects.
3110   if (!CCMatch) {
3111     SmallVector<CCValAssign, 16> RVLocs1;
3112     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3113                     getTargetMachine(), RVLocs1, *DAG.getContext());
3114     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3115
3116     SmallVector<CCValAssign, 16> RVLocs2;
3117     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3118                     getTargetMachine(), RVLocs2, *DAG.getContext());
3119     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3120
3121     if (RVLocs1.size() != RVLocs2.size())
3122       return false;
3123     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3124       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3125         return false;
3126       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3127         return false;
3128       if (RVLocs1[i].isRegLoc()) {
3129         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3130           return false;
3131       } else {
3132         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3133           return false;
3134       }
3135     }
3136   }
3137
3138   // If the callee takes no arguments then go on to check the results of the
3139   // call.
3140   if (!Outs.empty()) {
3141     // Check if stack adjustment is needed. For now, do not do this if any
3142     // argument is passed on the stack.
3143     SmallVector<CCValAssign, 16> ArgLocs;
3144     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3145                    getTargetMachine(), ArgLocs, *DAG.getContext());
3146
3147     // Allocate shadow area for Win64
3148     if (IsCalleeWin64)
3149       CCInfo.AllocateStack(32, 8);
3150
3151     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3152     if (CCInfo.getNextStackOffset()) {
3153       MachineFunction &MF = DAG.getMachineFunction();
3154       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3155         return false;
3156
3157       // Check if the arguments are already laid out in the right way as
3158       // the caller's fixed stack objects.
3159       MachineFrameInfo *MFI = MF.getFrameInfo();
3160       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3161       const X86InstrInfo *TII =
3162         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3163       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3164         CCValAssign &VA = ArgLocs[i];
3165         SDValue Arg = OutVals[i];
3166         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3167         if (VA.getLocInfo() == CCValAssign::Indirect)
3168           return false;
3169         if (!VA.isRegLoc()) {
3170           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3171                                    MFI, MRI, TII))
3172             return false;
3173         }
3174       }
3175     }
3176
3177     // If the tailcall address may be in a register, then make sure it's
3178     // possible to register allocate for it. In 32-bit, the call address can
3179     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3180     // callee-saved registers are restored. These happen to be the same
3181     // registers used to pass 'inreg' arguments so watch out for those.
3182     if (!Subtarget->is64Bit() &&
3183         ((!isa<GlobalAddressSDNode>(Callee) &&
3184           !isa<ExternalSymbolSDNode>(Callee)) ||
3185          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3186       unsigned NumInRegs = 0;
3187       // In PIC we need an extra register to formulate the address computation
3188       // for the callee.
3189       unsigned MaxInRegs =
3190           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3191
3192       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3193         CCValAssign &VA = ArgLocs[i];
3194         if (!VA.isRegLoc())
3195           continue;
3196         unsigned Reg = VA.getLocReg();
3197         switch (Reg) {
3198         default: break;
3199         case X86::EAX: case X86::EDX: case X86::ECX:
3200           if (++NumInRegs == MaxInRegs)
3201             return false;
3202           break;
3203         }
3204       }
3205     }
3206   }
3207
3208   return true;
3209 }
3210
3211 FastISel *
3212 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3213                                   const TargetLibraryInfo *libInfo) const {
3214   return X86::createFastISel(funcInfo, libInfo);
3215 }
3216
3217 //===----------------------------------------------------------------------===//
3218 //                           Other Lowering Hooks
3219 //===----------------------------------------------------------------------===//
3220
3221 static bool MayFoldLoad(SDValue Op) {
3222   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3223 }
3224
3225 static bool MayFoldIntoStore(SDValue Op) {
3226   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3227 }
3228
3229 static bool isTargetShuffle(unsigned Opcode) {
3230   switch(Opcode) {
3231   default: return false;
3232   case X86ISD::PSHUFD:
3233   case X86ISD::PSHUFHW:
3234   case X86ISD::PSHUFLW:
3235   case X86ISD::SHUFP:
3236   case X86ISD::PALIGNR:
3237   case X86ISD::MOVLHPS:
3238   case X86ISD::MOVLHPD:
3239   case X86ISD::MOVHLPS:
3240   case X86ISD::MOVLPS:
3241   case X86ISD::MOVLPD:
3242   case X86ISD::MOVSHDUP:
3243   case X86ISD::MOVSLDUP:
3244   case X86ISD::MOVDDUP:
3245   case X86ISD::MOVSS:
3246   case X86ISD::MOVSD:
3247   case X86ISD::UNPCKL:
3248   case X86ISD::UNPCKH:
3249   case X86ISD::VPERMILP:
3250   case X86ISD::VPERM2X128:
3251   case X86ISD::VPERMI:
3252     return true;
3253   }
3254 }
3255
3256 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3257                                     SDValue V1, SelectionDAG &DAG) {
3258   switch(Opc) {
3259   default: llvm_unreachable("Unknown x86 shuffle node");
3260   case X86ISD::MOVSHDUP:
3261   case X86ISD::MOVSLDUP:
3262   case X86ISD::MOVDDUP:
3263     return DAG.getNode(Opc, dl, VT, V1);
3264   }
3265 }
3266
3267 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3268                                     SDValue V1, unsigned TargetMask,
3269                                     SelectionDAG &DAG) {
3270   switch(Opc) {
3271   default: llvm_unreachable("Unknown x86 shuffle node");
3272   case X86ISD::PSHUFD:
3273   case X86ISD::PSHUFHW:
3274   case X86ISD::PSHUFLW:
3275   case X86ISD::VPERMILP:
3276   case X86ISD::VPERMI:
3277     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3278   }
3279 }
3280
3281 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3282                                     SDValue V1, SDValue V2, unsigned TargetMask,
3283                                     SelectionDAG &DAG) {
3284   switch(Opc) {
3285   default: llvm_unreachable("Unknown x86 shuffle node");
3286   case X86ISD::PALIGNR:
3287   case X86ISD::SHUFP:
3288   case X86ISD::VPERM2X128:
3289     return DAG.getNode(Opc, dl, VT, V1, V2,
3290                        DAG.getConstant(TargetMask, MVT::i8));
3291   }
3292 }
3293
3294 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3295                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3296   switch(Opc) {
3297   default: llvm_unreachable("Unknown x86 shuffle node");
3298   case X86ISD::MOVLHPS:
3299   case X86ISD::MOVLHPD:
3300   case X86ISD::MOVHLPS:
3301   case X86ISD::MOVLPS:
3302   case X86ISD::MOVLPD:
3303   case X86ISD::MOVSS:
3304   case X86ISD::MOVSD:
3305   case X86ISD::UNPCKL:
3306   case X86ISD::UNPCKH:
3307     return DAG.getNode(Opc, dl, VT, V1, V2);
3308   }
3309 }
3310
3311 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3312   MachineFunction &MF = DAG.getMachineFunction();
3313   const X86RegisterInfo *RegInfo =
3314     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3315   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3316   int ReturnAddrIndex = FuncInfo->getRAIndex();
3317
3318   if (ReturnAddrIndex == 0) {
3319     // Set up a frame object for the return address.
3320     unsigned SlotSize = RegInfo->getSlotSize();
3321     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3322                                                            -(int64_t)SlotSize,
3323                                                            false);
3324     FuncInfo->setRAIndex(ReturnAddrIndex);
3325   }
3326
3327   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3328 }
3329
3330 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3331                                        bool hasSymbolicDisplacement) {
3332   // Offset should fit into 32 bit immediate field.
3333   if (!isInt<32>(Offset))
3334     return false;
3335
3336   // If we don't have a symbolic displacement - we don't have any extra
3337   // restrictions.
3338   if (!hasSymbolicDisplacement)
3339     return true;
3340
3341   // FIXME: Some tweaks might be needed for medium code model.
3342   if (M != CodeModel::Small && M != CodeModel::Kernel)
3343     return false;
3344
3345   // For small code model we assume that latest object is 16MB before end of 31
3346   // bits boundary. We may also accept pretty large negative constants knowing
3347   // that all objects are in the positive half of address space.
3348   if (M == CodeModel::Small && Offset < 16*1024*1024)
3349     return true;
3350
3351   // For kernel code model we know that all object resist in the negative half
3352   // of 32bits address space. We may not accept negative offsets, since they may
3353   // be just off and we may accept pretty large positive ones.
3354   if (M == CodeModel::Kernel && Offset > 0)
3355     return true;
3356
3357   return false;
3358 }
3359
3360 /// isCalleePop - Determines whether the callee is required to pop its
3361 /// own arguments. Callee pop is necessary to support tail calls.
3362 bool X86::isCalleePop(CallingConv::ID CallingConv,
3363                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3364   if (IsVarArg)
3365     return false;
3366
3367   switch (CallingConv) {
3368   default:
3369     return false;
3370   case CallingConv::X86_StdCall:
3371     return !is64Bit;
3372   case CallingConv::X86_FastCall:
3373     return !is64Bit;
3374   case CallingConv::X86_ThisCall:
3375     return !is64Bit;
3376   case CallingConv::Fast:
3377     return TailCallOpt;
3378   case CallingConv::GHC:
3379     return TailCallOpt;
3380   case CallingConv::HiPE:
3381     return TailCallOpt;
3382   }
3383 }
3384
3385 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3386 /// specific condition code, returning the condition code and the LHS/RHS of the
3387 /// comparison to make.
3388 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3389                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3390   if (!isFP) {
3391     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3392       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3393         // X > -1   -> X == 0, jump !sign.
3394         RHS = DAG.getConstant(0, RHS.getValueType());
3395         return X86::COND_NS;
3396       }
3397       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3398         // X < 0   -> X == 0, jump on sign.
3399         return X86::COND_S;
3400       }
3401       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3402         // X < 1   -> X <= 0
3403         RHS = DAG.getConstant(0, RHS.getValueType());
3404         return X86::COND_LE;
3405       }
3406     }
3407
3408     switch (SetCCOpcode) {
3409     default: llvm_unreachable("Invalid integer condition!");
3410     case ISD::SETEQ:  return X86::COND_E;
3411     case ISD::SETGT:  return X86::COND_G;
3412     case ISD::SETGE:  return X86::COND_GE;
3413     case ISD::SETLT:  return X86::COND_L;
3414     case ISD::SETLE:  return X86::COND_LE;
3415     case ISD::SETNE:  return X86::COND_NE;
3416     case ISD::SETULT: return X86::COND_B;
3417     case ISD::SETUGT: return X86::COND_A;
3418     case ISD::SETULE: return X86::COND_BE;
3419     case ISD::SETUGE: return X86::COND_AE;
3420     }
3421   }
3422
3423   // First determine if it is required or is profitable to flip the operands.
3424
3425   // If LHS is a foldable load, but RHS is not, flip the condition.
3426   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3427       !ISD::isNON_EXTLoad(RHS.getNode())) {
3428     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3429     std::swap(LHS, RHS);
3430   }
3431
3432   switch (SetCCOpcode) {
3433   default: break;
3434   case ISD::SETOLT:
3435   case ISD::SETOLE:
3436   case ISD::SETUGT:
3437   case ISD::SETUGE:
3438     std::swap(LHS, RHS);
3439     break;
3440   }
3441
3442   // On a floating point condition, the flags are set as follows:
3443   // ZF  PF  CF   op
3444   //  0 | 0 | 0 | X > Y
3445   //  0 | 0 | 1 | X < Y
3446   //  1 | 0 | 0 | X == Y
3447   //  1 | 1 | 1 | unordered
3448   switch (SetCCOpcode) {
3449   default: llvm_unreachable("Condcode should be pre-legalized away");
3450   case ISD::SETUEQ:
3451   case ISD::SETEQ:   return X86::COND_E;
3452   case ISD::SETOLT:              // flipped
3453   case ISD::SETOGT:
3454   case ISD::SETGT:   return X86::COND_A;
3455   case ISD::SETOLE:              // flipped
3456   case ISD::SETOGE:
3457   case ISD::SETGE:   return X86::COND_AE;
3458   case ISD::SETUGT:              // flipped
3459   case ISD::SETULT:
3460   case ISD::SETLT:   return X86::COND_B;
3461   case ISD::SETUGE:              // flipped
3462   case ISD::SETULE:
3463   case ISD::SETLE:   return X86::COND_BE;
3464   case ISD::SETONE:
3465   case ISD::SETNE:   return X86::COND_NE;
3466   case ISD::SETUO:   return X86::COND_P;
3467   case ISD::SETO:    return X86::COND_NP;
3468   case ISD::SETOEQ:
3469   case ISD::SETUNE:  return X86::COND_INVALID;
3470   }
3471 }
3472
3473 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3474 /// code. Current x86 isa includes the following FP cmov instructions:
3475 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3476 static bool hasFPCMov(unsigned X86CC) {
3477   switch (X86CC) {
3478   default:
3479     return false;
3480   case X86::COND_B:
3481   case X86::COND_BE:
3482   case X86::COND_E:
3483   case X86::COND_P:
3484   case X86::COND_A:
3485   case X86::COND_AE:
3486   case X86::COND_NE:
3487   case X86::COND_NP:
3488     return true;
3489   }
3490 }
3491
3492 /// isFPImmLegal - Returns true if the target can instruction select the
3493 /// specified FP immediate natively. If false, the legalizer will
3494 /// materialize the FP immediate as a load from a constant pool.
3495 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3496   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3497     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3498       return true;
3499   }
3500   return false;
3501 }
3502
3503 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3504 /// the specified range (L, H].
3505 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3506   return (Val < 0) || (Val >= Low && Val < Hi);
3507 }
3508
3509 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3510 /// specified value.
3511 static bool isUndefOrEqual(int Val, int CmpVal) {
3512   return (Val < 0 || Val == CmpVal);
3513 }
3514
3515 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3516 /// from position Pos and ending in Pos+Size, falls within the specified
3517 /// sequential range (L, L+Pos]. or is undef.
3518 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3519                                        unsigned Pos, unsigned Size, int Low) {
3520   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3521     if (!isUndefOrEqual(Mask[i], Low))
3522       return false;
3523   return true;
3524 }
3525
3526 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3527 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3528 /// the second operand.
3529 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3530   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3531     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3532   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3533     return (Mask[0] < 2 && Mask[1] < 2);
3534   return false;
3535 }
3536
3537 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3538 /// is suitable for input to PSHUFHW.
3539 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3540   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3541     return false;
3542
3543   // Lower quadword copied in order or undef.
3544   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3545     return false;
3546
3547   // Upper quadword shuffled.
3548   for (unsigned i = 4; i != 8; ++i)
3549     if (!isUndefOrInRange(Mask[i], 4, 8))
3550       return false;
3551
3552   if (VT == MVT::v16i16) {
3553     // Lower quadword copied in order or undef.
3554     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3555       return false;
3556
3557     // Upper quadword shuffled.
3558     for (unsigned i = 12; i != 16; ++i)
3559       if (!isUndefOrInRange(Mask[i], 12, 16))
3560         return false;
3561   }
3562
3563   return true;
3564 }
3565
3566 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3567 /// is suitable for input to PSHUFLW.
3568 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3569   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3570     return false;
3571
3572   // Upper quadword copied in order.
3573   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3574     return false;
3575
3576   // Lower quadword shuffled.
3577   for (unsigned i = 0; i != 4; ++i)
3578     if (!isUndefOrInRange(Mask[i], 0, 4))
3579       return false;
3580
3581   if (VT == MVT::v16i16) {
3582     // Upper quadword copied in order.
3583     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3584       return false;
3585
3586     // Lower quadword shuffled.
3587     for (unsigned i = 8; i != 12; ++i)
3588       if (!isUndefOrInRange(Mask[i], 8, 12))
3589         return false;
3590   }
3591
3592   return true;
3593 }
3594
3595 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3596 /// is suitable for input to PALIGNR.
3597 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3598                           const X86Subtarget *Subtarget) {
3599   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3600       (VT.is256BitVector() && !Subtarget->hasInt256()))
3601     return false;
3602
3603   unsigned NumElts = VT.getVectorNumElements();
3604   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3605   unsigned NumLaneElts = NumElts/NumLanes;
3606
3607   // Do not handle 64-bit element shuffles with palignr.
3608   if (NumLaneElts == 2)
3609     return false;
3610
3611   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3612     unsigned i;
3613     for (i = 0; i != NumLaneElts; ++i) {
3614       if (Mask[i+l] >= 0)
3615         break;
3616     }
3617
3618     // Lane is all undef, go to next lane
3619     if (i == NumLaneElts)
3620       continue;
3621
3622     int Start = Mask[i+l];
3623
3624     // Make sure its in this lane in one of the sources
3625     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3626         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3627       return false;
3628
3629     // If not lane 0, then we must match lane 0
3630     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3631       return false;
3632
3633     // Correct second source to be contiguous with first source
3634     if (Start >= (int)NumElts)
3635       Start -= NumElts - NumLaneElts;
3636
3637     // Make sure we're shifting in the right direction.
3638     if (Start <= (int)(i+l))
3639       return false;
3640
3641     Start -= i;
3642
3643     // Check the rest of the elements to see if they are consecutive.
3644     for (++i; i != NumLaneElts; ++i) {
3645       int Idx = Mask[i+l];
3646
3647       // Make sure its in this lane
3648       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3649           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3650         return false;
3651
3652       // If not lane 0, then we must match lane 0
3653       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3654         return false;
3655
3656       if (Idx >= (int)NumElts)
3657         Idx -= NumElts - NumLaneElts;
3658
3659       if (!isUndefOrEqual(Idx, Start+i))
3660         return false;
3661
3662     }
3663   }
3664
3665   return true;
3666 }
3667
3668 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3669 /// the two vector operands have swapped position.
3670 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3671                                      unsigned NumElems) {
3672   for (unsigned i = 0; i != NumElems; ++i) {
3673     int idx = Mask[i];
3674     if (idx < 0)
3675       continue;
3676     else if (idx < (int)NumElems)
3677       Mask[i] = idx + NumElems;
3678     else
3679       Mask[i] = idx - NumElems;
3680   }
3681 }
3682
3683 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3684 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3685 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3686 /// reverse of what x86 shuffles want.
3687 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3688
3689   unsigned NumElems = VT.getVectorNumElements();
3690   unsigned NumLanes = VT.getSizeInBits()/128;
3691   unsigned NumLaneElems = NumElems/NumLanes;
3692
3693   if (NumLaneElems != 2 && NumLaneElems != 4)
3694     return false;
3695
3696   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3697   bool symetricMaskRequired =
3698     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3699
3700   // VSHUFPSY divides the resulting vector into 4 chunks.
3701   // The sources are also splitted into 4 chunks, and each destination
3702   // chunk must come from a different source chunk.
3703   //
3704   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3705   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3706   //
3707   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3708   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3709   //
3710   // VSHUFPDY divides the resulting vector into 4 chunks.
3711   // The sources are also splitted into 4 chunks, and each destination
3712   // chunk must come from a different source chunk.
3713   //
3714   //  SRC1 =>      X3       X2       X1       X0
3715   //  SRC2 =>      Y3       Y2       Y1       Y0
3716   //
3717   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3718   //
3719   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3720   unsigned HalfLaneElems = NumLaneElems/2;
3721   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3722     for (unsigned i = 0; i != NumLaneElems; ++i) {
3723       int Idx = Mask[i+l];
3724       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3725       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3726         return false;
3727       // For VSHUFPSY, the mask of the second half must be the same as the
3728       // first but with the appropriate offsets. This works in the same way as
3729       // VPERMILPS works with masks.
3730       if (!symetricMaskRequired || Idx < 0)
3731         continue;
3732       if (MaskVal[i] < 0) {
3733         MaskVal[i] = Idx - l;
3734         continue;
3735       }
3736       if ((signed)(Idx - l) != MaskVal[i])
3737         return false;
3738     }
3739   }
3740
3741   return true;
3742 }
3743
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3747   if (!VT.is128BitVector())
3748     return false;
3749
3750   unsigned NumElems = VT.getVectorNumElements();
3751
3752   if (NumElems != 4)
3753     return false;
3754
3755   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756   return isUndefOrEqual(Mask[0], 6) &&
3757          isUndefOrEqual(Mask[1], 7) &&
3758          isUndefOrEqual(Mask[2], 2) &&
3759          isUndefOrEqual(Mask[3], 3);
3760 }
3761
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3764 /// <2, 3, 2, 3>
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3766   if (!VT.is128BitVector())
3767     return false;
3768
3769   unsigned NumElems = VT.getVectorNumElements();
3770
3771   if (NumElems != 4)
3772     return false;
3773
3774   return isUndefOrEqual(Mask[0], 2) &&
3775          isUndefOrEqual(Mask[1], 3) &&
3776          isUndefOrEqual(Mask[2], 2) &&
3777          isUndefOrEqual(Mask[3], 3);
3778 }
3779
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3783   if (!VT.is128BitVector())
3784     return false;
3785
3786   unsigned NumElems = VT.getVectorNumElements();
3787
3788   if (NumElems != 2 && NumElems != 4)
3789     return false;
3790
3791   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792     if (!isUndefOrEqual(Mask[i], i + NumElems))
3793       return false;
3794
3795   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796     if (!isUndefOrEqual(Mask[i], i))
3797       return false;
3798
3799   return true;
3800 }
3801
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3805   if (!VT.is128BitVector())
3806     return false;
3807
3808   unsigned NumElems = VT.getVectorNumElements();
3809
3810   if (NumElems != 2 && NumElems != 4)
3811     return false;
3812
3813   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814     if (!isUndefOrEqual(Mask[i], i))
3815       return false;
3816
3817   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3819       return false;
3820
3821   return true;
3822 }
3823
3824 //
3825 // Some special combinations that can be optimized.
3826 //
3827 static
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829                                SelectionDAG &DAG) {
3830   MVT VT = SVOp->getSimpleValueType(0);
3831   SDLoc dl(SVOp);
3832
3833   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3834     return SDValue();
3835
3836   ArrayRef<int> Mask = SVOp->getMask();
3837
3838   // These are the special masks that may be optimized.
3839   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3841   bool MatchEvenMask = true;
3842   bool MatchOddMask  = true;
3843   for (int i=0; i<8; ++i) {
3844     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845       MatchEvenMask = false;
3846     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847       MatchOddMask = false;
3848   }
3849
3850   if (!MatchEvenMask && !MatchOddMask)
3851     return SDValue();
3852
3853   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3854
3855   SDValue Op0 = SVOp->getOperand(0);
3856   SDValue Op1 = SVOp->getOperand(1);
3857
3858   if (MatchEvenMask) {
3859     // Shift the second operand right to 32 bits.
3860     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3862   } else {
3863     // Shift the first operand left to 32 bits.
3864     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3866   }
3867   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3869 }
3870
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3874                          bool HasInt256, bool V2IsSplat = false) {
3875
3876   assert(VT.getSizeInBits() >= 128 &&
3877          "Unsupported vector type for unpckl");
3878
3879   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3880   unsigned NumLanes;
3881   unsigned NumOf256BitLanes;
3882   unsigned NumElts = VT.getVectorNumElements();
3883   if (VT.is256BitVector()) {
3884     if (NumElts != 4 && NumElts != 8 &&
3885         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3886     return false;
3887     NumLanes = 2;
3888     NumOf256BitLanes = 1;
3889   } else if (VT.is512BitVector()) {
3890     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3891            "Unsupported vector type for unpckh");
3892     NumLanes = 2;
3893     NumOf256BitLanes = 2;
3894   } else {
3895     NumLanes = 1;
3896     NumOf256BitLanes = 1;
3897   }
3898
3899   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3900   unsigned NumLaneElts = NumEltsInStride/NumLanes;
3901
3902   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
3903     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
3904       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3905         int BitI  = Mask[l256*NumEltsInStride+l+i];
3906         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
3907         if (!isUndefOrEqual(BitI, j+l256*NumElts))
3908           return false;
3909         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
3910           return false;
3911         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
3912           return false;
3913       }
3914     }
3915   }
3916   return true;
3917 }
3918
3919 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3920 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3921 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3922                          bool HasInt256, bool V2IsSplat = false) {
3923   assert(VT.getSizeInBits() >= 128 &&
3924          "Unsupported vector type for unpckh");
3925
3926   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3927   unsigned NumLanes;
3928   unsigned NumOf256BitLanes;
3929   unsigned NumElts = VT.getVectorNumElements();
3930   if (VT.is256BitVector()) {
3931     if (NumElts != 4 && NumElts != 8 &&
3932         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3933     return false;
3934     NumLanes = 2;
3935     NumOf256BitLanes = 1;
3936   } else if (VT.is512BitVector()) {
3937     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3938            "Unsupported vector type for unpckh");
3939     NumLanes = 2;
3940     NumOf256BitLanes = 2;
3941   } else {
3942     NumLanes = 1;
3943     NumOf256BitLanes = 1;
3944   }
3945
3946   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3947   unsigned NumLaneElts = NumEltsInStride/NumLanes;
3948
3949   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
3950     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
3951       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
3952         int BitI  = Mask[l256*NumEltsInStride+l+i];
3953         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
3954         if (!isUndefOrEqual(BitI, j+l256*NumElts))
3955           return false;
3956         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
3957           return false;
3958         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
3959           return false;
3960       }
3961     }
3962   }
3963   return true;
3964 }
3965
3966 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3967 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3968 /// <0, 0, 1, 1>
3969 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3970   unsigned NumElts = VT.getVectorNumElements();
3971   bool Is256BitVec = VT.is256BitVector();
3972
3973   if (VT.is512BitVector())
3974     return false;
3975   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3976          "Unsupported vector type for unpckh");
3977
3978   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3979       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3980     return false;
3981
3982   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3983   // FIXME: Need a better way to get rid of this, there's no latency difference
3984   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3985   // the former later. We should also remove the "_undef" special mask.
3986   if (NumElts == 4 && Is256BitVec)
3987     return false;
3988
3989   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3990   // independently on 128-bit lanes.
3991   unsigned NumLanes = VT.getSizeInBits()/128;
3992   unsigned NumLaneElts = NumElts/NumLanes;
3993
3994   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3995     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3996       int BitI  = Mask[l+i];
3997       int BitI1 = Mask[l+i+1];
3998
3999       if (!isUndefOrEqual(BitI, j))
4000         return false;
4001       if (!isUndefOrEqual(BitI1, j))
4002         return false;
4003     }
4004   }
4005
4006   return true;
4007 }
4008
4009 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4010 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4011 /// <2, 2, 3, 3>
4012 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4013   unsigned NumElts = VT.getVectorNumElements();
4014
4015   if (VT.is512BitVector())
4016     return false;
4017
4018   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4019          "Unsupported vector type for unpckh");
4020
4021   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4022       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4023     return false;
4024
4025   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4026   // independently on 128-bit lanes.
4027   unsigned NumLanes = VT.getSizeInBits()/128;
4028   unsigned NumLaneElts = NumElts/NumLanes;
4029
4030   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4031     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4032       int BitI  = Mask[l+i];
4033       int BitI1 = Mask[l+i+1];
4034       if (!isUndefOrEqual(BitI, j))
4035         return false;
4036       if (!isUndefOrEqual(BitI1, j))
4037         return false;
4038     }
4039   }
4040   return true;
4041 }
4042
4043 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4044 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4045 /// MOVSD, and MOVD, i.e. setting the lowest element.
4046 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4047   if (VT.getVectorElementType().getSizeInBits() < 32)
4048     return false;
4049   if (!VT.is128BitVector())
4050     return false;
4051
4052   unsigned NumElts = VT.getVectorNumElements();
4053
4054   if (!isUndefOrEqual(Mask[0], NumElts))
4055     return false;
4056
4057   for (unsigned i = 1; i != NumElts; ++i)
4058     if (!isUndefOrEqual(Mask[i], i))
4059       return false;
4060
4061   return true;
4062 }
4063
4064 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4065 /// as permutations between 128-bit chunks or halves. As an example: this
4066 /// shuffle bellow:
4067 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4068 /// The first half comes from the second half of V1 and the second half from the
4069 /// the second half of V2.
4070 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4071   if (!HasFp256 || !VT.is256BitVector())
4072     return false;
4073
4074   // The shuffle result is divided into half A and half B. In total the two
4075   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4076   // B must come from C, D, E or F.
4077   unsigned HalfSize = VT.getVectorNumElements()/2;
4078   bool MatchA = false, MatchB = false;
4079
4080   // Check if A comes from one of C, D, E, F.
4081   for (unsigned Half = 0; Half != 4; ++Half) {
4082     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4083       MatchA = true;
4084       break;
4085     }
4086   }
4087
4088   // Check if B comes from one of C, D, E, F.
4089   for (unsigned Half = 0; Half != 4; ++Half) {
4090     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4091       MatchB = true;
4092       break;
4093     }
4094   }
4095
4096   return MatchA && MatchB;
4097 }
4098
4099 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4100 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4101 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4102   MVT VT = SVOp->getSimpleValueType(0);
4103
4104   unsigned HalfSize = VT.getVectorNumElements()/2;
4105
4106   unsigned FstHalf = 0, SndHalf = 0;
4107   for (unsigned i = 0; i < HalfSize; ++i) {
4108     if (SVOp->getMaskElt(i) > 0) {
4109       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4110       break;
4111     }
4112   }
4113   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4114     if (SVOp->getMaskElt(i) > 0) {
4115       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4116       break;
4117     }
4118   }
4119
4120   return (FstHalf | (SndHalf << 4));
4121 }
4122
4123 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4124 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4125   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4126   if (EltSize < 32)
4127     return false;
4128
4129   unsigned NumElts = VT.getVectorNumElements();
4130   Imm8 = 0;
4131   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4132     for (unsigned i = 0; i != NumElts; ++i) {
4133       if (Mask[i] < 0)
4134         continue;
4135       Imm8 |= Mask[i] << (i*2);
4136     }
4137     return true;
4138   }
4139
4140   unsigned LaneSize = 4;
4141   SmallVector<int, 4> MaskVal(LaneSize, -1);
4142
4143   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4144     for (unsigned i = 0; i != LaneSize; ++i) {
4145       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4146         return false;
4147       if (Mask[i+l] < 0)
4148         continue;
4149       if (MaskVal[i] < 0) {
4150         MaskVal[i] = Mask[i+l] - l;
4151         Imm8 |= MaskVal[i] << (i*2);
4152         continue;
4153       }
4154       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4155         return false;
4156     }
4157   }
4158   return true;
4159 }
4160
4161 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4162 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4163 /// Note that VPERMIL mask matching is different depending whether theunderlying
4164 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4165 /// to the same elements of the low, but to the higher half of the source.
4166 /// In VPERMILPD the two lanes could be shuffled independently of each other
4167 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4168 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4169   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4170   if (VT.getSizeInBits() < 256 || EltSize < 32)
4171     return false;
4172   bool symetricMaskRequired = (EltSize == 32);
4173   unsigned NumElts = VT.getVectorNumElements();
4174
4175   unsigned NumLanes = VT.getSizeInBits()/128;
4176   unsigned LaneSize = NumElts/NumLanes;
4177   // 2 or 4 elements in one lane
4178   
4179   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4180   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4181     for (unsigned i = 0; i != LaneSize; ++i) {
4182       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4183         return false;
4184       if (symetricMaskRequired) {
4185         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4186           ExpectedMaskVal[i] = Mask[i+l] - l;
4187           continue;
4188         }
4189         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4190           return false;
4191       }
4192     }
4193   }
4194   return true;
4195 }
4196
4197 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4198 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4199 /// element of vector 2 and the other elements to come from vector 1 in order.
4200 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4201                                bool V2IsSplat = false, bool V2IsUndef = false) {
4202   if (!VT.is128BitVector())
4203     return false;
4204
4205   unsigned NumOps = VT.getVectorNumElements();
4206   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4207     return false;
4208
4209   if (!isUndefOrEqual(Mask[0], 0))
4210     return false;
4211
4212   for (unsigned i = 1; i != NumOps; ++i)
4213     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4214           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4215           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4216       return false;
4217
4218   return true;
4219 }
4220
4221 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4222 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4223 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4224 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4225                            const X86Subtarget *Subtarget) {
4226   if (!Subtarget->hasSSE3())
4227     return false;
4228
4229   unsigned NumElems = VT.getVectorNumElements();
4230
4231   if ((VT.is128BitVector() && NumElems != 4) ||
4232       (VT.is256BitVector() && NumElems != 8) ||
4233       (VT.is512BitVector() && NumElems != 16))
4234     return false;
4235
4236   // "i+1" is the value the indexed mask element must have
4237   for (unsigned i = 0; i != NumElems; i += 2)
4238     if (!isUndefOrEqual(Mask[i], i+1) ||
4239         !isUndefOrEqual(Mask[i+1], i+1))
4240       return false;
4241
4242   return true;
4243 }
4244
4245 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4246 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4247 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4248 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4249                            const X86Subtarget *Subtarget) {
4250   if (!Subtarget->hasSSE3())
4251     return false;
4252
4253   unsigned NumElems = VT.getVectorNumElements();
4254
4255   if ((VT.is128BitVector() && NumElems != 4) ||
4256       (VT.is256BitVector() && NumElems != 8) ||
4257       (VT.is512BitVector() && NumElems != 16))
4258     return false;
4259
4260   // "i" is the value the indexed mask element must have
4261   for (unsigned i = 0; i != NumElems; i += 2)
4262     if (!isUndefOrEqual(Mask[i], i) ||
4263         !isUndefOrEqual(Mask[i+1], i))
4264       return false;
4265
4266   return true;
4267 }
4268
4269 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4270 /// specifies a shuffle of elements that is suitable for input to 256-bit
4271 /// version of MOVDDUP.
4272 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4273   if (!HasFp256 || !VT.is256BitVector())
4274     return false;
4275
4276   unsigned NumElts = VT.getVectorNumElements();
4277   if (NumElts != 4)
4278     return false;
4279
4280   for (unsigned i = 0; i != NumElts/2; ++i)
4281     if (!isUndefOrEqual(Mask[i], 0))
4282       return false;
4283   for (unsigned i = NumElts/2; i != NumElts; ++i)
4284     if (!isUndefOrEqual(Mask[i], NumElts/2))
4285       return false;
4286   return true;
4287 }
4288
4289 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4290 /// specifies a shuffle of elements that is suitable for input to 128-bit
4291 /// version of MOVDDUP.
4292 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4293   if (!VT.is128BitVector())
4294     return false;
4295
4296   unsigned e = VT.getVectorNumElements() / 2;
4297   for (unsigned i = 0; i != e; ++i)
4298     if (!isUndefOrEqual(Mask[i], i))
4299       return false;
4300   for (unsigned i = 0; i != e; ++i)
4301     if (!isUndefOrEqual(Mask[e+i], i))
4302       return false;
4303   return true;
4304 }
4305
4306 /// isVEXTRACTIndex - Return true if the specified
4307 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4308 /// suitable for instruction that extract 128 or 256 bit vectors
4309 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4310   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4311   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4312     return false;
4313
4314   // The index should be aligned on a vecWidth-bit boundary.
4315   uint64_t Index =
4316     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4317
4318   MVT VT = N->getSimpleValueType(0);
4319   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4320   bool Result = (Index * ElSize) % vecWidth == 0;
4321
4322   return Result;
4323 }
4324
4325 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4326 /// operand specifies a subvector insert that is suitable for input to
4327 /// insertion of 128 or 256-bit subvectors
4328 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4329   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4330   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4331     return false;
4332   // The index should be aligned on a vecWidth-bit boundary.
4333   uint64_t Index =
4334     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4335
4336   MVT VT = N->getSimpleValueType(0);
4337   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4338   bool Result = (Index * ElSize) % vecWidth == 0;
4339
4340   return Result;
4341 }
4342
4343 bool X86::isVINSERT128Index(SDNode *N) {
4344   return isVINSERTIndex(N, 128);
4345 }
4346
4347 bool X86::isVINSERT256Index(SDNode *N) {
4348   return isVINSERTIndex(N, 256);
4349 }
4350
4351 bool X86::isVEXTRACT128Index(SDNode *N) {
4352   return isVEXTRACTIndex(N, 128);
4353 }
4354
4355 bool X86::isVEXTRACT256Index(SDNode *N) {
4356   return isVEXTRACTIndex(N, 256);
4357 }
4358
4359 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4360 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4361 /// Handles 128-bit and 256-bit.
4362 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4363   MVT VT = N->getSimpleValueType(0);
4364
4365   assert((VT.getSizeInBits() >= 128) &&
4366          "Unsupported vector type for PSHUF/SHUFP");
4367
4368   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4369   // independently on 128-bit lanes.
4370   unsigned NumElts = VT.getVectorNumElements();
4371   unsigned NumLanes = VT.getSizeInBits()/128;
4372   unsigned NumLaneElts = NumElts/NumLanes;
4373
4374   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4375          "Only supports 2, 4 or 8 elements per lane");
4376
4377   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4378   unsigned Mask = 0;
4379   for (unsigned i = 0; i != NumElts; ++i) {
4380     int Elt = N->getMaskElt(i);
4381     if (Elt < 0) continue;
4382     Elt &= NumLaneElts - 1;
4383     unsigned ShAmt = (i << Shift) % 8;
4384     Mask |= Elt << ShAmt;
4385   }
4386
4387   return Mask;
4388 }
4389
4390 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4391 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4392 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4393   MVT VT = N->getSimpleValueType(0);
4394
4395   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4396          "Unsupported vector type for PSHUFHW");
4397
4398   unsigned NumElts = VT.getVectorNumElements();
4399
4400   unsigned Mask = 0;
4401   for (unsigned l = 0; l != NumElts; l += 8) {
4402     // 8 nodes per lane, but we only care about the last 4.
4403     for (unsigned i = 0; i < 4; ++i) {
4404       int Elt = N->getMaskElt(l+i+4);
4405       if (Elt < 0) continue;
4406       Elt &= 0x3; // only 2-bits.
4407       Mask |= Elt << (i * 2);
4408     }
4409   }
4410
4411   return Mask;
4412 }
4413
4414 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4415 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4416 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4417   MVT VT = N->getSimpleValueType(0);
4418
4419   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4420          "Unsupported vector type for PSHUFHW");
4421
4422   unsigned NumElts = VT.getVectorNumElements();
4423
4424   unsigned Mask = 0;
4425   for (unsigned l = 0; l != NumElts; l += 8) {
4426     // 8 nodes per lane, but we only care about the first 4.
4427     for (unsigned i = 0; i < 4; ++i) {
4428       int Elt = N->getMaskElt(l+i);
4429       if (Elt < 0) continue;
4430       Elt &= 0x3; // only 2-bits
4431       Mask |= Elt << (i * 2);
4432     }
4433   }
4434
4435   return Mask;
4436 }
4437
4438 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4439 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4440 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4441   MVT VT = SVOp->getSimpleValueType(0);
4442   unsigned EltSize = VT.is512BitVector() ? 1 :
4443     VT.getVectorElementType().getSizeInBits() >> 3;
4444
4445   unsigned NumElts = VT.getVectorNumElements();
4446   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4447   unsigned NumLaneElts = NumElts/NumLanes;
4448
4449   int Val = 0;
4450   unsigned i;
4451   for (i = 0; i != NumElts; ++i) {
4452     Val = SVOp->getMaskElt(i);
4453     if (Val >= 0)
4454       break;
4455   }
4456   if (Val >= (int)NumElts)
4457     Val -= NumElts - NumLaneElts;
4458
4459   assert(Val - i > 0 && "PALIGNR imm should be positive");
4460   return (Val - i) * EltSize;
4461 }
4462
4463 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4464   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4465   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4466     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4467
4468   uint64_t Index =
4469     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4470
4471   MVT VecVT = N->getOperand(0).getSimpleValueType();
4472   MVT ElVT = VecVT.getVectorElementType();
4473
4474   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4475   return Index / NumElemsPerChunk;
4476 }
4477
4478 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4479   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4480   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4481     llvm_unreachable("Illegal insert subvector for VINSERT");
4482
4483   uint64_t Index =
4484     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4485
4486   MVT VecVT = N->getSimpleValueType(0);
4487   MVT ElVT = VecVT.getVectorElementType();
4488
4489   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4490   return Index / NumElemsPerChunk;
4491 }
4492
4493 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4494 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4495 /// and VINSERTI128 instructions.
4496 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4497   return getExtractVEXTRACTImmediate(N, 128);
4498 }
4499
4500 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4501 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4502 /// and VINSERTI64x4 instructions.
4503 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4504   return getExtractVEXTRACTImmediate(N, 256);
4505 }
4506
4507 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4508 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4509 /// and VINSERTI128 instructions.
4510 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4511   return getInsertVINSERTImmediate(N, 128);
4512 }
4513
4514 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4515 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4516 /// and VINSERTI64x4 instructions.
4517 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4518   return getInsertVINSERTImmediate(N, 256);
4519 }
4520
4521 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4522 /// constant +0.0.
4523 bool X86::isZeroNode(SDValue Elt) {
4524   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4525     return CN->isNullValue();
4526   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4527     return CFP->getValueAPF().isPosZero();
4528   return false;
4529 }
4530
4531 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4532 /// their permute mask.
4533 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4534                                     SelectionDAG &DAG) {
4535   MVT VT = SVOp->getSimpleValueType(0);
4536   unsigned NumElems = VT.getVectorNumElements();
4537   SmallVector<int, 8> MaskVec;
4538
4539   for (unsigned i = 0; i != NumElems; ++i) {
4540     int Idx = SVOp->getMaskElt(i);
4541     if (Idx >= 0) {
4542       if (Idx < (int)NumElems)
4543         Idx += NumElems;
4544       else
4545         Idx -= NumElems;
4546     }
4547     MaskVec.push_back(Idx);
4548   }
4549   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4550                               SVOp->getOperand(0), &MaskVec[0]);
4551 }
4552
4553 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4554 /// match movhlps. The lower half elements should come from upper half of
4555 /// V1 (and in order), and the upper half elements should come from the upper
4556 /// half of V2 (and in order).
4557 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4558   if (!VT.is128BitVector())
4559     return false;
4560   if (VT.getVectorNumElements() != 4)
4561     return false;
4562   for (unsigned i = 0, e = 2; i != e; ++i)
4563     if (!isUndefOrEqual(Mask[i], i+2))
4564       return false;
4565   for (unsigned i = 2; i != 4; ++i)
4566     if (!isUndefOrEqual(Mask[i], i+4))
4567       return false;
4568   return true;
4569 }
4570
4571 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4572 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4573 /// required.
4574 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4575   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4576     return false;
4577   N = N->getOperand(0).getNode();
4578   if (!ISD::isNON_EXTLoad(N))
4579     return false;
4580   if (LD)
4581     *LD = cast<LoadSDNode>(N);
4582   return true;
4583 }
4584
4585 // Test whether the given value is a vector value which will be legalized
4586 // into a load.
4587 static bool WillBeConstantPoolLoad(SDNode *N) {
4588   if (N->getOpcode() != ISD::BUILD_VECTOR)
4589     return false;
4590
4591   // Check for any non-constant elements.
4592   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4593     switch (N->getOperand(i).getNode()->getOpcode()) {
4594     case ISD::UNDEF:
4595     case ISD::ConstantFP:
4596     case ISD::Constant:
4597       break;
4598     default:
4599       return false;
4600     }
4601
4602   // Vectors of all-zeros and all-ones are materialized with special
4603   // instructions rather than being loaded.
4604   return !ISD::isBuildVectorAllZeros(N) &&
4605          !ISD::isBuildVectorAllOnes(N);
4606 }
4607
4608 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4609 /// match movlp{s|d}. The lower half elements should come from lower half of
4610 /// V1 (and in order), and the upper half elements should come from the upper
4611 /// half of V2 (and in order). And since V1 will become the source of the
4612 /// MOVLP, it must be either a vector load or a scalar load to vector.
4613 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4614                                ArrayRef<int> Mask, MVT VT) {
4615   if (!VT.is128BitVector())
4616     return false;
4617
4618   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4619     return false;
4620   // Is V2 is a vector load, don't do this transformation. We will try to use
4621   // load folding shufps op.
4622   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4623     return false;
4624
4625   unsigned NumElems = VT.getVectorNumElements();
4626
4627   if (NumElems != 2 && NumElems != 4)
4628     return false;
4629   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4630     if (!isUndefOrEqual(Mask[i], i))
4631       return false;
4632   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4633     if (!isUndefOrEqual(Mask[i], i+NumElems))
4634       return false;
4635   return true;
4636 }
4637
4638 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4639 /// all the same.
4640 static bool isSplatVector(SDNode *N) {
4641   if (N->getOpcode() != ISD::BUILD_VECTOR)
4642     return false;
4643
4644   SDValue SplatValue = N->getOperand(0);
4645   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4646     if (N->getOperand(i) != SplatValue)
4647       return false;
4648   return true;
4649 }
4650
4651 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4652 /// to an zero vector.
4653 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4654 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4655   SDValue V1 = N->getOperand(0);
4656   SDValue V2 = N->getOperand(1);
4657   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4658   for (unsigned i = 0; i != NumElems; ++i) {
4659     int Idx = N->getMaskElt(i);
4660     if (Idx >= (int)NumElems) {
4661       unsigned Opc = V2.getOpcode();
4662       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4663         continue;
4664       if (Opc != ISD::BUILD_VECTOR ||
4665           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4666         return false;
4667     } else if (Idx >= 0) {
4668       unsigned Opc = V1.getOpcode();
4669       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4670         continue;
4671       if (Opc != ISD::BUILD_VECTOR ||
4672           !X86::isZeroNode(V1.getOperand(Idx)))
4673         return false;
4674     }
4675   }
4676   return true;
4677 }
4678
4679 /// getZeroVector - Returns a vector of specified type with all zero elements.
4680 ///
4681 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4682                              SelectionDAG &DAG, SDLoc dl) {
4683   assert(VT.isVector() && "Expected a vector type");
4684
4685   // Always build SSE zero vectors as <4 x i32> bitcasted
4686   // to their dest type. This ensures they get CSE'd.
4687   SDValue Vec;
4688   if (VT.is128BitVector()) {  // SSE
4689     if (Subtarget->hasSSE2()) {  // SSE2
4690       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4691       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4692     } else { // SSE1
4693       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4694       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4695     }
4696   } else if (VT.is256BitVector()) { // AVX
4697     if (Subtarget->hasInt256()) { // AVX2
4698       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4699       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4700       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4701                         array_lengthof(Ops));
4702     } else {
4703       // 256-bit logic and arithmetic instructions in AVX are all
4704       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4705       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4706       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4707       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4708                         array_lengthof(Ops));
4709     }
4710   } else if (VT.is512BitVector()) { // AVX-512
4711       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4712       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4713                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4714       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4715   } else
4716     llvm_unreachable("Unexpected vector type");
4717
4718   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4719 }
4720
4721 /// getOnesVector - Returns a vector of specified type with all bits set.
4722 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4723 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4724 /// Then bitcast to their original type, ensuring they get CSE'd.
4725 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4726                              SDLoc dl) {
4727   assert(VT.isVector() && "Expected a vector type");
4728
4729   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4730   SDValue Vec;
4731   if (VT.is256BitVector()) {
4732     if (HasInt256) { // AVX2
4733       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4734       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4735                         array_lengthof(Ops));
4736     } else { // AVX
4737       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4738       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4739     }
4740   } else if (VT.is128BitVector()) {
4741     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4742   } else
4743     llvm_unreachable("Unexpected vector type");
4744
4745   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4746 }
4747
4748 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4749 /// that point to V2 points to its first element.
4750 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4751   for (unsigned i = 0; i != NumElems; ++i) {
4752     if (Mask[i] > (int)NumElems) {
4753       Mask[i] = NumElems;
4754     }
4755   }
4756 }
4757
4758 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4759 /// operation of specified width.
4760 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4761                        SDValue V2) {
4762   unsigned NumElems = VT.getVectorNumElements();
4763   SmallVector<int, 8> Mask;
4764   Mask.push_back(NumElems);
4765   for (unsigned i = 1; i != NumElems; ++i)
4766     Mask.push_back(i);
4767   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4768 }
4769
4770 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4771 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4772                           SDValue V2) {
4773   unsigned NumElems = VT.getVectorNumElements();
4774   SmallVector<int, 8> Mask;
4775   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4776     Mask.push_back(i);
4777     Mask.push_back(i + NumElems);
4778   }
4779   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4780 }
4781
4782 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4783 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4784                           SDValue V2) {
4785   unsigned NumElems = VT.getVectorNumElements();
4786   SmallVector<int, 8> Mask;
4787   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4788     Mask.push_back(i + Half);
4789     Mask.push_back(i + NumElems + Half);
4790   }
4791   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4792 }
4793
4794 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4795 // a generic shuffle instruction because the target has no such instructions.
4796 // Generate shuffles which repeat i16 and i8 several times until they can be
4797 // represented by v4f32 and then be manipulated by target suported shuffles.
4798 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4799   MVT VT = V.getSimpleValueType();
4800   int NumElems = VT.getVectorNumElements();
4801   SDLoc dl(V);
4802
4803   while (NumElems > 4) {
4804     if (EltNo < NumElems/2) {
4805       V = getUnpackl(DAG, dl, VT, V, V);
4806     } else {
4807       V = getUnpackh(DAG, dl, VT, V, V);
4808       EltNo -= NumElems/2;
4809     }
4810     NumElems >>= 1;
4811   }
4812   return V;
4813 }
4814
4815 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4816 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4817   MVT VT = V.getSimpleValueType();
4818   SDLoc dl(V);
4819
4820   if (VT.is128BitVector()) {
4821     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4822     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4823     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4824                              &SplatMask[0]);
4825   } else if (VT.is256BitVector()) {
4826     // To use VPERMILPS to splat scalars, the second half of indicies must
4827     // refer to the higher part, which is a duplication of the lower one,
4828     // because VPERMILPS can only handle in-lane permutations.
4829     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4830                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4831
4832     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4833     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4834                              &SplatMask[0]);
4835   } else
4836     llvm_unreachable("Vector size not supported");
4837
4838   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4839 }
4840
4841 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4842 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4843   MVT SrcVT = SV->getSimpleValueType(0);
4844   SDValue V1 = SV->getOperand(0);
4845   SDLoc dl(SV);
4846
4847   int EltNo = SV->getSplatIndex();
4848   int NumElems = SrcVT.getVectorNumElements();
4849   bool Is256BitVec = SrcVT.is256BitVector();
4850
4851   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4852          "Unknown how to promote splat for type");
4853
4854   // Extract the 128-bit part containing the splat element and update
4855   // the splat element index when it refers to the higher register.
4856   if (Is256BitVec) {
4857     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4858     if (EltNo >= NumElems/2)
4859       EltNo -= NumElems/2;
4860   }
4861
4862   // All i16 and i8 vector types can't be used directly by a generic shuffle
4863   // instruction because the target has no such instruction. Generate shuffles
4864   // which repeat i16 and i8 several times until they fit in i32, and then can
4865   // be manipulated by target suported shuffles.
4866   MVT EltVT = SrcVT.getVectorElementType();
4867   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4868     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4869
4870   // Recreate the 256-bit vector and place the same 128-bit vector
4871   // into the low and high part. This is necessary because we want
4872   // to use VPERM* to shuffle the vectors
4873   if (Is256BitVec) {
4874     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4875   }
4876
4877   return getLegalSplat(DAG, V1, EltNo);
4878 }
4879
4880 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4881 /// vector of zero or undef vector.  This produces a shuffle where the low
4882 /// element of V2 is swizzled into the zero/undef vector, landing at element
4883 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4884 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4885                                            bool IsZero,
4886                                            const X86Subtarget *Subtarget,
4887                                            SelectionDAG &DAG) {
4888   MVT VT = V2.getSimpleValueType();
4889   SDValue V1 = IsZero
4890     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4891   unsigned NumElems = VT.getVectorNumElements();
4892   SmallVector<int, 16> MaskVec;
4893   for (unsigned i = 0; i != NumElems; ++i)
4894     // If this is the insertion idx, put the low elt of V2 here.
4895     MaskVec.push_back(i == Idx ? NumElems : i);
4896   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4897 }
4898
4899 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4900 /// target specific opcode. Returns true if the Mask could be calculated.
4901 /// Sets IsUnary to true if only uses one source.
4902 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4903                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4904   unsigned NumElems = VT.getVectorNumElements();
4905   SDValue ImmN;
4906
4907   IsUnary = false;
4908   switch(N->getOpcode()) {
4909   case X86ISD::SHUFP:
4910     ImmN = N->getOperand(N->getNumOperands()-1);
4911     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4912     break;
4913   case X86ISD::UNPCKH:
4914     DecodeUNPCKHMask(VT, Mask);
4915     break;
4916   case X86ISD::UNPCKL:
4917     DecodeUNPCKLMask(VT, Mask);
4918     break;
4919   case X86ISD::MOVHLPS:
4920     DecodeMOVHLPSMask(NumElems, Mask);
4921     break;
4922   case X86ISD::MOVLHPS:
4923     DecodeMOVLHPSMask(NumElems, Mask);
4924     break;
4925   case X86ISD::PALIGNR:
4926     ImmN = N->getOperand(N->getNumOperands()-1);
4927     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4928     break;
4929   case X86ISD::PSHUFD:
4930   case X86ISD::VPERMILP:
4931     ImmN = N->getOperand(N->getNumOperands()-1);
4932     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4933     IsUnary = true;
4934     break;
4935   case X86ISD::PSHUFHW:
4936     ImmN = N->getOperand(N->getNumOperands()-1);
4937     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4938     IsUnary = true;
4939     break;
4940   case X86ISD::PSHUFLW:
4941     ImmN = N->getOperand(N->getNumOperands()-1);
4942     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4943     IsUnary = true;
4944     break;
4945   case X86ISD::VPERMI:
4946     ImmN = N->getOperand(N->getNumOperands()-1);
4947     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4948     IsUnary = true;
4949     break;
4950   case X86ISD::MOVSS:
4951   case X86ISD::MOVSD: {
4952     // The index 0 always comes from the first element of the second source,
4953     // this is why MOVSS and MOVSD are used in the first place. The other
4954     // elements come from the other positions of the first source vector
4955     Mask.push_back(NumElems);
4956     for (unsigned i = 1; i != NumElems; ++i) {
4957       Mask.push_back(i);
4958     }
4959     break;
4960   }
4961   case X86ISD::VPERM2X128:
4962     ImmN = N->getOperand(N->getNumOperands()-1);
4963     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4964     if (Mask.empty()) return false;
4965     break;
4966   case X86ISD::MOVDDUP:
4967   case X86ISD::MOVLHPD:
4968   case X86ISD::MOVLPD:
4969   case X86ISD::MOVLPS:
4970   case X86ISD::MOVSHDUP:
4971   case X86ISD::MOVSLDUP:
4972     // Not yet implemented
4973     return false;
4974   default: llvm_unreachable("unknown target shuffle node");
4975   }
4976
4977   return true;
4978 }
4979
4980 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4981 /// element of the result of the vector shuffle.
4982 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4983                                    unsigned Depth) {
4984   if (Depth == 6)
4985     return SDValue();  // Limit search depth.
4986
4987   SDValue V = SDValue(N, 0);
4988   EVT VT = V.getValueType();
4989   unsigned Opcode = V.getOpcode();
4990
4991   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4992   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4993     int Elt = SV->getMaskElt(Index);
4994
4995     if (Elt < 0)
4996       return DAG.getUNDEF(VT.getVectorElementType());
4997
4998     unsigned NumElems = VT.getVectorNumElements();
4999     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5000                                          : SV->getOperand(1);
5001     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5002   }
5003
5004   // Recurse into target specific vector shuffles to find scalars.
5005   if (isTargetShuffle(Opcode)) {
5006     MVT ShufVT = V.getSimpleValueType();
5007     unsigned NumElems = ShufVT.getVectorNumElements();
5008     SmallVector<int, 16> ShuffleMask;
5009     bool IsUnary;
5010
5011     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5012       return SDValue();
5013
5014     int Elt = ShuffleMask[Index];
5015     if (Elt < 0)
5016       return DAG.getUNDEF(ShufVT.getVectorElementType());
5017
5018     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5019                                          : N->getOperand(1);
5020     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5021                                Depth+1);
5022   }
5023
5024   // Actual nodes that may contain scalar elements
5025   if (Opcode == ISD::BITCAST) {
5026     V = V.getOperand(0);
5027     EVT SrcVT = V.getValueType();
5028     unsigned NumElems = VT.getVectorNumElements();
5029
5030     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5031       return SDValue();
5032   }
5033
5034   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5035     return (Index == 0) ? V.getOperand(0)
5036                         : DAG.getUNDEF(VT.getVectorElementType());
5037
5038   if (V.getOpcode() == ISD::BUILD_VECTOR)
5039     return V.getOperand(Index);
5040
5041   return SDValue();
5042 }
5043
5044 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5045 /// shuffle operation which come from a consecutively from a zero. The
5046 /// search can start in two different directions, from left or right.
5047 /// We count undefs as zeros until PreferredNum is reached.
5048 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5049                                          unsigned NumElems, bool ZerosFromLeft,
5050                                          SelectionDAG &DAG,
5051                                          unsigned PreferredNum = -1U) {
5052   unsigned NumZeros = 0;
5053   for (unsigned i = 0; i != NumElems; ++i) {
5054     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5055     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5056     if (!Elt.getNode())
5057       break;
5058
5059     if (X86::isZeroNode(Elt))
5060       ++NumZeros;
5061     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5062       NumZeros = std::min(NumZeros + 1, PreferredNum);
5063     else
5064       break;
5065   }
5066
5067   return NumZeros;
5068 }
5069
5070 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5071 /// correspond consecutively to elements from one of the vector operands,
5072 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5073 static
5074 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5075                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5076                               unsigned NumElems, unsigned &OpNum) {
5077   bool SeenV1 = false;
5078   bool SeenV2 = false;
5079
5080   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5081     int Idx = SVOp->getMaskElt(i);
5082     // Ignore undef indicies
5083     if (Idx < 0)
5084       continue;
5085
5086     if (Idx < (int)NumElems)
5087       SeenV1 = true;
5088     else
5089       SeenV2 = true;
5090
5091     // Only accept consecutive elements from the same vector
5092     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5093       return false;
5094   }
5095
5096   OpNum = SeenV1 ? 0 : 1;
5097   return true;
5098 }
5099
5100 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5101 /// logical left shift of a vector.
5102 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5103                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5104   unsigned NumElems =
5105     SVOp->getSimpleValueType(0).getVectorNumElements();
5106   unsigned NumZeros = getNumOfConsecutiveZeros(
5107       SVOp, NumElems, false /* check zeros from right */, DAG,
5108       SVOp->getMaskElt(0));
5109   unsigned OpSrc;
5110
5111   if (!NumZeros)
5112     return false;
5113
5114   // Considering the elements in the mask that are not consecutive zeros,
5115   // check if they consecutively come from only one of the source vectors.
5116   //
5117   //               V1 = {X, A, B, C}     0
5118   //                         \  \  \    /
5119   //   vector_shuffle V1, V2 <1, 2, 3, X>
5120   //
5121   if (!isShuffleMaskConsecutive(SVOp,
5122             0,                   // Mask Start Index
5123             NumElems-NumZeros,   // Mask End Index(exclusive)
5124             NumZeros,            // Where to start looking in the src vector
5125             NumElems,            // Number of elements in vector
5126             OpSrc))              // Which source operand ?
5127     return false;
5128
5129   isLeft = false;
5130   ShAmt = NumZeros;
5131   ShVal = SVOp->getOperand(OpSrc);
5132   return true;
5133 }
5134
5135 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5136 /// logical left shift of a vector.
5137 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5138                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5139   unsigned NumElems =
5140     SVOp->getSimpleValueType(0).getVectorNumElements();
5141   unsigned NumZeros = getNumOfConsecutiveZeros(
5142       SVOp, NumElems, true /* check zeros from left */, DAG,
5143       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5144   unsigned OpSrc;
5145
5146   if (!NumZeros)
5147     return false;
5148
5149   // Considering the elements in the mask that are not consecutive zeros,
5150   // check if they consecutively come from only one of the source vectors.
5151   //
5152   //                           0    { A, B, X, X } = V2
5153   //                          / \    /  /
5154   //   vector_shuffle V1, V2 <X, X, 4, 5>
5155   //
5156   if (!isShuffleMaskConsecutive(SVOp,
5157             NumZeros,     // Mask Start Index
5158             NumElems,     // Mask End Index(exclusive)
5159             0,            // Where to start looking in the src vector
5160             NumElems,     // Number of elements in vector
5161             OpSrc))       // Which source operand ?
5162     return false;
5163
5164   isLeft = true;
5165   ShAmt = NumZeros;
5166   ShVal = SVOp->getOperand(OpSrc);
5167   return true;
5168 }
5169
5170 /// isVectorShift - Returns true if the shuffle can be implemented as a
5171 /// logical left or right shift of a vector.
5172 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5173                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5174   // Although the logic below support any bitwidth size, there are no
5175   // shift instructions which handle more than 128-bit vectors.
5176   if (!SVOp->getSimpleValueType(0).is128BitVector())
5177     return false;
5178
5179   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5180       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5181     return true;
5182
5183   return false;
5184 }
5185
5186 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5187 ///
5188 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5189                                        unsigned NumNonZero, unsigned NumZero,
5190                                        SelectionDAG &DAG,
5191                                        const X86Subtarget* Subtarget,
5192                                        const TargetLowering &TLI) {
5193   if (NumNonZero > 8)
5194     return SDValue();
5195
5196   SDLoc dl(Op);
5197   SDValue V(0, 0);
5198   bool First = true;
5199   for (unsigned i = 0; i < 16; ++i) {
5200     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5201     if (ThisIsNonZero && First) {
5202       if (NumZero)
5203         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5204       else
5205         V = DAG.getUNDEF(MVT::v8i16);
5206       First = false;
5207     }
5208
5209     if ((i & 1) != 0) {
5210       SDValue ThisElt(0, 0), LastElt(0, 0);
5211       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5212       if (LastIsNonZero) {
5213         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5214                               MVT::i16, Op.getOperand(i-1));
5215       }
5216       if (ThisIsNonZero) {
5217         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5218         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5219                               ThisElt, DAG.getConstant(8, MVT::i8));
5220         if (LastIsNonZero)
5221           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5222       } else
5223         ThisElt = LastElt;
5224
5225       if (ThisElt.getNode())
5226         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5227                         DAG.getIntPtrConstant(i/2));
5228     }
5229   }
5230
5231   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5232 }
5233
5234 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5235 ///
5236 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5237                                      unsigned NumNonZero, unsigned NumZero,
5238                                      SelectionDAG &DAG,
5239                                      const X86Subtarget* Subtarget,
5240                                      const TargetLowering &TLI) {
5241   if (NumNonZero > 4)
5242     return SDValue();
5243
5244   SDLoc dl(Op);
5245   SDValue V(0, 0);
5246   bool First = true;
5247   for (unsigned i = 0; i < 8; ++i) {
5248     bool isNonZero = (NonZeros & (1 << i)) != 0;
5249     if (isNonZero) {
5250       if (First) {
5251         if (NumZero)
5252           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5253         else
5254           V = DAG.getUNDEF(MVT::v8i16);
5255         First = false;
5256       }
5257       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5258                       MVT::v8i16, V, Op.getOperand(i),
5259                       DAG.getIntPtrConstant(i));
5260     }
5261   }
5262
5263   return V;
5264 }
5265
5266 /// getVShift - Return a vector logical shift node.
5267 ///
5268 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5269                          unsigned NumBits, SelectionDAG &DAG,
5270                          const TargetLowering &TLI, SDLoc dl) {
5271   assert(VT.is128BitVector() && "Unknown type for VShift");
5272   EVT ShVT = MVT::v2i64;
5273   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5274   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5275   return DAG.getNode(ISD::BITCAST, dl, VT,
5276                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5277                              DAG.getConstant(NumBits,
5278                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5279 }
5280
5281 static SDValue
5282 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5283
5284   // Check if the scalar load can be widened into a vector load. And if
5285   // the address is "base + cst" see if the cst can be "absorbed" into
5286   // the shuffle mask.
5287   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5288     SDValue Ptr = LD->getBasePtr();
5289     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5290       return SDValue();
5291     EVT PVT = LD->getValueType(0);
5292     if (PVT != MVT::i32 && PVT != MVT::f32)
5293       return SDValue();
5294
5295     int FI = -1;
5296     int64_t Offset = 0;
5297     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5298       FI = FINode->getIndex();
5299       Offset = 0;
5300     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5301                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5302       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5303       Offset = Ptr.getConstantOperandVal(1);
5304       Ptr = Ptr.getOperand(0);
5305     } else {
5306       return SDValue();
5307     }
5308
5309     // FIXME: 256-bit vector instructions don't require a strict alignment,
5310     // improve this code to support it better.
5311     unsigned RequiredAlign = VT.getSizeInBits()/8;
5312     SDValue Chain = LD->getChain();
5313     // Make sure the stack object alignment is at least 16 or 32.
5314     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5315     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5316       if (MFI->isFixedObjectIndex(FI)) {
5317         // Can't change the alignment. FIXME: It's possible to compute
5318         // the exact stack offset and reference FI + adjust offset instead.
5319         // If someone *really* cares about this. That's the way to implement it.
5320         return SDValue();
5321       } else {
5322         MFI->setObjectAlignment(FI, RequiredAlign);
5323       }
5324     }
5325
5326     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5327     // Ptr + (Offset & ~15).
5328     if (Offset < 0)
5329       return SDValue();
5330     if ((Offset % RequiredAlign) & 3)
5331       return SDValue();
5332     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5333     if (StartOffset)
5334       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5335                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5336
5337     int EltNo = (Offset - StartOffset) >> 2;
5338     unsigned NumElems = VT.getVectorNumElements();
5339
5340     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5341     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5342                              LD->getPointerInfo().getWithOffset(StartOffset),
5343                              false, false, false, 0);
5344
5345     SmallVector<int, 8> Mask;
5346     for (unsigned i = 0; i != NumElems; ++i)
5347       Mask.push_back(EltNo);
5348
5349     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5350   }
5351
5352   return SDValue();
5353 }
5354
5355 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5356 /// vector of type 'VT', see if the elements can be replaced by a single large
5357 /// load which has the same value as a build_vector whose operands are 'elts'.
5358 ///
5359 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5360 ///
5361 /// FIXME: we'd also like to handle the case where the last elements are zero
5362 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5363 /// There's even a handy isZeroNode for that purpose.
5364 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5365                                         SDLoc &DL, SelectionDAG &DAG) {
5366   EVT EltVT = VT.getVectorElementType();
5367   unsigned NumElems = Elts.size();
5368
5369   LoadSDNode *LDBase = NULL;
5370   unsigned LastLoadedElt = -1U;
5371
5372   // For each element in the initializer, see if we've found a load or an undef.
5373   // If we don't find an initial load element, or later load elements are
5374   // non-consecutive, bail out.
5375   for (unsigned i = 0; i < NumElems; ++i) {
5376     SDValue Elt = Elts[i];
5377
5378     if (!Elt.getNode() ||
5379         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5380       return SDValue();
5381     if (!LDBase) {
5382       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5383         return SDValue();
5384       LDBase = cast<LoadSDNode>(Elt.getNode());
5385       LastLoadedElt = i;
5386       continue;
5387     }
5388     if (Elt.getOpcode() == ISD::UNDEF)
5389       continue;
5390
5391     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5392     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5393       return SDValue();
5394     LastLoadedElt = i;
5395   }
5396
5397   // If we have found an entire vector of loads and undefs, then return a large
5398   // load of the entire vector width starting at the base pointer.  If we found
5399   // consecutive loads for the low half, generate a vzext_load node.
5400   if (LastLoadedElt == NumElems - 1) {
5401     SDValue NewLd = SDValue();
5402     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5403       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5404                           LDBase->getPointerInfo(),
5405                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5406                           LDBase->isInvariant(), 0);
5407     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5408                         LDBase->getPointerInfo(),
5409                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5410                         LDBase->isInvariant(), LDBase->getAlignment());
5411
5412     if (LDBase->hasAnyUseOfValue(1)) {
5413       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5414                                      SDValue(LDBase, 1),
5415                                      SDValue(NewLd.getNode(), 1));
5416       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5417       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5418                              SDValue(NewLd.getNode(), 1));
5419     }
5420
5421     return NewLd;
5422   }
5423   if (NumElems == 4 && LastLoadedElt == 1 &&
5424       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5425     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5426     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5427     SDValue ResNode =
5428         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5429                                 array_lengthof(Ops), MVT::i64,
5430                                 LDBase->getPointerInfo(),
5431                                 LDBase->getAlignment(),
5432                                 false/*isVolatile*/, true/*ReadMem*/,
5433                                 false/*WriteMem*/);
5434
5435     // Make sure the newly-created LOAD is in the same position as LDBase in
5436     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5437     // update uses of LDBase's output chain to use the TokenFactor.
5438     if (LDBase->hasAnyUseOfValue(1)) {
5439       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5440                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5441       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5442       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5443                              SDValue(ResNode.getNode(), 1));
5444     }
5445
5446     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5447   }
5448   return SDValue();
5449 }
5450
5451 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5452 /// to generate a splat value for the following cases:
5453 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5454 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5455 /// a scalar load, or a constant.
5456 /// The VBROADCAST node is returned when a pattern is found,
5457 /// or SDValue() otherwise.
5458 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5459                                     SelectionDAG &DAG) {
5460   if (!Subtarget->hasFp256())
5461     return SDValue();
5462
5463   MVT VT = Op.getSimpleValueType();
5464   SDLoc dl(Op);
5465
5466   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5467          "Unsupported vector type for broadcast.");
5468
5469   SDValue Ld;
5470   bool ConstSplatVal;
5471
5472   switch (Op.getOpcode()) {
5473     default:
5474       // Unknown pattern found.
5475       return SDValue();
5476
5477     case ISD::BUILD_VECTOR: {
5478       // The BUILD_VECTOR node must be a splat.
5479       if (!isSplatVector(Op.getNode()))
5480         return SDValue();
5481
5482       Ld = Op.getOperand(0);
5483       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5484                      Ld.getOpcode() == ISD::ConstantFP);
5485
5486       // The suspected load node has several users. Make sure that all
5487       // of its users are from the BUILD_VECTOR node.
5488       // Constants may have multiple users.
5489       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5490         return SDValue();
5491       break;
5492     }
5493
5494     case ISD::VECTOR_SHUFFLE: {
5495       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5496
5497       // Shuffles must have a splat mask where the first element is
5498       // broadcasted.
5499       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5500         return SDValue();
5501
5502       SDValue Sc = Op.getOperand(0);
5503       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5504           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5505
5506         if (!Subtarget->hasInt256())
5507           return SDValue();
5508
5509         // Use the register form of the broadcast instruction available on AVX2.
5510         if (VT.getSizeInBits() >= 256)
5511           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5512         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5513       }
5514
5515       Ld = Sc.getOperand(0);
5516       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5517                        Ld.getOpcode() == ISD::ConstantFP);
5518
5519       // The scalar_to_vector node and the suspected
5520       // load node must have exactly one user.
5521       // Constants may have multiple users.
5522
5523       // AVX-512 has register version of the broadcast
5524       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5525         Ld.getValueType().getSizeInBits() >= 32;
5526       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5527           !hasRegVer))
5528         return SDValue();
5529       break;
5530     }
5531   }
5532
5533   bool IsGE256 = (VT.getSizeInBits() >= 256);
5534
5535   // Handle the broadcasting a single constant scalar from the constant pool
5536   // into a vector. On Sandybridge it is still better to load a constant vector
5537   // from the constant pool and not to broadcast it from a scalar.
5538   if (ConstSplatVal && Subtarget->hasInt256()) {
5539     EVT CVT = Ld.getValueType();
5540     assert(!CVT.isVector() && "Must not broadcast a vector type");
5541     unsigned ScalarSize = CVT.getSizeInBits();
5542
5543     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5544       const Constant *C = 0;
5545       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5546         C = CI->getConstantIntValue();
5547       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5548         C = CF->getConstantFPValue();
5549
5550       assert(C && "Invalid constant type");
5551
5552       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5553       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5554       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5555       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5556                        MachinePointerInfo::getConstantPool(),
5557                        false, false, false, Alignment);
5558
5559       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5560     }
5561   }
5562
5563   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5564   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5565
5566   // Handle AVX2 in-register broadcasts.
5567   if (!IsLoad && Subtarget->hasInt256() &&
5568       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5569     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5570
5571   // The scalar source must be a normal load.
5572   if (!IsLoad)
5573     return SDValue();
5574
5575   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5576     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5577
5578   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5579   // double since there is no vbroadcastsd xmm
5580   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5581     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5582       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5583   }
5584
5585   // Unsupported broadcast.
5586   return SDValue();
5587 }
5588
5589 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5590   MVT VT = Op.getSimpleValueType();
5591
5592   // Skip if insert_vec_elt is not supported.
5593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5594   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5595     return SDValue();
5596
5597   SDLoc DL(Op);
5598   unsigned NumElems = Op.getNumOperands();
5599
5600   SDValue VecIn1;
5601   SDValue VecIn2;
5602   SmallVector<unsigned, 4> InsertIndices;
5603   SmallVector<int, 8> Mask(NumElems, -1);
5604
5605   for (unsigned i = 0; i != NumElems; ++i) {
5606     unsigned Opc = Op.getOperand(i).getOpcode();
5607
5608     if (Opc == ISD::UNDEF)
5609       continue;
5610
5611     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5612       // Quit if more than 1 elements need inserting.
5613       if (InsertIndices.size() > 1)
5614         return SDValue();
5615
5616       InsertIndices.push_back(i);
5617       continue;
5618     }
5619
5620     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5621     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5622
5623     // Quit if extracted from vector of different type.
5624     if (ExtractedFromVec.getValueType() != VT)
5625       return SDValue();
5626
5627     // Quit if non-constant index.
5628     if (!isa<ConstantSDNode>(ExtIdx))
5629       return SDValue();
5630
5631     if (VecIn1.getNode() == 0)
5632       VecIn1 = ExtractedFromVec;
5633     else if (VecIn1 != ExtractedFromVec) {
5634       if (VecIn2.getNode() == 0)
5635         VecIn2 = ExtractedFromVec;
5636       else if (VecIn2 != ExtractedFromVec)
5637         // Quit if more than 2 vectors to shuffle
5638         return SDValue();
5639     }
5640
5641     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5642
5643     if (ExtractedFromVec == VecIn1)
5644       Mask[i] = Idx;
5645     else if (ExtractedFromVec == VecIn2)
5646       Mask[i] = Idx + NumElems;
5647   }
5648
5649   if (VecIn1.getNode() == 0)
5650     return SDValue();
5651
5652   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5653   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5654   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5655     unsigned Idx = InsertIndices[i];
5656     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5657                      DAG.getIntPtrConstant(Idx));
5658   }
5659
5660   return NV;
5661 }
5662
5663 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5664 SDValue
5665 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5666
5667   MVT VT = Op.getSimpleValueType();
5668   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5669          "Unexpected type in LowerBUILD_VECTORvXi1!");
5670
5671   SDLoc dl(Op);
5672   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5673     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5674     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5675                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5676     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5677                        Ops, VT.getVectorNumElements());
5678   }
5679
5680   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5681     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5682     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5683                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5684     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5685                        Ops, VT.getVectorNumElements());
5686   }
5687
5688   bool AllContants = true;
5689   uint64_t Immediate = 0;
5690   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5691     SDValue In = Op.getOperand(idx);
5692     if (In.getOpcode() == ISD::UNDEF)
5693       continue;
5694     if (!isa<ConstantSDNode>(In)) {
5695       AllContants = false;
5696       break;
5697     }
5698     if (cast<ConstantSDNode>(In)->getZExtValue())
5699       Immediate |= (1ULL << idx);
5700   }
5701
5702   if (AllContants) {
5703     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5704       DAG.getConstant(Immediate, MVT::i16));
5705     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5706                        DAG.getIntPtrConstant(0));
5707   }
5708
5709   // Splat vector (with undefs)
5710   SDValue In = Op.getOperand(0);
5711   for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5712     if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5713       llvm_unreachable("Unsupported predicate operation");
5714   }
5715
5716   SDValue EFLAGS, X86CC;
5717   if (In.getOpcode() == ISD::SETCC) {
5718     SDValue Op0 = In.getOperand(0);
5719     SDValue Op1 = In.getOperand(1);
5720     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5721     bool isFP = Op1.getValueType().isFloatingPoint();
5722     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5723
5724     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5725
5726     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5727     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5728     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5729   } else if (In.getOpcode() == X86ISD::SETCC) {
5730     X86CC = In.getOperand(0);
5731     EFLAGS = In.getOperand(1);
5732   } else {
5733     // The algorithm:
5734     //   Bit1 = In & 0x1
5735     //   if (Bit1 != 0)
5736     //     ZF = 0
5737     //   else
5738     //     ZF = 1
5739     //   if (ZF == 0)
5740     //     res = allOnes ### CMOVNE -1, %res
5741     //   else
5742     //     res = allZero
5743     MVT InVT = In.getSimpleValueType();
5744     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5745     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5746     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5747   }
5748
5749   if (VT == MVT::v16i1) {
5750     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5751     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5752     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5753           Cst0, Cst1, X86CC, EFLAGS);
5754     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5755   }
5756
5757   if (VT == MVT::v8i1) {
5758     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5759     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5760     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5761           Cst0, Cst1, X86CC, EFLAGS);
5762     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5763     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5764   }
5765   llvm_unreachable("Unsupported predicate operation");
5766 }
5767
5768 SDValue
5769 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5770   SDLoc dl(Op);
5771
5772   MVT VT = Op.getSimpleValueType();
5773   MVT ExtVT = VT.getVectorElementType();
5774   unsigned NumElems = Op.getNumOperands();
5775
5776   // Generate vectors for predicate vectors.
5777   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5778     return LowerBUILD_VECTORvXi1(Op, DAG);
5779
5780   // Vectors containing all zeros can be matched by pxor and xorps later
5781   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5782     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5783     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5784     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5785       return Op;
5786
5787     return getZeroVector(VT, Subtarget, DAG, dl);
5788   }
5789
5790   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5791   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5792   // vpcmpeqd on 256-bit vectors.
5793   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5794     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5795       return Op;
5796
5797     if (!VT.is512BitVector())
5798       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5799   }
5800
5801   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5802   if (Broadcast.getNode())
5803     return Broadcast;
5804
5805   unsigned EVTBits = ExtVT.getSizeInBits();
5806
5807   unsigned NumZero  = 0;
5808   unsigned NumNonZero = 0;
5809   unsigned NonZeros = 0;
5810   bool IsAllConstants = true;
5811   SmallSet<SDValue, 8> Values;
5812   for (unsigned i = 0; i < NumElems; ++i) {
5813     SDValue Elt = Op.getOperand(i);
5814     if (Elt.getOpcode() == ISD::UNDEF)
5815       continue;
5816     Values.insert(Elt);
5817     if (Elt.getOpcode() != ISD::Constant &&
5818         Elt.getOpcode() != ISD::ConstantFP)
5819       IsAllConstants = false;
5820     if (X86::isZeroNode(Elt))
5821       NumZero++;
5822     else {
5823       NonZeros |= (1 << i);
5824       NumNonZero++;
5825     }
5826   }
5827
5828   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5829   if (NumNonZero == 0)
5830     return DAG.getUNDEF(VT);
5831
5832   // Special case for single non-zero, non-undef, element.
5833   if (NumNonZero == 1) {
5834     unsigned Idx = countTrailingZeros(NonZeros);
5835     SDValue Item = Op.getOperand(Idx);
5836
5837     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5838     // the value are obviously zero, truncate the value to i32 and do the
5839     // insertion that way.  Only do this if the value is non-constant or if the
5840     // value is a constant being inserted into element 0.  It is cheaper to do
5841     // a constant pool load than it is to do a movd + shuffle.
5842     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5843         (!IsAllConstants || Idx == 0)) {
5844       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5845         // Handle SSE only.
5846         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5847         EVT VecVT = MVT::v4i32;
5848         unsigned VecElts = 4;
5849
5850         // Truncate the value (which may itself be a constant) to i32, and
5851         // convert it to a vector with movd (S2V+shuffle to zero extend).
5852         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5853         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5854         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5855
5856         // Now we have our 32-bit value zero extended in the low element of
5857         // a vector.  If Idx != 0, swizzle it into place.
5858         if (Idx != 0) {
5859           SmallVector<int, 4> Mask;
5860           Mask.push_back(Idx);
5861           for (unsigned i = 1; i != VecElts; ++i)
5862             Mask.push_back(i);
5863           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5864                                       &Mask[0]);
5865         }
5866         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5867       }
5868     }
5869
5870     // If we have a constant or non-constant insertion into the low element of
5871     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5872     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5873     // depending on what the source datatype is.
5874     if (Idx == 0) {
5875       if (NumZero == 0)
5876         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5877
5878       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5879           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5880         if (VT.is256BitVector() || VT.is512BitVector()) {
5881           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5882           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5883                              Item, DAG.getIntPtrConstant(0));
5884         }
5885         assert(VT.is128BitVector() && "Expected an SSE value type!");
5886         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5887         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5888         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5889       }
5890
5891       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5892         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5893         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5894         if (VT.is256BitVector()) {
5895           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5896           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5897         } else {
5898           assert(VT.is128BitVector() && "Expected an SSE value type!");
5899           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5900         }
5901         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5902       }
5903     }
5904
5905     // Is it a vector logical left shift?
5906     if (NumElems == 2 && Idx == 1 &&
5907         X86::isZeroNode(Op.getOperand(0)) &&
5908         !X86::isZeroNode(Op.getOperand(1))) {
5909       unsigned NumBits = VT.getSizeInBits();
5910       return getVShift(true, VT,
5911                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5912                                    VT, Op.getOperand(1)),
5913                        NumBits/2, DAG, *this, dl);
5914     }
5915
5916     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5917       return SDValue();
5918
5919     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5920     // is a non-constant being inserted into an element other than the low one,
5921     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5922     // movd/movss) to move this into the low element, then shuffle it into
5923     // place.
5924     if (EVTBits == 32) {
5925       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5926
5927       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5928       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5929       SmallVector<int, 8> MaskVec;
5930       for (unsigned i = 0; i != NumElems; ++i)
5931         MaskVec.push_back(i == Idx ? 0 : 1);
5932       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5933     }
5934   }
5935
5936   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5937   if (Values.size() == 1) {
5938     if (EVTBits == 32) {
5939       // Instead of a shuffle like this:
5940       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5941       // Check if it's possible to issue this instead.
5942       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5943       unsigned Idx = countTrailingZeros(NonZeros);
5944       SDValue Item = Op.getOperand(Idx);
5945       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5946         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5947     }
5948     return SDValue();
5949   }
5950
5951   // A vector full of immediates; various special cases are already
5952   // handled, so this is best done with a single constant-pool load.
5953   if (IsAllConstants)
5954     return SDValue();
5955
5956   // For AVX-length vectors, build the individual 128-bit pieces and use
5957   // shuffles to put them in place.
5958   if (VT.is256BitVector()) {
5959     SmallVector<SDValue, 32> V;
5960     for (unsigned i = 0; i != NumElems; ++i)
5961       V.push_back(Op.getOperand(i));
5962
5963     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5964
5965     // Build both the lower and upper subvector.
5966     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5967     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5968                                 NumElems/2);
5969
5970     // Recreate the wider vector with the lower and upper part.
5971     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5972   }
5973
5974   // Let legalizer expand 2-wide build_vectors.
5975   if (EVTBits == 64) {
5976     if (NumNonZero == 1) {
5977       // One half is zero or undef.
5978       unsigned Idx = countTrailingZeros(NonZeros);
5979       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5980                                  Op.getOperand(Idx));
5981       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5982     }
5983     return SDValue();
5984   }
5985
5986   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5987   if (EVTBits == 8 && NumElems == 16) {
5988     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5989                                         Subtarget, *this);
5990     if (V.getNode()) return V;
5991   }
5992
5993   if (EVTBits == 16 && NumElems == 8) {
5994     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5995                                       Subtarget, *this);
5996     if (V.getNode()) return V;
5997   }
5998
5999   // If element VT is == 32 bits, turn it into a number of shuffles.
6000   SmallVector<SDValue, 8> V(NumElems);
6001   if (NumElems == 4 && NumZero > 0) {
6002     for (unsigned i = 0; i < 4; ++i) {
6003       bool isZero = !(NonZeros & (1 << i));
6004       if (isZero)
6005         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6006       else
6007         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6008     }
6009
6010     for (unsigned i = 0; i < 2; ++i) {
6011       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6012         default: break;
6013         case 0:
6014           V[i] = V[i*2];  // Must be a zero vector.
6015           break;
6016         case 1:
6017           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6018           break;
6019         case 2:
6020           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6021           break;
6022         case 3:
6023           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6024           break;
6025       }
6026     }
6027
6028     bool Reverse1 = (NonZeros & 0x3) == 2;
6029     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6030     int MaskVec[] = {
6031       Reverse1 ? 1 : 0,
6032       Reverse1 ? 0 : 1,
6033       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6034       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6035     };
6036     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6037   }
6038
6039   if (Values.size() > 1 && VT.is128BitVector()) {
6040     // Check for a build vector of consecutive loads.
6041     for (unsigned i = 0; i < NumElems; ++i)
6042       V[i] = Op.getOperand(i);
6043
6044     // Check for elements which are consecutive loads.
6045     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
6046     if (LD.getNode())
6047       return LD;
6048
6049     // Check for a build vector from mostly shuffle plus few inserting.
6050     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6051     if (Sh.getNode())
6052       return Sh;
6053
6054     // For SSE 4.1, use insertps to put the high elements into the low element.
6055     if (getSubtarget()->hasSSE41()) {
6056       SDValue Result;
6057       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6058         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6059       else
6060         Result = DAG.getUNDEF(VT);
6061
6062       for (unsigned i = 1; i < NumElems; ++i) {
6063         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6064         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6065                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6066       }
6067       return Result;
6068     }
6069
6070     // Otherwise, expand into a number of unpckl*, start by extending each of
6071     // our (non-undef) elements to the full vector width with the element in the
6072     // bottom slot of the vector (which generates no code for SSE).
6073     for (unsigned i = 0; i < NumElems; ++i) {
6074       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6075         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6076       else
6077         V[i] = DAG.getUNDEF(VT);
6078     }
6079
6080     // Next, we iteratively mix elements, e.g. for v4f32:
6081     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6082     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6083     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6084     unsigned EltStride = NumElems >> 1;
6085     while (EltStride != 0) {
6086       for (unsigned i = 0; i < EltStride; ++i) {
6087         // If V[i+EltStride] is undef and this is the first round of mixing,
6088         // then it is safe to just drop this shuffle: V[i] is already in the
6089         // right place, the one element (since it's the first round) being
6090         // inserted as undef can be dropped.  This isn't safe for successive
6091         // rounds because they will permute elements within both vectors.
6092         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6093             EltStride == NumElems/2)
6094           continue;
6095
6096         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6097       }
6098       EltStride >>= 1;
6099     }
6100     return V[0];
6101   }
6102   return SDValue();
6103 }
6104
6105 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6106 // to create 256-bit vectors from two other 128-bit ones.
6107 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6108   SDLoc dl(Op);
6109   MVT ResVT = Op.getSimpleValueType();
6110
6111   assert((ResVT.is256BitVector() ||
6112           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6113
6114   SDValue V1 = Op.getOperand(0);
6115   SDValue V2 = Op.getOperand(1);
6116   unsigned NumElems = ResVT.getVectorNumElements();
6117   if(ResVT.is256BitVector())
6118     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6119
6120   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6121 }
6122
6123 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6124   assert(Op.getNumOperands() == 2);
6125
6126   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6127   // from two other 128-bit ones.
6128   return LowerAVXCONCAT_VECTORS(Op, DAG);
6129 }
6130
6131 // Try to lower a shuffle node into a simple blend instruction.
6132 static SDValue
6133 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6134                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6135   SDValue V1 = SVOp->getOperand(0);
6136   SDValue V2 = SVOp->getOperand(1);
6137   SDLoc dl(SVOp);
6138   MVT VT = SVOp->getSimpleValueType(0);
6139   MVT EltVT = VT.getVectorElementType();
6140   unsigned NumElems = VT.getVectorNumElements();
6141
6142   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6143     return SDValue();
6144   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6145     return SDValue();
6146
6147   // Check the mask for BLEND and build the value.
6148   unsigned MaskValue = 0;
6149   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6150   unsigned NumLanes = (NumElems-1)/8 + 1;
6151   unsigned NumElemsInLane = NumElems / NumLanes;
6152
6153   // Blend for v16i16 should be symetric for the both lanes.
6154   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6155
6156     int SndLaneEltIdx = (NumLanes == 2) ?
6157       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6158     int EltIdx = SVOp->getMaskElt(i);
6159
6160     if ((EltIdx < 0 || EltIdx == (int)i) &&
6161         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6162       continue;
6163
6164     if (((unsigned)EltIdx == (i + NumElems)) &&
6165         (SndLaneEltIdx < 0 ||
6166          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6167       MaskValue |= (1<<i);
6168     else
6169       return SDValue();
6170   }
6171
6172   // Convert i32 vectors to floating point if it is not AVX2.
6173   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6174   MVT BlendVT = VT;
6175   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6176     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6177                                NumElems);
6178     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6179     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6180   }
6181
6182   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6183                             DAG.getConstant(MaskValue, MVT::i32));
6184   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6185 }
6186
6187 // v8i16 shuffles - Prefer shuffles in the following order:
6188 // 1. [all]   pshuflw, pshufhw, optional move
6189 // 2. [ssse3] 1 x pshufb
6190 // 3. [ssse3] 2 x pshufb + 1 x por
6191 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6192 static SDValue
6193 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6194                          SelectionDAG &DAG) {
6195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6196   SDValue V1 = SVOp->getOperand(0);
6197   SDValue V2 = SVOp->getOperand(1);
6198   SDLoc dl(SVOp);
6199   SmallVector<int, 8> MaskVals;
6200
6201   // Determine if more than 1 of the words in each of the low and high quadwords
6202   // of the result come from the same quadword of one of the two inputs.  Undef
6203   // mask values count as coming from any quadword, for better codegen.
6204   unsigned LoQuad[] = { 0, 0, 0, 0 };
6205   unsigned HiQuad[] = { 0, 0, 0, 0 };
6206   std::bitset<4> InputQuads;
6207   for (unsigned i = 0; i < 8; ++i) {
6208     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6209     int EltIdx = SVOp->getMaskElt(i);
6210     MaskVals.push_back(EltIdx);
6211     if (EltIdx < 0) {
6212       ++Quad[0];
6213       ++Quad[1];
6214       ++Quad[2];
6215       ++Quad[3];
6216       continue;
6217     }
6218     ++Quad[EltIdx / 4];
6219     InputQuads.set(EltIdx / 4);
6220   }
6221
6222   int BestLoQuad = -1;
6223   unsigned MaxQuad = 1;
6224   for (unsigned i = 0; i < 4; ++i) {
6225     if (LoQuad[i] > MaxQuad) {
6226       BestLoQuad = i;
6227       MaxQuad = LoQuad[i];
6228     }
6229   }
6230
6231   int BestHiQuad = -1;
6232   MaxQuad = 1;
6233   for (unsigned i = 0; i < 4; ++i) {
6234     if (HiQuad[i] > MaxQuad) {
6235       BestHiQuad = i;
6236       MaxQuad = HiQuad[i];
6237     }
6238   }
6239
6240   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6241   // of the two input vectors, shuffle them into one input vector so only a
6242   // single pshufb instruction is necessary. If There are more than 2 input
6243   // quads, disable the next transformation since it does not help SSSE3.
6244   bool V1Used = InputQuads[0] || InputQuads[1];
6245   bool V2Used = InputQuads[2] || InputQuads[3];
6246   if (Subtarget->hasSSSE3()) {
6247     if (InputQuads.count() == 2 && V1Used && V2Used) {
6248       BestLoQuad = InputQuads[0] ? 0 : 1;
6249       BestHiQuad = InputQuads[2] ? 2 : 3;
6250     }
6251     if (InputQuads.count() > 2) {
6252       BestLoQuad = -1;
6253       BestHiQuad = -1;
6254     }
6255   }
6256
6257   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6258   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6259   // words from all 4 input quadwords.
6260   SDValue NewV;
6261   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6262     int MaskV[] = {
6263       BestLoQuad < 0 ? 0 : BestLoQuad,
6264       BestHiQuad < 0 ? 1 : BestHiQuad
6265     };
6266     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6267                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6268                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6269     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6270
6271     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6272     // source words for the shuffle, to aid later transformations.
6273     bool AllWordsInNewV = true;
6274     bool InOrder[2] = { true, true };
6275     for (unsigned i = 0; i != 8; ++i) {
6276       int idx = MaskVals[i];
6277       if (idx != (int)i)
6278         InOrder[i/4] = false;
6279       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6280         continue;
6281       AllWordsInNewV = false;
6282       break;
6283     }
6284
6285     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6286     if (AllWordsInNewV) {
6287       for (int i = 0; i != 8; ++i) {
6288         int idx = MaskVals[i];
6289         if (idx < 0)
6290           continue;
6291         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6292         if ((idx != i) && idx < 4)
6293           pshufhw = false;
6294         if ((idx != i) && idx > 3)
6295           pshuflw = false;
6296       }
6297       V1 = NewV;
6298       V2Used = false;
6299       BestLoQuad = 0;
6300       BestHiQuad = 1;
6301     }
6302
6303     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6304     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6305     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6306       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6307       unsigned TargetMask = 0;
6308       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6309                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6310       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6311       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6312                              getShufflePSHUFLWImmediate(SVOp);
6313       V1 = NewV.getOperand(0);
6314       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6315     }
6316   }
6317
6318   // Promote splats to a larger type which usually leads to more efficient code.
6319   // FIXME: Is this true if pshufb is available?
6320   if (SVOp->isSplat())
6321     return PromoteSplat(SVOp, DAG);
6322
6323   // If we have SSSE3, and all words of the result are from 1 input vector,
6324   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6325   // is present, fall back to case 4.
6326   if (Subtarget->hasSSSE3()) {
6327     SmallVector<SDValue,16> pshufbMask;
6328
6329     // If we have elements from both input vectors, set the high bit of the
6330     // shuffle mask element to zero out elements that come from V2 in the V1
6331     // mask, and elements that come from V1 in the V2 mask, so that the two
6332     // results can be OR'd together.
6333     bool TwoInputs = V1Used && V2Used;
6334     for (unsigned i = 0; i != 8; ++i) {
6335       int EltIdx = MaskVals[i] * 2;
6336       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6337       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6338       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6339       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6340     }
6341     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6342     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6343                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6344                                  MVT::v16i8, &pshufbMask[0], 16));
6345     if (!TwoInputs)
6346       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6347
6348     // Calculate the shuffle mask for the second input, shuffle it, and
6349     // OR it with the first shuffled input.
6350     pshufbMask.clear();
6351     for (unsigned i = 0; i != 8; ++i) {
6352       int EltIdx = MaskVals[i] * 2;
6353       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6354       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6355       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6356       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6357     }
6358     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6359     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6360                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6361                                  MVT::v16i8, &pshufbMask[0], 16));
6362     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6363     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6364   }
6365
6366   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6367   // and update MaskVals with new element order.
6368   std::bitset<8> InOrder;
6369   if (BestLoQuad >= 0) {
6370     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6371     for (int i = 0; i != 4; ++i) {
6372       int idx = MaskVals[i];
6373       if (idx < 0) {
6374         InOrder.set(i);
6375       } else if ((idx / 4) == BestLoQuad) {
6376         MaskV[i] = idx & 3;
6377         InOrder.set(i);
6378       }
6379     }
6380     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6381                                 &MaskV[0]);
6382
6383     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6384       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6385       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6386                                   NewV.getOperand(0),
6387                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6388     }
6389   }
6390
6391   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6392   // and update MaskVals with the new element order.
6393   if (BestHiQuad >= 0) {
6394     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6395     for (unsigned i = 4; i != 8; ++i) {
6396       int idx = MaskVals[i];
6397       if (idx < 0) {
6398         InOrder.set(i);
6399       } else if ((idx / 4) == BestHiQuad) {
6400         MaskV[i] = (idx & 3) + 4;
6401         InOrder.set(i);
6402       }
6403     }
6404     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6405                                 &MaskV[0]);
6406
6407     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6408       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6409       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6410                                   NewV.getOperand(0),
6411                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6412     }
6413   }
6414
6415   // In case BestHi & BestLo were both -1, which means each quadword has a word
6416   // from each of the four input quadwords, calculate the InOrder bitvector now
6417   // before falling through to the insert/extract cleanup.
6418   if (BestLoQuad == -1 && BestHiQuad == -1) {
6419     NewV = V1;
6420     for (int i = 0; i != 8; ++i)
6421       if (MaskVals[i] < 0 || MaskVals[i] == i)
6422         InOrder.set(i);
6423   }
6424
6425   // The other elements are put in the right place using pextrw and pinsrw.
6426   for (unsigned i = 0; i != 8; ++i) {
6427     if (InOrder[i])
6428       continue;
6429     int EltIdx = MaskVals[i];
6430     if (EltIdx < 0)
6431       continue;
6432     SDValue ExtOp = (EltIdx < 8) ?
6433       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6434                   DAG.getIntPtrConstant(EltIdx)) :
6435       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6436                   DAG.getIntPtrConstant(EltIdx - 8));
6437     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6438                        DAG.getIntPtrConstant(i));
6439   }
6440   return NewV;
6441 }
6442
6443 // v16i8 shuffles - Prefer shuffles in the following order:
6444 // 1. [ssse3] 1 x pshufb
6445 // 2. [ssse3] 2 x pshufb + 1 x por
6446 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6447 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6448                                         const X86Subtarget* Subtarget,
6449                                         SelectionDAG &DAG) {
6450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6451   SDValue V1 = SVOp->getOperand(0);
6452   SDValue V2 = SVOp->getOperand(1);
6453   SDLoc dl(SVOp);
6454   ArrayRef<int> MaskVals = SVOp->getMask();
6455
6456   // Promote splats to a larger type which usually leads to more efficient code.
6457   // FIXME: Is this true if pshufb is available?
6458   if (SVOp->isSplat())
6459     return PromoteSplat(SVOp, DAG);
6460
6461   // If we have SSSE3, case 1 is generated when all result bytes come from
6462   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6463   // present, fall back to case 3.
6464
6465   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6466   if (Subtarget->hasSSSE3()) {
6467     SmallVector<SDValue,16> pshufbMask;
6468
6469     // If all result elements are from one input vector, then only translate
6470     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6471     //
6472     // Otherwise, we have elements from both input vectors, and must zero out
6473     // elements that come from V2 in the first mask, and V1 in the second mask
6474     // so that we can OR them together.
6475     for (unsigned i = 0; i != 16; ++i) {
6476       int EltIdx = MaskVals[i];
6477       if (EltIdx < 0 || EltIdx >= 16)
6478         EltIdx = 0x80;
6479       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6480     }
6481     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6482                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6483                                  MVT::v16i8, &pshufbMask[0], 16));
6484
6485     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6486     // the 2nd operand if it's undefined or zero.
6487     if (V2.getOpcode() == ISD::UNDEF ||
6488         ISD::isBuildVectorAllZeros(V2.getNode()))
6489       return V1;
6490
6491     // Calculate the shuffle mask for the second input, shuffle it, and
6492     // OR it with the first shuffled input.
6493     pshufbMask.clear();
6494     for (unsigned i = 0; i != 16; ++i) {
6495       int EltIdx = MaskVals[i];
6496       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6497       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6498     }
6499     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6500                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6501                                  MVT::v16i8, &pshufbMask[0], 16));
6502     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6503   }
6504
6505   // No SSSE3 - Calculate in place words and then fix all out of place words
6506   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6507   // the 16 different words that comprise the two doublequadword input vectors.
6508   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6509   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6510   SDValue NewV = V1;
6511   for (int i = 0; i != 8; ++i) {
6512     int Elt0 = MaskVals[i*2];
6513     int Elt1 = MaskVals[i*2+1];
6514
6515     // This word of the result is all undef, skip it.
6516     if (Elt0 < 0 && Elt1 < 0)
6517       continue;
6518
6519     // This word of the result is already in the correct place, skip it.
6520     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6521       continue;
6522
6523     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6524     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6525     SDValue InsElt;
6526
6527     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6528     // using a single extract together, load it and store it.
6529     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6530       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6531                            DAG.getIntPtrConstant(Elt1 / 2));
6532       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6533                         DAG.getIntPtrConstant(i));
6534       continue;
6535     }
6536
6537     // If Elt1 is defined, extract it from the appropriate source.  If the
6538     // source byte is not also odd, shift the extracted word left 8 bits
6539     // otherwise clear the bottom 8 bits if we need to do an or.
6540     if (Elt1 >= 0) {
6541       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6542                            DAG.getIntPtrConstant(Elt1 / 2));
6543       if ((Elt1 & 1) == 0)
6544         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6545                              DAG.getConstant(8,
6546                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6547       else if (Elt0 >= 0)
6548         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6549                              DAG.getConstant(0xFF00, MVT::i16));
6550     }
6551     // If Elt0 is defined, extract it from the appropriate source.  If the
6552     // source byte is not also even, shift the extracted word right 8 bits. If
6553     // Elt1 was also defined, OR the extracted values together before
6554     // inserting them in the result.
6555     if (Elt0 >= 0) {
6556       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6557                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6558       if ((Elt0 & 1) != 0)
6559         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6560                               DAG.getConstant(8,
6561                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6562       else if (Elt1 >= 0)
6563         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6564                              DAG.getConstant(0x00FF, MVT::i16));
6565       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6566                          : InsElt0;
6567     }
6568     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6569                        DAG.getIntPtrConstant(i));
6570   }
6571   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6572 }
6573
6574 // v32i8 shuffles - Translate to VPSHUFB if possible.
6575 static
6576 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6577                                  const X86Subtarget *Subtarget,
6578                                  SelectionDAG &DAG) {
6579   MVT VT = SVOp->getSimpleValueType(0);
6580   SDValue V1 = SVOp->getOperand(0);
6581   SDValue V2 = SVOp->getOperand(1);
6582   SDLoc dl(SVOp);
6583   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6584
6585   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6586   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6587   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6588
6589   // VPSHUFB may be generated if
6590   // (1) one of input vector is undefined or zeroinitializer.
6591   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6592   // And (2) the mask indexes don't cross the 128-bit lane.
6593   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6594       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6595     return SDValue();
6596
6597   if (V1IsAllZero && !V2IsAllZero) {
6598     CommuteVectorShuffleMask(MaskVals, 32);
6599     V1 = V2;
6600   }
6601   SmallVector<SDValue, 32> pshufbMask;
6602   for (unsigned i = 0; i != 32; i++) {
6603     int EltIdx = MaskVals[i];
6604     if (EltIdx < 0 || EltIdx >= 32)
6605       EltIdx = 0x80;
6606     else {
6607       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6608         // Cross lane is not allowed.
6609         return SDValue();
6610       EltIdx &= 0xf;
6611     }
6612     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6613   }
6614   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6615                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6616                                   MVT::v32i8, &pshufbMask[0], 32));
6617 }
6618
6619 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6620 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6621 /// done when every pair / quad of shuffle mask elements point to elements in
6622 /// the right sequence. e.g.
6623 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6624 static
6625 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6626                                  SelectionDAG &DAG) {
6627   MVT VT = SVOp->getSimpleValueType(0);
6628   SDLoc dl(SVOp);
6629   unsigned NumElems = VT.getVectorNumElements();
6630   MVT NewVT;
6631   unsigned Scale;
6632   switch (VT.SimpleTy) {
6633   default: llvm_unreachable("Unexpected!");
6634   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6635   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6636   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6637   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6638   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6639   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6640   }
6641
6642   SmallVector<int, 8> MaskVec;
6643   for (unsigned i = 0; i != NumElems; i += Scale) {
6644     int StartIdx = -1;
6645     for (unsigned j = 0; j != Scale; ++j) {
6646       int EltIdx = SVOp->getMaskElt(i+j);
6647       if (EltIdx < 0)
6648         continue;
6649       if (StartIdx < 0)
6650         StartIdx = (EltIdx / Scale);
6651       if (EltIdx != (int)(StartIdx*Scale + j))
6652         return SDValue();
6653     }
6654     MaskVec.push_back(StartIdx);
6655   }
6656
6657   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6658   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6659   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6660 }
6661
6662 /// getVZextMovL - Return a zero-extending vector move low node.
6663 ///
6664 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6665                             SDValue SrcOp, SelectionDAG &DAG,
6666                             const X86Subtarget *Subtarget, SDLoc dl) {
6667   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6668     LoadSDNode *LD = NULL;
6669     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6670       LD = dyn_cast<LoadSDNode>(SrcOp);
6671     if (!LD) {
6672       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6673       // instead.
6674       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6675       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6676           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6677           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6678           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6679         // PR2108
6680         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6681         return DAG.getNode(ISD::BITCAST, dl, VT,
6682                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6683                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6684                                                    OpVT,
6685                                                    SrcOp.getOperand(0)
6686                                                           .getOperand(0))));
6687       }
6688     }
6689   }
6690
6691   return DAG.getNode(ISD::BITCAST, dl, VT,
6692                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6693                                  DAG.getNode(ISD::BITCAST, dl,
6694                                              OpVT, SrcOp)));
6695 }
6696
6697 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6698 /// which could not be matched by any known target speficic shuffle
6699 static SDValue
6700 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6701
6702   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6703   if (NewOp.getNode())
6704     return NewOp;
6705
6706   MVT VT = SVOp->getSimpleValueType(0);
6707
6708   unsigned NumElems = VT.getVectorNumElements();
6709   unsigned NumLaneElems = NumElems / 2;
6710
6711   SDLoc dl(SVOp);
6712   MVT EltVT = VT.getVectorElementType();
6713   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6714   SDValue Output[2];
6715
6716   SmallVector<int, 16> Mask;
6717   for (unsigned l = 0; l < 2; ++l) {
6718     // Build a shuffle mask for the output, discovering on the fly which
6719     // input vectors to use as shuffle operands (recorded in InputUsed).
6720     // If building a suitable shuffle vector proves too hard, then bail
6721     // out with UseBuildVector set.
6722     bool UseBuildVector = false;
6723     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6724     unsigned LaneStart = l * NumLaneElems;
6725     for (unsigned i = 0; i != NumLaneElems; ++i) {
6726       // The mask element.  This indexes into the input.
6727       int Idx = SVOp->getMaskElt(i+LaneStart);
6728       if (Idx < 0) {
6729         // the mask element does not index into any input vector.
6730         Mask.push_back(-1);
6731         continue;
6732       }
6733
6734       // The input vector this mask element indexes into.
6735       int Input = Idx / NumLaneElems;
6736
6737       // Turn the index into an offset from the start of the input vector.
6738       Idx -= Input * NumLaneElems;
6739
6740       // Find or create a shuffle vector operand to hold this input.
6741       unsigned OpNo;
6742       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6743         if (InputUsed[OpNo] == Input)
6744           // This input vector is already an operand.
6745           break;
6746         if (InputUsed[OpNo] < 0) {
6747           // Create a new operand for this input vector.
6748           InputUsed[OpNo] = Input;
6749           break;
6750         }
6751       }
6752
6753       if (OpNo >= array_lengthof(InputUsed)) {
6754         // More than two input vectors used!  Give up on trying to create a
6755         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6756         UseBuildVector = true;
6757         break;
6758       }
6759
6760       // Add the mask index for the new shuffle vector.
6761       Mask.push_back(Idx + OpNo * NumLaneElems);
6762     }
6763
6764     if (UseBuildVector) {
6765       SmallVector<SDValue, 16> SVOps;
6766       for (unsigned i = 0; i != NumLaneElems; ++i) {
6767         // The mask element.  This indexes into the input.
6768         int Idx = SVOp->getMaskElt(i+LaneStart);
6769         if (Idx < 0) {
6770           SVOps.push_back(DAG.getUNDEF(EltVT));
6771           continue;
6772         }
6773
6774         // The input vector this mask element indexes into.
6775         int Input = Idx / NumElems;
6776
6777         // Turn the index into an offset from the start of the input vector.
6778         Idx -= Input * NumElems;
6779
6780         // Extract the vector element by hand.
6781         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6782                                     SVOp->getOperand(Input),
6783                                     DAG.getIntPtrConstant(Idx)));
6784       }
6785
6786       // Construct the output using a BUILD_VECTOR.
6787       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6788                               SVOps.size());
6789     } else if (InputUsed[0] < 0) {
6790       // No input vectors were used! The result is undefined.
6791       Output[l] = DAG.getUNDEF(NVT);
6792     } else {
6793       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6794                                         (InputUsed[0] % 2) * NumLaneElems,
6795                                         DAG, dl);
6796       // If only one input was used, use an undefined vector for the other.
6797       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6798         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6799                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6800       // At least one input vector was used. Create a new shuffle vector.
6801       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6802     }
6803
6804     Mask.clear();
6805   }
6806
6807   // Concatenate the result back
6808   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6809 }
6810
6811 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6812 /// 4 elements, and match them with several different shuffle types.
6813 static SDValue
6814 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6815   SDValue V1 = SVOp->getOperand(0);
6816   SDValue V2 = SVOp->getOperand(1);
6817   SDLoc dl(SVOp);
6818   MVT VT = SVOp->getSimpleValueType(0);
6819
6820   assert(VT.is128BitVector() && "Unsupported vector size");
6821
6822   std::pair<int, int> Locs[4];
6823   int Mask1[] = { -1, -1, -1, -1 };
6824   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6825
6826   unsigned NumHi = 0;
6827   unsigned NumLo = 0;
6828   for (unsigned i = 0; i != 4; ++i) {
6829     int Idx = PermMask[i];
6830     if (Idx < 0) {
6831       Locs[i] = std::make_pair(-1, -1);
6832     } else {
6833       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6834       if (Idx < 4) {
6835         Locs[i] = std::make_pair(0, NumLo);
6836         Mask1[NumLo] = Idx;
6837         NumLo++;
6838       } else {
6839         Locs[i] = std::make_pair(1, NumHi);
6840         if (2+NumHi < 4)
6841           Mask1[2+NumHi] = Idx;
6842         NumHi++;
6843       }
6844     }
6845   }
6846
6847   if (NumLo <= 2 && NumHi <= 2) {
6848     // If no more than two elements come from either vector. This can be
6849     // implemented with two shuffles. First shuffle gather the elements.
6850     // The second shuffle, which takes the first shuffle as both of its
6851     // vector operands, put the elements into the right order.
6852     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6853
6854     int Mask2[] = { -1, -1, -1, -1 };
6855
6856     for (unsigned i = 0; i != 4; ++i)
6857       if (Locs[i].first != -1) {
6858         unsigned Idx = (i < 2) ? 0 : 4;
6859         Idx += Locs[i].first * 2 + Locs[i].second;
6860         Mask2[i] = Idx;
6861       }
6862
6863     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6864   }
6865
6866   if (NumLo == 3 || NumHi == 3) {
6867     // Otherwise, we must have three elements from one vector, call it X, and
6868     // one element from the other, call it Y.  First, use a shufps to build an
6869     // intermediate vector with the one element from Y and the element from X
6870     // that will be in the same half in the final destination (the indexes don't
6871     // matter). Then, use a shufps to build the final vector, taking the half
6872     // containing the element from Y from the intermediate, and the other half
6873     // from X.
6874     if (NumHi == 3) {
6875       // Normalize it so the 3 elements come from V1.
6876       CommuteVectorShuffleMask(PermMask, 4);
6877       std::swap(V1, V2);
6878     }
6879
6880     // Find the element from V2.
6881     unsigned HiIndex;
6882     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6883       int Val = PermMask[HiIndex];
6884       if (Val < 0)
6885         continue;
6886       if (Val >= 4)
6887         break;
6888     }
6889
6890     Mask1[0] = PermMask[HiIndex];
6891     Mask1[1] = -1;
6892     Mask1[2] = PermMask[HiIndex^1];
6893     Mask1[3] = -1;
6894     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6895
6896     if (HiIndex >= 2) {
6897       Mask1[0] = PermMask[0];
6898       Mask1[1] = PermMask[1];
6899       Mask1[2] = HiIndex & 1 ? 6 : 4;
6900       Mask1[3] = HiIndex & 1 ? 4 : 6;
6901       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6902     }
6903
6904     Mask1[0] = HiIndex & 1 ? 2 : 0;
6905     Mask1[1] = HiIndex & 1 ? 0 : 2;
6906     Mask1[2] = PermMask[2];
6907     Mask1[3] = PermMask[3];
6908     if (Mask1[2] >= 0)
6909       Mask1[2] += 4;
6910     if (Mask1[3] >= 0)
6911       Mask1[3] += 4;
6912     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6913   }
6914
6915   // Break it into (shuffle shuffle_hi, shuffle_lo).
6916   int LoMask[] = { -1, -1, -1, -1 };
6917   int HiMask[] = { -1, -1, -1, -1 };
6918
6919   int *MaskPtr = LoMask;
6920   unsigned MaskIdx = 0;
6921   unsigned LoIdx = 0;
6922   unsigned HiIdx = 2;
6923   for (unsigned i = 0; i != 4; ++i) {
6924     if (i == 2) {
6925       MaskPtr = HiMask;
6926       MaskIdx = 1;
6927       LoIdx = 0;
6928       HiIdx = 2;
6929     }
6930     int Idx = PermMask[i];
6931     if (Idx < 0) {
6932       Locs[i] = std::make_pair(-1, -1);
6933     } else if (Idx < 4) {
6934       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6935       MaskPtr[LoIdx] = Idx;
6936       LoIdx++;
6937     } else {
6938       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6939       MaskPtr[HiIdx] = Idx;
6940       HiIdx++;
6941     }
6942   }
6943
6944   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6945   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6946   int MaskOps[] = { -1, -1, -1, -1 };
6947   for (unsigned i = 0; i != 4; ++i)
6948     if (Locs[i].first != -1)
6949       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6950   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6951 }
6952
6953 static bool MayFoldVectorLoad(SDValue V) {
6954   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6955     V = V.getOperand(0);
6956
6957   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6958     V = V.getOperand(0);
6959   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6960       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6961     // BUILD_VECTOR (load), undef
6962     V = V.getOperand(0);
6963
6964   return MayFoldLoad(V);
6965 }
6966
6967 static
6968 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6969   MVT VT = Op.getSimpleValueType();
6970
6971   // Canonizalize to v2f64.
6972   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6973   return DAG.getNode(ISD::BITCAST, dl, VT,
6974                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6975                                           V1, DAG));
6976 }
6977
6978 static
6979 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6980                         bool HasSSE2) {
6981   SDValue V1 = Op.getOperand(0);
6982   SDValue V2 = Op.getOperand(1);
6983   MVT VT = Op.getSimpleValueType();
6984
6985   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6986
6987   if (HasSSE2 && VT == MVT::v2f64)
6988     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6989
6990   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6991   return DAG.getNode(ISD::BITCAST, dl, VT,
6992                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6993                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6994                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6995 }
6996
6997 static
6998 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6999   SDValue V1 = Op.getOperand(0);
7000   SDValue V2 = Op.getOperand(1);
7001   MVT VT = Op.getSimpleValueType();
7002
7003   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7004          "unsupported shuffle type");
7005
7006   if (V2.getOpcode() == ISD::UNDEF)
7007     V2 = V1;
7008
7009   // v4i32 or v4f32
7010   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7011 }
7012
7013 static
7014 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7015   SDValue V1 = Op.getOperand(0);
7016   SDValue V2 = Op.getOperand(1);
7017   MVT VT = Op.getSimpleValueType();
7018   unsigned NumElems = VT.getVectorNumElements();
7019
7020   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7021   // operand of these instructions is only memory, so check if there's a
7022   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7023   // same masks.
7024   bool CanFoldLoad = false;
7025
7026   // Trivial case, when V2 comes from a load.
7027   if (MayFoldVectorLoad(V2))
7028     CanFoldLoad = true;
7029
7030   // When V1 is a load, it can be folded later into a store in isel, example:
7031   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7032   //    turns into:
7033   //  (MOVLPSmr addr:$src1, VR128:$src2)
7034   // So, recognize this potential and also use MOVLPS or MOVLPD
7035   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7036     CanFoldLoad = true;
7037
7038   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7039   if (CanFoldLoad) {
7040     if (HasSSE2 && NumElems == 2)
7041       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7042
7043     if (NumElems == 4)
7044       // If we don't care about the second element, proceed to use movss.
7045       if (SVOp->getMaskElt(1) != -1)
7046         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7047   }
7048
7049   // movl and movlp will both match v2i64, but v2i64 is never matched by
7050   // movl earlier because we make it strict to avoid messing with the movlp load
7051   // folding logic (see the code above getMOVLP call). Match it here then,
7052   // this is horrible, but will stay like this until we move all shuffle
7053   // matching to x86 specific nodes. Note that for the 1st condition all
7054   // types are matched with movsd.
7055   if (HasSSE2) {
7056     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7057     // as to remove this logic from here, as much as possible
7058     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7059       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7060     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7061   }
7062
7063   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7064
7065   // Invert the operand order and use SHUFPS to match it.
7066   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7067                               getShuffleSHUFImmediate(SVOp), DAG);
7068 }
7069
7070 // Reduce a vector shuffle to zext.
7071 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7072                                     SelectionDAG &DAG) {
7073   // PMOVZX is only available from SSE41.
7074   if (!Subtarget->hasSSE41())
7075     return SDValue();
7076
7077   MVT VT = Op.getSimpleValueType();
7078
7079   // Only AVX2 support 256-bit vector integer extending.
7080   if (!Subtarget->hasInt256() && VT.is256BitVector())
7081     return SDValue();
7082
7083   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7084   SDLoc DL(Op);
7085   SDValue V1 = Op.getOperand(0);
7086   SDValue V2 = Op.getOperand(1);
7087   unsigned NumElems = VT.getVectorNumElements();
7088
7089   // Extending is an unary operation and the element type of the source vector
7090   // won't be equal to or larger than i64.
7091   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7092       VT.getVectorElementType() == MVT::i64)
7093     return SDValue();
7094
7095   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7096   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7097   while ((1U << Shift) < NumElems) {
7098     if (SVOp->getMaskElt(1U << Shift) == 1)
7099       break;
7100     Shift += 1;
7101     // The maximal ratio is 8, i.e. from i8 to i64.
7102     if (Shift > 3)
7103       return SDValue();
7104   }
7105
7106   // Check the shuffle mask.
7107   unsigned Mask = (1U << Shift) - 1;
7108   for (unsigned i = 0; i != NumElems; ++i) {
7109     int EltIdx = SVOp->getMaskElt(i);
7110     if ((i & Mask) != 0 && EltIdx != -1)
7111       return SDValue();
7112     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7113       return SDValue();
7114   }
7115
7116   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7117   MVT NeVT = MVT::getIntegerVT(NBits);
7118   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7119
7120   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7121     return SDValue();
7122
7123   // Simplify the operand as it's prepared to be fed into shuffle.
7124   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7125   if (V1.getOpcode() == ISD::BITCAST &&
7126       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7127       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7128       V1.getOperand(0).getOperand(0)
7129         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7130     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7131     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7132     ConstantSDNode *CIdx =
7133       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7134     // If it's foldable, i.e. normal load with single use, we will let code
7135     // selection to fold it. Otherwise, we will short the conversion sequence.
7136     if (CIdx && CIdx->getZExtValue() == 0 &&
7137         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7138       MVT FullVT = V.getSimpleValueType();
7139       MVT V1VT = V1.getSimpleValueType();
7140       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7141         // The "ext_vec_elt" node is wider than the result node.
7142         // In this case we should extract subvector from V.
7143         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7144         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7145         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7146                                         FullVT.getVectorNumElements()/Ratio);
7147         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7148                         DAG.getIntPtrConstant(0));
7149       }
7150       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7151     }
7152   }
7153
7154   return DAG.getNode(ISD::BITCAST, DL, VT,
7155                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7156 }
7157
7158 static SDValue
7159 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7160                        SelectionDAG &DAG) {
7161   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7162   MVT VT = Op.getSimpleValueType();
7163   SDLoc dl(Op);
7164   SDValue V1 = Op.getOperand(0);
7165   SDValue V2 = Op.getOperand(1);
7166
7167   if (isZeroShuffle(SVOp))
7168     return getZeroVector(VT, Subtarget, DAG, dl);
7169
7170   // Handle splat operations
7171   if (SVOp->isSplat()) {
7172     // Use vbroadcast whenever the splat comes from a foldable load
7173     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7174     if (Broadcast.getNode())
7175       return Broadcast;
7176   }
7177
7178   // Check integer expanding shuffles.
7179   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7180   if (NewOp.getNode())
7181     return NewOp;
7182
7183   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7184   // do it!
7185   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7186       VT == MVT::v16i16 || VT == MVT::v32i8) {
7187     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7188     if (NewOp.getNode())
7189       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7190   } else if ((VT == MVT::v4i32 ||
7191              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7192     // FIXME: Figure out a cleaner way to do this.
7193     // Try to make use of movq to zero out the top part.
7194     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7195       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7196       if (NewOp.getNode()) {
7197         MVT NewVT = NewOp.getSimpleValueType();
7198         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7199                                NewVT, true, false))
7200           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7201                               DAG, Subtarget, dl);
7202       }
7203     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7204       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7205       if (NewOp.getNode()) {
7206         MVT NewVT = NewOp.getSimpleValueType();
7207         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7208           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7209                               DAG, Subtarget, dl);
7210       }
7211     }
7212   }
7213   return SDValue();
7214 }
7215
7216 SDValue
7217 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7218   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7219   SDValue V1 = Op.getOperand(0);
7220   SDValue V2 = Op.getOperand(1);
7221   MVT VT = Op.getSimpleValueType();
7222   SDLoc dl(Op);
7223   unsigned NumElems = VT.getVectorNumElements();
7224   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7225   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7226   bool V1IsSplat = false;
7227   bool V2IsSplat = false;
7228   bool HasSSE2 = Subtarget->hasSSE2();
7229   bool HasFp256    = Subtarget->hasFp256();
7230   bool HasInt256   = Subtarget->hasInt256();
7231   MachineFunction &MF = DAG.getMachineFunction();
7232   bool OptForSize = MF.getFunction()->getAttributes().
7233     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7234
7235   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7236
7237   if (V1IsUndef && V2IsUndef)
7238     return DAG.getUNDEF(VT);
7239
7240   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7241
7242   // Vector shuffle lowering takes 3 steps:
7243   //
7244   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7245   //    narrowing and commutation of operands should be handled.
7246   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7247   //    shuffle nodes.
7248   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7249   //    so the shuffle can be broken into other shuffles and the legalizer can
7250   //    try the lowering again.
7251   //
7252   // The general idea is that no vector_shuffle operation should be left to
7253   // be matched during isel, all of them must be converted to a target specific
7254   // node here.
7255
7256   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7257   // narrowing and commutation of operands should be handled. The actual code
7258   // doesn't include all of those, work in progress...
7259   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7260   if (NewOp.getNode())
7261     return NewOp;
7262
7263   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7264
7265   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7266   // unpckh_undef). Only use pshufd if speed is more important than size.
7267   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7268     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7269   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7270     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7271
7272   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7273       V2IsUndef && MayFoldVectorLoad(V1))
7274     return getMOVDDup(Op, dl, V1, DAG);
7275
7276   if (isMOVHLPS_v_undef_Mask(M, VT))
7277     return getMOVHighToLow(Op, dl, DAG);
7278
7279   // Use to match splats
7280   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7281       (VT == MVT::v2f64 || VT == MVT::v2i64))
7282     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7283
7284   if (isPSHUFDMask(M, VT)) {
7285     // The actual implementation will match the mask in the if above and then
7286     // during isel it can match several different instructions, not only pshufd
7287     // as its name says, sad but true, emulate the behavior for now...
7288     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7289       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7290
7291     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7292
7293     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7294       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7295
7296     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7297       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7298                                   DAG);
7299
7300     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7301                                 TargetMask, DAG);
7302   }
7303
7304   if (isPALIGNRMask(M, VT, Subtarget))
7305     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7306                                 getShufflePALIGNRImmediate(SVOp),
7307                                 DAG);
7308
7309   // Check if this can be converted into a logical shift.
7310   bool isLeft = false;
7311   unsigned ShAmt = 0;
7312   SDValue ShVal;
7313   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7314   if (isShift && ShVal.hasOneUse()) {
7315     // If the shifted value has multiple uses, it may be cheaper to use
7316     // v_set0 + movlhps or movhlps, etc.
7317     MVT EltVT = VT.getVectorElementType();
7318     ShAmt *= EltVT.getSizeInBits();
7319     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7320   }
7321
7322   if (isMOVLMask(M, VT)) {
7323     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7324       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7325     if (!isMOVLPMask(M, VT)) {
7326       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7327         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7328
7329       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7330         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7331     }
7332   }
7333
7334   // FIXME: fold these into legal mask.
7335   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7336     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7337
7338   if (isMOVHLPSMask(M, VT))
7339     return getMOVHighToLow(Op, dl, DAG);
7340
7341   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7342     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7343
7344   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7345     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7346
7347   if (isMOVLPMask(M, VT))
7348     return getMOVLP(Op, dl, DAG, HasSSE2);
7349
7350   if (ShouldXformToMOVHLPS(M, VT) ||
7351       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7352     return CommuteVectorShuffle(SVOp, DAG);
7353
7354   if (isShift) {
7355     // No better options. Use a vshldq / vsrldq.
7356     MVT EltVT = VT.getVectorElementType();
7357     ShAmt *= EltVT.getSizeInBits();
7358     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7359   }
7360
7361   bool Commuted = false;
7362   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7363   // 1,1,1,1 -> v8i16 though.
7364   V1IsSplat = isSplatVector(V1.getNode());
7365   V2IsSplat = isSplatVector(V2.getNode());
7366
7367   // Canonicalize the splat or undef, if present, to be on the RHS.
7368   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7369     CommuteVectorShuffleMask(M, NumElems);
7370     std::swap(V1, V2);
7371     std::swap(V1IsSplat, V2IsSplat);
7372     Commuted = true;
7373   }
7374
7375   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7376     // Shuffling low element of v1 into undef, just return v1.
7377     if (V2IsUndef)
7378       return V1;
7379     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7380     // the instruction selector will not match, so get a canonical MOVL with
7381     // swapped operands to undo the commute.
7382     return getMOVL(DAG, dl, VT, V2, V1);
7383   }
7384
7385   if (isUNPCKLMask(M, VT, HasInt256))
7386     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7387
7388   if (isUNPCKHMask(M, VT, HasInt256))
7389     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7390
7391   if (V2IsSplat) {
7392     // Normalize mask so all entries that point to V2 points to its first
7393     // element then try to match unpck{h|l} again. If match, return a
7394     // new vector_shuffle with the corrected mask.p
7395     SmallVector<int, 8> NewMask(M.begin(), M.end());
7396     NormalizeMask(NewMask, NumElems);
7397     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7398       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7399     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7400       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7401   }
7402
7403   if (Commuted) {
7404     // Commute is back and try unpck* again.
7405     // FIXME: this seems wrong.
7406     CommuteVectorShuffleMask(M, NumElems);
7407     std::swap(V1, V2);
7408     std::swap(V1IsSplat, V2IsSplat);
7409     Commuted = false;
7410
7411     if (isUNPCKLMask(M, VT, HasInt256))
7412       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7413
7414     if (isUNPCKHMask(M, VT, HasInt256))
7415       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7416   }
7417
7418   // Normalize the node to match x86 shuffle ops if needed
7419   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7420     return CommuteVectorShuffle(SVOp, DAG);
7421
7422   // The checks below are all present in isShuffleMaskLegal, but they are
7423   // inlined here right now to enable us to directly emit target specific
7424   // nodes, and remove one by one until they don't return Op anymore.
7425
7426   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7427       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7428     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7429       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7430   }
7431
7432   if (isPSHUFHWMask(M, VT, HasInt256))
7433     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7434                                 getShufflePSHUFHWImmediate(SVOp),
7435                                 DAG);
7436
7437   if (isPSHUFLWMask(M, VT, HasInt256))
7438     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7439                                 getShufflePSHUFLWImmediate(SVOp),
7440                                 DAG);
7441
7442   if (isSHUFPMask(M, VT))
7443     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7444                                 getShuffleSHUFImmediate(SVOp), DAG);
7445
7446   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7447     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7448   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7449     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7450
7451   //===--------------------------------------------------------------------===//
7452   // Generate target specific nodes for 128 or 256-bit shuffles only
7453   // supported in the AVX instruction set.
7454   //
7455
7456   // Handle VMOVDDUPY permutations
7457   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7458     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7459
7460   // Handle VPERMILPS/D* permutations
7461   if (isVPERMILPMask(M, VT)) {
7462     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7463       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7464                                   getShuffleSHUFImmediate(SVOp), DAG);
7465     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7466                                 getShuffleSHUFImmediate(SVOp), DAG);
7467   }
7468
7469   // Handle VPERM2F128/VPERM2I128 permutations
7470   if (isVPERM2X128Mask(M, VT, HasFp256))
7471     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7472                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7473
7474   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7475   if (BlendOp.getNode())
7476     return BlendOp;
7477
7478   unsigned Imm8;
7479   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7480     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7481
7482   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7483       VT.is512BitVector()) {
7484     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7485     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7486     SmallVector<SDValue, 16> permclMask;
7487     for (unsigned i = 0; i != NumElems; ++i) {
7488       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7489     }
7490
7491     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7492                                 &permclMask[0], NumElems);
7493     if (V2IsUndef)
7494       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7495       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7496                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7497     return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7498                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7499   }
7500
7501   //===--------------------------------------------------------------------===//
7502   // Since no target specific shuffle was selected for this generic one,
7503   // lower it into other known shuffles. FIXME: this isn't true yet, but
7504   // this is the plan.
7505   //
7506
7507   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7508   if (VT == MVT::v8i16) {
7509     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7510     if (NewOp.getNode())
7511       return NewOp;
7512   }
7513
7514   if (VT == MVT::v16i8) {
7515     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7516     if (NewOp.getNode())
7517       return NewOp;
7518   }
7519
7520   if (VT == MVT::v32i8) {
7521     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7522     if (NewOp.getNode())
7523       return NewOp;
7524   }
7525
7526   // Handle all 128-bit wide vectors with 4 elements, and match them with
7527   // several different shuffle types.
7528   if (NumElems == 4 && VT.is128BitVector())
7529     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7530
7531   // Handle general 256-bit shuffles
7532   if (VT.is256BitVector())
7533     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7534
7535   return SDValue();
7536 }
7537
7538 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7539   MVT VT = Op.getSimpleValueType();
7540   SDLoc dl(Op);
7541
7542   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7543     return SDValue();
7544
7545   if (VT.getSizeInBits() == 8) {
7546     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7547                                   Op.getOperand(0), Op.getOperand(1));
7548     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7549                                   DAG.getValueType(VT));
7550     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7551   }
7552
7553   if (VT.getSizeInBits() == 16) {
7554     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7555     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7556     if (Idx == 0)
7557       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7558                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7559                                      DAG.getNode(ISD::BITCAST, dl,
7560                                                  MVT::v4i32,
7561                                                  Op.getOperand(0)),
7562                                      Op.getOperand(1)));
7563     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7564                                   Op.getOperand(0), Op.getOperand(1));
7565     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7566                                   DAG.getValueType(VT));
7567     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7568   }
7569
7570   if (VT == MVT::f32) {
7571     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7572     // the result back to FR32 register. It's only worth matching if the
7573     // result has a single use which is a store or a bitcast to i32.  And in
7574     // the case of a store, it's not worth it if the index is a constant 0,
7575     // because a MOVSSmr can be used instead, which is smaller and faster.
7576     if (!Op.hasOneUse())
7577       return SDValue();
7578     SDNode *User = *Op.getNode()->use_begin();
7579     if ((User->getOpcode() != ISD::STORE ||
7580          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7581           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7582         (User->getOpcode() != ISD::BITCAST ||
7583          User->getValueType(0) != MVT::i32))
7584       return SDValue();
7585     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7586                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7587                                               Op.getOperand(0)),
7588                                               Op.getOperand(1));
7589     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7590   }
7591
7592   if (VT == MVT::i32 || VT == MVT::i64) {
7593     // ExtractPS/pextrq works with constant index.
7594     if (isa<ConstantSDNode>(Op.getOperand(1)))
7595       return Op;
7596   }
7597   return SDValue();
7598 }
7599
7600 SDValue
7601 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7602                                            SelectionDAG &DAG) const {
7603   SDLoc dl(Op);
7604   SDValue Vec = Op.getOperand(0);
7605   MVT VecVT = Vec.getSimpleValueType();
7606   SDValue Idx = Op.getOperand(1);
7607   if (!isa<ConstantSDNode>(Idx)) {
7608     if (VecVT.is512BitVector() ||
7609         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7610          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7611
7612       MVT MaskEltVT =
7613         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7614       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7615                                     MaskEltVT.getSizeInBits());
7616       
7617       if (Idx.getSimpleValueType() != MaskEltVT)
7618         if (Idx.getOpcode() == ISD::ZERO_EXTEND ||
7619             Idx.getOpcode() == ISD::SIGN_EXTEND)
7620           Idx = Idx.getOperand(0);
7621       assert(Idx.getSimpleValueType() == MaskEltVT &&
7622              "Unexpected index in insertelement");
7623       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7624                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7625                                 Idx, DAG.getConstant(0, getPointerTy()));
7626       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7627       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7628                         Perm, DAG.getConstant(0, getPointerTy()));
7629     }
7630     return SDValue();
7631   }
7632
7633   // If this is a 256-bit vector result, first extract the 128-bit vector and
7634   // then extract the element from the 128-bit vector.
7635   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7636
7637     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7638     // Get the 128-bit vector.
7639     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7640     MVT EltVT = VecVT.getVectorElementType();
7641
7642     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7643
7644     //if (IdxVal >= NumElems/2)
7645     //  IdxVal -= NumElems/2;
7646     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7647     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7648                        DAG.getConstant(IdxVal, MVT::i32));
7649   }
7650
7651   assert(VecVT.is128BitVector() && "Unexpected vector length");
7652
7653   if (Subtarget->hasSSE41()) {
7654     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7655     if (Res.getNode())
7656       return Res;
7657   }
7658
7659   MVT VT = Op.getSimpleValueType();
7660   // TODO: handle v16i8.
7661   if (VT.getSizeInBits() == 16) {
7662     SDValue Vec = Op.getOperand(0);
7663     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7664     if (Idx == 0)
7665       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7666                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7667                                      DAG.getNode(ISD::BITCAST, dl,
7668                                                  MVT::v4i32, Vec),
7669                                      Op.getOperand(1)));
7670     // Transform it so it match pextrw which produces a 32-bit result.
7671     MVT EltVT = MVT::i32;
7672     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7673                                   Op.getOperand(0), Op.getOperand(1));
7674     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7675                                   DAG.getValueType(VT));
7676     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7677   }
7678
7679   if (VT.getSizeInBits() == 32) {
7680     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7681     if (Idx == 0)
7682       return Op;
7683
7684     // SHUFPS the element to the lowest double word, then movss.
7685     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7686     MVT VVT = Op.getOperand(0).getSimpleValueType();
7687     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7688                                        DAG.getUNDEF(VVT), Mask);
7689     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7690                        DAG.getIntPtrConstant(0));
7691   }
7692
7693   if (VT.getSizeInBits() == 64) {
7694     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7695     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7696     //        to match extract_elt for f64.
7697     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7698     if (Idx == 0)
7699       return Op;
7700
7701     // UNPCKHPD the element to the lowest double word, then movsd.
7702     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7703     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7704     int Mask[2] = { 1, -1 };
7705     MVT VVT = Op.getOperand(0).getSimpleValueType();
7706     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7707                                        DAG.getUNDEF(VVT), Mask);
7708     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7709                        DAG.getIntPtrConstant(0));
7710   }
7711
7712   return SDValue();
7713 }
7714
7715 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7716   MVT VT = Op.getSimpleValueType();
7717   MVT EltVT = VT.getVectorElementType();
7718   SDLoc dl(Op);
7719
7720   SDValue N0 = Op.getOperand(0);
7721   SDValue N1 = Op.getOperand(1);
7722   SDValue N2 = Op.getOperand(2);
7723
7724   if (!VT.is128BitVector())
7725     return SDValue();
7726
7727   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7728       isa<ConstantSDNode>(N2)) {
7729     unsigned Opc;
7730     if (VT == MVT::v8i16)
7731       Opc = X86ISD::PINSRW;
7732     else if (VT == MVT::v16i8)
7733       Opc = X86ISD::PINSRB;
7734     else
7735       Opc = X86ISD::PINSRB;
7736
7737     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7738     // argument.
7739     if (N1.getValueType() != MVT::i32)
7740       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7741     if (N2.getValueType() != MVT::i32)
7742       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7743     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7744   }
7745
7746   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7747     // Bits [7:6] of the constant are the source select.  This will always be
7748     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7749     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7750     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7751     // Bits [5:4] of the constant are the destination select.  This is the
7752     //  value of the incoming immediate.
7753     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7754     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7755     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7756     // Create this as a scalar to vector..
7757     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7758     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7759   }
7760
7761   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7762     // PINSR* works with constant index.
7763     return Op;
7764   }
7765   return SDValue();
7766 }
7767
7768 SDValue
7769 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7770   MVT VT = Op.getSimpleValueType();
7771   MVT EltVT = VT.getVectorElementType();
7772
7773   SDLoc dl(Op);
7774   SDValue N0 = Op.getOperand(0);
7775   SDValue N1 = Op.getOperand(1);
7776   SDValue N2 = Op.getOperand(2);
7777
7778   // If this is a 256-bit vector result, first extract the 128-bit vector,
7779   // insert the element into the extracted half and then place it back.
7780   if (VT.is256BitVector() || VT.is512BitVector()) {
7781     if (!isa<ConstantSDNode>(N2))
7782       return SDValue();
7783
7784     // Get the desired 128-bit vector half.
7785     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7786     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7787
7788     // Insert the element into the desired half.
7789     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7790     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7791
7792     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7793                     DAG.getConstant(IdxIn128, MVT::i32));
7794
7795     // Insert the changed part back to the 256-bit vector
7796     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7797   }
7798
7799   if (Subtarget->hasSSE41())
7800     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7801
7802   if (EltVT == MVT::i8)
7803     return SDValue();
7804
7805   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7806     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7807     // as its second argument.
7808     if (N1.getValueType() != MVT::i32)
7809       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7810     if (N2.getValueType() != MVT::i32)
7811       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7812     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7813   }
7814   return SDValue();
7815 }
7816
7817 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7818   SDLoc dl(Op);
7819   MVT OpVT = Op.getSimpleValueType();
7820
7821   // If this is a 256-bit vector result, first insert into a 128-bit
7822   // vector and then insert into the 256-bit vector.
7823   if (!OpVT.is128BitVector()) {
7824     // Insert into a 128-bit vector.
7825     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7826     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7827                                  OpVT.getVectorNumElements() / SizeFactor);
7828
7829     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7830
7831     // Insert the 128-bit vector.
7832     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7833   }
7834
7835   if (OpVT == MVT::v1i64 &&
7836       Op.getOperand(0).getValueType() == MVT::i64)
7837     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7838
7839   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7840   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7841   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7842                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7843 }
7844
7845 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7846 // a simple subregister reference or explicit instructions to grab
7847 // upper bits of a vector.
7848 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7849                                       SelectionDAG &DAG) {
7850   SDLoc dl(Op);
7851   SDValue In =  Op.getOperand(0);
7852   SDValue Idx = Op.getOperand(1);
7853   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7854   MVT ResVT   = Op.getSimpleValueType();
7855   MVT InVT    = In.getSimpleValueType();
7856
7857   if (Subtarget->hasFp256()) {
7858     if (ResVT.is128BitVector() &&
7859         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7860         isa<ConstantSDNode>(Idx)) {
7861       return Extract128BitVector(In, IdxVal, DAG, dl);
7862     }
7863     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7864         isa<ConstantSDNode>(Idx)) {
7865       return Extract256BitVector(In, IdxVal, DAG, dl);
7866     }
7867   }
7868   return SDValue();
7869 }
7870
7871 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7872 // simple superregister reference or explicit instructions to insert
7873 // the upper bits of a vector.
7874 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7875                                      SelectionDAG &DAG) {
7876   if (Subtarget->hasFp256()) {
7877     SDLoc dl(Op.getNode());
7878     SDValue Vec = Op.getNode()->getOperand(0);
7879     SDValue SubVec = Op.getNode()->getOperand(1);
7880     SDValue Idx = Op.getNode()->getOperand(2);
7881
7882     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
7883          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
7884         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
7885         isa<ConstantSDNode>(Idx)) {
7886       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7887       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7888     }
7889
7890     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
7891         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
7892         isa<ConstantSDNode>(Idx)) {
7893       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7894       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7895     }
7896   }
7897   return SDValue();
7898 }
7899
7900 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7901 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7902 // one of the above mentioned nodes. It has to be wrapped because otherwise
7903 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7904 // be used to form addressing mode. These wrapped nodes will be selected
7905 // into MOV32ri.
7906 SDValue
7907 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7908   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7909
7910   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7911   // global base reg.
7912   unsigned char OpFlag = 0;
7913   unsigned WrapperKind = X86ISD::Wrapper;
7914   CodeModel::Model M = getTargetMachine().getCodeModel();
7915
7916   if (Subtarget->isPICStyleRIPRel() &&
7917       (M == CodeModel::Small || M == CodeModel::Kernel))
7918     WrapperKind = X86ISD::WrapperRIP;
7919   else if (Subtarget->isPICStyleGOT())
7920     OpFlag = X86II::MO_GOTOFF;
7921   else if (Subtarget->isPICStyleStubPIC())
7922     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7923
7924   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7925                                              CP->getAlignment(),
7926                                              CP->getOffset(), OpFlag);
7927   SDLoc DL(CP);
7928   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7929   // With PIC, the address is actually $g + Offset.
7930   if (OpFlag) {
7931     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7932                          DAG.getNode(X86ISD::GlobalBaseReg,
7933                                      SDLoc(), getPointerTy()),
7934                          Result);
7935   }
7936
7937   return Result;
7938 }
7939
7940 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7941   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7942
7943   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7944   // global base reg.
7945   unsigned char OpFlag = 0;
7946   unsigned WrapperKind = X86ISD::Wrapper;
7947   CodeModel::Model M = getTargetMachine().getCodeModel();
7948
7949   if (Subtarget->isPICStyleRIPRel() &&
7950       (M == CodeModel::Small || M == CodeModel::Kernel))
7951     WrapperKind = X86ISD::WrapperRIP;
7952   else if (Subtarget->isPICStyleGOT())
7953     OpFlag = X86II::MO_GOTOFF;
7954   else if (Subtarget->isPICStyleStubPIC())
7955     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7956
7957   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7958                                           OpFlag);
7959   SDLoc DL(JT);
7960   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7961
7962   // With PIC, the address is actually $g + Offset.
7963   if (OpFlag)
7964     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7965                          DAG.getNode(X86ISD::GlobalBaseReg,
7966                                      SDLoc(), getPointerTy()),
7967                          Result);
7968
7969   return Result;
7970 }
7971
7972 SDValue
7973 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7974   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7975
7976   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7977   // global base reg.
7978   unsigned char OpFlag = 0;
7979   unsigned WrapperKind = X86ISD::Wrapper;
7980   CodeModel::Model M = getTargetMachine().getCodeModel();
7981
7982   if (Subtarget->isPICStyleRIPRel() &&
7983       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7984     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7985       OpFlag = X86II::MO_GOTPCREL;
7986     WrapperKind = X86ISD::WrapperRIP;
7987   } else if (Subtarget->isPICStyleGOT()) {
7988     OpFlag = X86II::MO_GOT;
7989   } else if (Subtarget->isPICStyleStubPIC()) {
7990     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7991   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7992     OpFlag = X86II::MO_DARWIN_NONLAZY;
7993   }
7994
7995   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7996
7997   SDLoc DL(Op);
7998   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7999
8000   // With PIC, the address is actually $g + Offset.
8001   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8002       !Subtarget->is64Bit()) {
8003     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8004                          DAG.getNode(X86ISD::GlobalBaseReg,
8005                                      SDLoc(), getPointerTy()),
8006                          Result);
8007   }
8008
8009   // For symbols that require a load from a stub to get the address, emit the
8010   // load.
8011   if (isGlobalStubReference(OpFlag))
8012     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8013                          MachinePointerInfo::getGOT(), false, false, false, 0);
8014
8015   return Result;
8016 }
8017
8018 SDValue
8019 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8020   // Create the TargetBlockAddressAddress node.
8021   unsigned char OpFlags =
8022     Subtarget->ClassifyBlockAddressReference();
8023   CodeModel::Model M = getTargetMachine().getCodeModel();
8024   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8025   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8026   SDLoc dl(Op);
8027   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8028                                              OpFlags);
8029
8030   if (Subtarget->isPICStyleRIPRel() &&
8031       (M == CodeModel::Small || M == CodeModel::Kernel))
8032     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8033   else
8034     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8035
8036   // With PIC, the address is actually $g + Offset.
8037   if (isGlobalRelativeToPICBase(OpFlags)) {
8038     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8039                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8040                          Result);
8041   }
8042
8043   return Result;
8044 }
8045
8046 SDValue
8047 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8048                                       int64_t Offset, SelectionDAG &DAG) const {
8049   // Create the TargetGlobalAddress node, folding in the constant
8050   // offset if it is legal.
8051   unsigned char OpFlags =
8052     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8053   CodeModel::Model M = getTargetMachine().getCodeModel();
8054   SDValue Result;
8055   if (OpFlags == X86II::MO_NO_FLAG &&
8056       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8057     // A direct static reference to a global.
8058     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8059     Offset = 0;
8060   } else {
8061     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8062   }
8063
8064   if (Subtarget->isPICStyleRIPRel() &&
8065       (M == CodeModel::Small || M == CodeModel::Kernel))
8066     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8067   else
8068     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8069
8070   // With PIC, the address is actually $g + Offset.
8071   if (isGlobalRelativeToPICBase(OpFlags)) {
8072     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8073                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8074                          Result);
8075   }
8076
8077   // For globals that require a load from a stub to get the address, emit the
8078   // load.
8079   if (isGlobalStubReference(OpFlags))
8080     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8081                          MachinePointerInfo::getGOT(), false, false, false, 0);
8082
8083   // If there was a non-zero offset that we didn't fold, create an explicit
8084   // addition for it.
8085   if (Offset != 0)
8086     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8087                          DAG.getConstant(Offset, getPointerTy()));
8088
8089   return Result;
8090 }
8091
8092 SDValue
8093 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8094   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8095   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8096   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8097 }
8098
8099 static SDValue
8100 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8101            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8102            unsigned char OperandFlags, bool LocalDynamic = false) {
8103   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8104   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8105   SDLoc dl(GA);
8106   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8107                                            GA->getValueType(0),
8108                                            GA->getOffset(),
8109                                            OperandFlags);
8110
8111   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8112                                            : X86ISD::TLSADDR;
8113
8114   if (InFlag) {
8115     SDValue Ops[] = { Chain,  TGA, *InFlag };
8116     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8117   } else {
8118     SDValue Ops[]  = { Chain, TGA };
8119     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8120   }
8121
8122   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8123   MFI->setAdjustsStack(true);
8124
8125   SDValue Flag = Chain.getValue(1);
8126   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8127 }
8128
8129 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8130 static SDValue
8131 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8132                                 const EVT PtrVT) {
8133   SDValue InFlag;
8134   SDLoc dl(GA);  // ? function entry point might be better
8135   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8136                                    DAG.getNode(X86ISD::GlobalBaseReg,
8137                                                SDLoc(), PtrVT), InFlag);
8138   InFlag = Chain.getValue(1);
8139
8140   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8141 }
8142
8143 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8144 static SDValue
8145 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8146                                 const EVT PtrVT) {
8147   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8148                     X86::RAX, X86II::MO_TLSGD);
8149 }
8150
8151 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8152                                            SelectionDAG &DAG,
8153                                            const EVT PtrVT,
8154                                            bool is64Bit) {
8155   SDLoc dl(GA);
8156
8157   // Get the start address of the TLS block for this module.
8158   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8159       .getInfo<X86MachineFunctionInfo>();
8160   MFI->incNumLocalDynamicTLSAccesses();
8161
8162   SDValue Base;
8163   if (is64Bit) {
8164     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8165                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8166   } else {
8167     SDValue InFlag;
8168     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8169         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8170     InFlag = Chain.getValue(1);
8171     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8172                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8173   }
8174
8175   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8176   // of Base.
8177
8178   // Build x@dtpoff.
8179   unsigned char OperandFlags = X86II::MO_DTPOFF;
8180   unsigned WrapperKind = X86ISD::Wrapper;
8181   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8182                                            GA->getValueType(0),
8183                                            GA->getOffset(), OperandFlags);
8184   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8185
8186   // Add x@dtpoff with the base.
8187   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8188 }
8189
8190 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8191 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8192                                    const EVT PtrVT, TLSModel::Model model,
8193                                    bool is64Bit, bool isPIC) {
8194   SDLoc dl(GA);
8195
8196   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8197   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8198                                                          is64Bit ? 257 : 256));
8199
8200   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8201                                       DAG.getIntPtrConstant(0),
8202                                       MachinePointerInfo(Ptr),
8203                                       false, false, false, 0);
8204
8205   unsigned char OperandFlags = 0;
8206   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8207   // initialexec.
8208   unsigned WrapperKind = X86ISD::Wrapper;
8209   if (model == TLSModel::LocalExec) {
8210     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8211   } else if (model == TLSModel::InitialExec) {
8212     if (is64Bit) {
8213       OperandFlags = X86II::MO_GOTTPOFF;
8214       WrapperKind = X86ISD::WrapperRIP;
8215     } else {
8216       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8217     }
8218   } else {
8219     llvm_unreachable("Unexpected model");
8220   }
8221
8222   // emit "addl x@ntpoff,%eax" (local exec)
8223   // or "addl x@indntpoff,%eax" (initial exec)
8224   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8225   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8226                                            GA->getValueType(0),
8227                                            GA->getOffset(), OperandFlags);
8228   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8229
8230   if (model == TLSModel::InitialExec) {
8231     if (isPIC && !is64Bit) {
8232       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8233                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8234                            Offset);
8235     }
8236
8237     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8238                          MachinePointerInfo::getGOT(), false, false, false,
8239                          0);
8240   }
8241
8242   // The address of the thread local variable is the add of the thread
8243   // pointer with the offset of the variable.
8244   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8245 }
8246
8247 SDValue
8248 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8249
8250   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8251   const GlobalValue *GV = GA->getGlobal();
8252
8253   if (Subtarget->isTargetELF()) {
8254     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8255
8256     switch (model) {
8257       case TLSModel::GeneralDynamic:
8258         if (Subtarget->is64Bit())
8259           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8260         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8261       case TLSModel::LocalDynamic:
8262         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8263                                            Subtarget->is64Bit());
8264       case TLSModel::InitialExec:
8265       case TLSModel::LocalExec:
8266         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8267                                    Subtarget->is64Bit(),
8268                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8269     }
8270     llvm_unreachable("Unknown TLS model.");
8271   }
8272
8273   if (Subtarget->isTargetDarwin()) {
8274     // Darwin only has one model of TLS.  Lower to that.
8275     unsigned char OpFlag = 0;
8276     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8277                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8278
8279     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8280     // global base reg.
8281     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8282                   !Subtarget->is64Bit();
8283     if (PIC32)
8284       OpFlag = X86II::MO_TLVP_PIC_BASE;
8285     else
8286       OpFlag = X86II::MO_TLVP;
8287     SDLoc DL(Op);
8288     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8289                                                 GA->getValueType(0),
8290                                                 GA->getOffset(), OpFlag);
8291     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8292
8293     // With PIC32, the address is actually $g + Offset.
8294     if (PIC32)
8295       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8296                            DAG.getNode(X86ISD::GlobalBaseReg,
8297                                        SDLoc(), getPointerTy()),
8298                            Offset);
8299
8300     // Lowering the machine isd will make sure everything is in the right
8301     // location.
8302     SDValue Chain = DAG.getEntryNode();
8303     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8304     SDValue Args[] = { Chain, Offset };
8305     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8306
8307     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8308     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8309     MFI->setAdjustsStack(true);
8310
8311     // And our return value (tls address) is in the standard call return value
8312     // location.
8313     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8314     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8315                               Chain.getValue(1));
8316   }
8317
8318   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8319     // Just use the implicit TLS architecture
8320     // Need to generate someting similar to:
8321     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8322     //                                  ; from TEB
8323     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8324     //   mov     rcx, qword [rdx+rcx*8]
8325     //   mov     eax, .tls$:tlsvar
8326     //   [rax+rcx] contains the address
8327     // Windows 64bit: gs:0x58
8328     // Windows 32bit: fs:__tls_array
8329
8330     // If GV is an alias then use the aliasee for determining
8331     // thread-localness.
8332     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8333       GV = GA->resolveAliasedGlobal(false);
8334     SDLoc dl(GA);
8335     SDValue Chain = DAG.getEntryNode();
8336
8337     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8338     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8339     // use its literal value of 0x2C.
8340     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8341                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8342                                                              256)
8343                                         : Type::getInt32PtrTy(*DAG.getContext(),
8344                                                               257));
8345
8346     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8347       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8348         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8349
8350     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8351                                         MachinePointerInfo(Ptr),
8352                                         false, false, false, 0);
8353
8354     // Load the _tls_index variable
8355     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8356     if (Subtarget->is64Bit())
8357       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8358                            IDX, MachinePointerInfo(), MVT::i32,
8359                            false, false, 0);
8360     else
8361       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8362                         false, false, false, 0);
8363
8364     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8365                                     getPointerTy());
8366     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8367
8368     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8369     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8370                       false, false, false, 0);
8371
8372     // Get the offset of start of .tls section
8373     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8374                                              GA->getValueType(0),
8375                                              GA->getOffset(), X86II::MO_SECREL);
8376     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8377
8378     // The address of the thread local variable is the add of the thread
8379     // pointer with the offset of the variable.
8380     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8381   }
8382
8383   llvm_unreachable("TLS not implemented for this target.");
8384 }
8385
8386 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8387 /// and take a 2 x i32 value to shift plus a shift amount.
8388 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8389   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8390   EVT VT = Op.getValueType();
8391   unsigned VTBits = VT.getSizeInBits();
8392   SDLoc dl(Op);
8393   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8394   SDValue ShOpLo = Op.getOperand(0);
8395   SDValue ShOpHi = Op.getOperand(1);
8396   SDValue ShAmt  = Op.getOperand(2);
8397   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8398                                      DAG.getConstant(VTBits - 1, MVT::i8))
8399                        : DAG.getConstant(0, VT);
8400
8401   SDValue Tmp2, Tmp3;
8402   if (Op.getOpcode() == ISD::SHL_PARTS) {
8403     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8404     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8405   } else {
8406     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8407     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8408   }
8409
8410   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8411                                 DAG.getConstant(VTBits, MVT::i8));
8412   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8413                              AndNode, DAG.getConstant(0, MVT::i8));
8414
8415   SDValue Hi, Lo;
8416   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8417   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8418   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8419
8420   if (Op.getOpcode() == ISD::SHL_PARTS) {
8421     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8422     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8423   } else {
8424     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8425     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8426   }
8427
8428   SDValue Ops[2] = { Lo, Hi };
8429   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8430 }
8431
8432 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8433                                            SelectionDAG &DAG) const {
8434   EVT SrcVT = Op.getOperand(0).getValueType();
8435
8436   if (SrcVT.isVector())
8437     return SDValue();
8438
8439   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8440          "Unknown SINT_TO_FP to lower!");
8441
8442   // These are really Legal; return the operand so the caller accepts it as
8443   // Legal.
8444   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8445     return Op;
8446   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8447       Subtarget->is64Bit()) {
8448     return Op;
8449   }
8450
8451   SDLoc dl(Op);
8452   unsigned Size = SrcVT.getSizeInBits()/8;
8453   MachineFunction &MF = DAG.getMachineFunction();
8454   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8455   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8456   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8457                                StackSlot,
8458                                MachinePointerInfo::getFixedStack(SSFI),
8459                                false, false, 0);
8460   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8461 }
8462
8463 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8464                                      SDValue StackSlot,
8465                                      SelectionDAG &DAG) const {
8466   // Build the FILD
8467   SDLoc DL(Op);
8468   SDVTList Tys;
8469   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8470   if (useSSE)
8471     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8472   else
8473     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8474
8475   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8476
8477   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8478   MachineMemOperand *MMO;
8479   if (FI) {
8480     int SSFI = FI->getIndex();
8481     MMO =
8482       DAG.getMachineFunction()
8483       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8484                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8485   } else {
8486     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8487     StackSlot = StackSlot.getOperand(1);
8488   }
8489   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8490   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8491                                            X86ISD::FILD, DL,
8492                                            Tys, Ops, array_lengthof(Ops),
8493                                            SrcVT, MMO);
8494
8495   if (useSSE) {
8496     Chain = Result.getValue(1);
8497     SDValue InFlag = Result.getValue(2);
8498
8499     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8500     // shouldn't be necessary except that RFP cannot be live across
8501     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8502     MachineFunction &MF = DAG.getMachineFunction();
8503     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8504     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8505     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8506     Tys = DAG.getVTList(MVT::Other);
8507     SDValue Ops[] = {
8508       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8509     };
8510     MachineMemOperand *MMO =
8511       DAG.getMachineFunction()
8512       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8513                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8514
8515     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8516                                     Ops, array_lengthof(Ops),
8517                                     Op.getValueType(), MMO);
8518     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8519                          MachinePointerInfo::getFixedStack(SSFI),
8520                          false, false, false, 0);
8521   }
8522
8523   return Result;
8524 }
8525
8526 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8527 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8528                                                SelectionDAG &DAG) const {
8529   // This algorithm is not obvious. Here it is what we're trying to output:
8530   /*
8531      movq       %rax,  %xmm0
8532      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8533      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8534      #ifdef __SSE3__
8535        haddpd   %xmm0, %xmm0
8536      #else
8537        pshufd   $0x4e, %xmm0, %xmm1
8538        addpd    %xmm1, %xmm0
8539      #endif
8540   */
8541
8542   SDLoc dl(Op);
8543   LLVMContext *Context = DAG.getContext();
8544
8545   // Build some magic constants.
8546   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8547   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8548   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8549
8550   SmallVector<Constant*,2> CV1;
8551   CV1.push_back(
8552     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8553                                       APInt(64, 0x4330000000000000ULL))));
8554   CV1.push_back(
8555     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8556                                       APInt(64, 0x4530000000000000ULL))));
8557   Constant *C1 = ConstantVector::get(CV1);
8558   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8559
8560   // Load the 64-bit value into an XMM register.
8561   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8562                             Op.getOperand(0));
8563   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8564                               MachinePointerInfo::getConstantPool(),
8565                               false, false, false, 16);
8566   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8567                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8568                               CLod0);
8569
8570   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8571                               MachinePointerInfo::getConstantPool(),
8572                               false, false, false, 16);
8573   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8574   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8575   SDValue Result;
8576
8577   if (Subtarget->hasSSE3()) {
8578     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8579     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8580   } else {
8581     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8582     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8583                                            S2F, 0x4E, DAG);
8584     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8585                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8586                          Sub);
8587   }
8588
8589   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8590                      DAG.getIntPtrConstant(0));
8591 }
8592
8593 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8594 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8595                                                SelectionDAG &DAG) const {
8596   SDLoc dl(Op);
8597   // FP constant to bias correct the final result.
8598   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8599                                    MVT::f64);
8600
8601   // Load the 32-bit value into an XMM register.
8602   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8603                              Op.getOperand(0));
8604
8605   // Zero out the upper parts of the register.
8606   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8607
8608   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8609                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8610                      DAG.getIntPtrConstant(0));
8611
8612   // Or the load with the bias.
8613   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8614                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8615                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8616                                                    MVT::v2f64, Load)),
8617                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8618                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8619                                                    MVT::v2f64, Bias)));
8620   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8621                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8622                    DAG.getIntPtrConstant(0));
8623
8624   // Subtract the bias.
8625   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8626
8627   // Handle final rounding.
8628   EVT DestVT = Op.getValueType();
8629
8630   if (DestVT.bitsLT(MVT::f64))
8631     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8632                        DAG.getIntPtrConstant(0));
8633   if (DestVT.bitsGT(MVT::f64))
8634     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8635
8636   // Handle final rounding.
8637   return Sub;
8638 }
8639
8640 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8641                                                SelectionDAG &DAG) const {
8642   SDValue N0 = Op.getOperand(0);
8643   EVT SVT = N0.getValueType();
8644   SDLoc dl(Op);
8645
8646   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8647           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8648          "Custom UINT_TO_FP is not supported!");
8649
8650   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8651                              SVT.getVectorNumElements());
8652   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8653                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8654 }
8655
8656 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8657                                            SelectionDAG &DAG) const {
8658   SDValue N0 = Op.getOperand(0);
8659   SDLoc dl(Op);
8660
8661   if (Op.getValueType().isVector())
8662     return lowerUINT_TO_FP_vec(Op, DAG);
8663
8664   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8665   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8666   // the optimization here.
8667   if (DAG.SignBitIsZero(N0))
8668     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8669
8670   EVT SrcVT = N0.getValueType();
8671   EVT DstVT = Op.getValueType();
8672   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8673     return LowerUINT_TO_FP_i64(Op, DAG);
8674   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8675     return LowerUINT_TO_FP_i32(Op, DAG);
8676   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8677     return SDValue();
8678
8679   // Make a 64-bit buffer, and use it to build an FILD.
8680   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8681   if (SrcVT == MVT::i32) {
8682     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8683     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8684                                      getPointerTy(), StackSlot, WordOff);
8685     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8686                                   StackSlot, MachinePointerInfo(),
8687                                   false, false, 0);
8688     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8689                                   OffsetSlot, MachinePointerInfo(),
8690                                   false, false, 0);
8691     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8692     return Fild;
8693   }
8694
8695   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8696   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8697                                StackSlot, MachinePointerInfo(),
8698                                false, false, 0);
8699   // For i64 source, we need to add the appropriate power of 2 if the input
8700   // was negative.  This is the same as the optimization in
8701   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8702   // we must be careful to do the computation in x87 extended precision, not
8703   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8704   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8705   MachineMemOperand *MMO =
8706     DAG.getMachineFunction()
8707     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8708                           MachineMemOperand::MOLoad, 8, 8);
8709
8710   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8711   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8712   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8713                                          array_lengthof(Ops), MVT::i64, MMO);
8714
8715   APInt FF(32, 0x5F800000ULL);
8716
8717   // Check whether the sign bit is set.
8718   SDValue SignSet = DAG.getSetCC(dl,
8719                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8720                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8721                                  ISD::SETLT);
8722
8723   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8724   SDValue FudgePtr = DAG.getConstantPool(
8725                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8726                                          getPointerTy());
8727
8728   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8729   SDValue Zero = DAG.getIntPtrConstant(0);
8730   SDValue Four = DAG.getIntPtrConstant(4);
8731   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8732                                Zero, Four);
8733   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8734
8735   // Load the value out, extending it from f32 to f80.
8736   // FIXME: Avoid the extend by constructing the right constant pool?
8737   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8738                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8739                                  MVT::f32, false, false, 4);
8740   // Extend everything to 80 bits to force it to be done on x87.
8741   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8742   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8743 }
8744
8745 std::pair<SDValue,SDValue>
8746 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8747                                     bool IsSigned, bool IsReplace) const {
8748   SDLoc DL(Op);
8749
8750   EVT DstTy = Op.getValueType();
8751
8752   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8753     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8754     DstTy = MVT::i64;
8755   }
8756
8757   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8758          DstTy.getSimpleVT() >= MVT::i16 &&
8759          "Unknown FP_TO_INT to lower!");
8760
8761   // These are really Legal.
8762   if (DstTy == MVT::i32 &&
8763       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8764     return std::make_pair(SDValue(), SDValue());
8765   if (Subtarget->is64Bit() &&
8766       DstTy == MVT::i64 &&
8767       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8768     return std::make_pair(SDValue(), SDValue());
8769
8770   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8771   // stack slot, or into the FTOL runtime function.
8772   MachineFunction &MF = DAG.getMachineFunction();
8773   unsigned MemSize = DstTy.getSizeInBits()/8;
8774   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8775   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8776
8777   unsigned Opc;
8778   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8779     Opc = X86ISD::WIN_FTOL;
8780   else
8781     switch (DstTy.getSimpleVT().SimpleTy) {
8782     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8783     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8784     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8785     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8786     }
8787
8788   SDValue Chain = DAG.getEntryNode();
8789   SDValue Value = Op.getOperand(0);
8790   EVT TheVT = Op.getOperand(0).getValueType();
8791   // FIXME This causes a redundant load/store if the SSE-class value is already
8792   // in memory, such as if it is on the callstack.
8793   if (isScalarFPTypeInSSEReg(TheVT)) {
8794     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8795     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8796                          MachinePointerInfo::getFixedStack(SSFI),
8797                          false, false, 0);
8798     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8799     SDValue Ops[] = {
8800       Chain, StackSlot, DAG.getValueType(TheVT)
8801     };
8802
8803     MachineMemOperand *MMO =
8804       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8805                               MachineMemOperand::MOLoad, MemSize, MemSize);
8806     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8807                                     array_lengthof(Ops), DstTy, MMO);
8808     Chain = Value.getValue(1);
8809     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8810     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8811   }
8812
8813   MachineMemOperand *MMO =
8814     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8815                             MachineMemOperand::MOStore, MemSize, MemSize);
8816
8817   if (Opc != X86ISD::WIN_FTOL) {
8818     // Build the FP_TO_INT*_IN_MEM
8819     SDValue Ops[] = { Chain, Value, StackSlot };
8820     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8821                                            Ops, array_lengthof(Ops), DstTy,
8822                                            MMO);
8823     return std::make_pair(FIST, StackSlot);
8824   } else {
8825     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8826       DAG.getVTList(MVT::Other, MVT::Glue),
8827       Chain, Value);
8828     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8829       MVT::i32, ftol.getValue(1));
8830     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8831       MVT::i32, eax.getValue(2));
8832     SDValue Ops[] = { eax, edx };
8833     SDValue pair = IsReplace
8834       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8835       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8836     return std::make_pair(pair, SDValue());
8837   }
8838 }
8839
8840 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8841                               const X86Subtarget *Subtarget) {
8842   MVT VT = Op->getSimpleValueType(0);
8843   SDValue In = Op->getOperand(0);
8844   MVT InVT = In.getSimpleValueType();
8845   SDLoc dl(Op);
8846
8847   // Optimize vectors in AVX mode:
8848   //
8849   //   v8i16 -> v8i32
8850   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8851   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8852   //   Concat upper and lower parts.
8853   //
8854   //   v4i32 -> v4i64
8855   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8856   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8857   //   Concat upper and lower parts.
8858   //
8859
8860   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8861       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8862     return SDValue();
8863
8864   if (Subtarget->hasInt256())
8865     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8866
8867   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8868   SDValue Undef = DAG.getUNDEF(InVT);
8869   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8870   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8871   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8872
8873   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8874                              VT.getVectorNumElements()/2);
8875
8876   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8877   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8878
8879   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8880 }
8881
8882 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
8883                                         SelectionDAG &DAG) {
8884   MVT VT = Op->getValueType(0).getSimpleVT();
8885   SDValue In = Op->getOperand(0);
8886   MVT InVT = In.getValueType().getSimpleVT();
8887   SDLoc DL(Op);
8888   unsigned int NumElts = VT.getVectorNumElements();
8889   if (NumElts != 8 && NumElts != 16)
8890     return SDValue();
8891
8892   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
8893     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8894
8895   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
8896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8897   // Now we have only mask extension
8898   assert(InVT.getVectorElementType() == MVT::i1);
8899   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
8900   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
8901   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
8902   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
8903   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
8904                            MachinePointerInfo::getConstantPool(),
8905                            false, false, false, Alignment);
8906
8907   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
8908   if (VT.is512BitVector())
8909     return Brcst;
8910   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
8911 }
8912
8913 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
8914                                SelectionDAG &DAG) {
8915   if (Subtarget->hasFp256()) {
8916     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8917     if (Res.getNode())
8918       return Res;
8919   }
8920
8921   return SDValue();
8922 }
8923
8924 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
8925                                 SelectionDAG &DAG) {
8926   SDLoc DL(Op);
8927   MVT VT = Op.getSimpleValueType();
8928   SDValue In = Op.getOperand(0);
8929   MVT SVT = In.getSimpleValueType();
8930
8931   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
8932     return LowerZERO_EXTEND_AVX512(Op, DAG);
8933
8934   if (Subtarget->hasFp256()) {
8935     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8936     if (Res.getNode())
8937       return Res;
8938   }
8939
8940   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8941       VT.getVectorNumElements() != SVT.getVectorNumElements())
8942     return SDValue();
8943
8944   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8945
8946   // AVX2 has better support of integer extending.
8947   if (Subtarget->hasInt256())
8948     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8949
8950   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8951   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8952   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8953                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8954                                                 DAG.getUNDEF(MVT::v8i16),
8955                                                 &Mask[0]));
8956
8957   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8958 }
8959
8960 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8961   SDLoc DL(Op);
8962   MVT VT = Op.getSimpleValueType();  
8963   SDValue In = Op.getOperand(0);
8964   MVT InVT = In.getSimpleValueType();
8965   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
8966          "Invalid TRUNCATE operation");
8967
8968   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
8969     if (VT.getVectorElementType().getSizeInBits() >=8)
8970       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
8971
8972     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
8973     unsigned NumElts = InVT.getVectorNumElements();
8974     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
8975     if (InVT.getSizeInBits() < 512) {
8976       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
8977       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
8978       InVT = ExtVT;
8979     }
8980     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
8981     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
8982     SDValue CP = DAG.getConstantPool(C, getPointerTy());
8983     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
8984     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
8985                            MachinePointerInfo::getConstantPool(),
8986                            false, false, false, Alignment);
8987     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
8988     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
8989     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
8990   }
8991
8992   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
8993     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8994     if (Subtarget->hasInt256()) {
8995       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8996       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8997       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8998                                 ShufMask);
8999       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9000                          DAG.getIntPtrConstant(0));
9001     }
9002
9003     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9004     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9005                                DAG.getIntPtrConstant(0));
9006     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9007                                DAG.getIntPtrConstant(2));
9008
9009     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9010     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9011
9012     // The PSHUFD mask:
9013     static const int ShufMask1[] = {0, 2, 0, 0};
9014     SDValue Undef = DAG.getUNDEF(VT);
9015     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9016     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9017
9018     // The MOVLHPS mask:
9019     static const int ShufMask2[] = {0, 1, 4, 5};
9020     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9021   }
9022
9023   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9024     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9025     if (Subtarget->hasInt256()) {
9026       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9027
9028       SmallVector<SDValue,32> pshufbMask;
9029       for (unsigned i = 0; i < 2; ++i) {
9030         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9031         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9032         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9033         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9034         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9035         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9036         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9037         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9038         for (unsigned j = 0; j < 8; ++j)
9039           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9040       }
9041       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9042                                &pshufbMask[0], 32);
9043       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9044       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9045
9046       static const int ShufMask[] = {0,  2,  -1,  -1};
9047       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9048                                 &ShufMask[0]);
9049       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9050                        DAG.getIntPtrConstant(0));
9051       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9052     }
9053
9054     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9055                                DAG.getIntPtrConstant(0));
9056
9057     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9058                                DAG.getIntPtrConstant(4));
9059
9060     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9061     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9062
9063     // The PSHUFB mask:
9064     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9065                                    -1, -1, -1, -1, -1, -1, -1, -1};
9066
9067     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9068     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9069     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9070
9071     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9072     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9073
9074     // The MOVLHPS Mask:
9075     static const int ShufMask2[] = {0, 1, 4, 5};
9076     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9077     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9078   }
9079
9080   // Handle truncation of V256 to V128 using shuffles.
9081   if (!VT.is128BitVector() || !InVT.is256BitVector())
9082     return SDValue();
9083
9084   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9085
9086   unsigned NumElems = VT.getVectorNumElements();
9087   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9088                              NumElems * 2);
9089
9090   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9091   // Prepare truncation shuffle mask
9092   for (unsigned i = 0; i != NumElems; ++i)
9093     MaskVec[i] = i * 2;
9094   SDValue V = DAG.getVectorShuffle(NVT, DL,
9095                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9096                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9097   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9098                      DAG.getIntPtrConstant(0));
9099 }
9100
9101 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9102                                            SelectionDAG &DAG) const {
9103   MVT VT = Op.getSimpleValueType();
9104   if (VT.isVector()) {
9105     if (VT == MVT::v8i16)
9106       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9107                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9108                                      MVT::v8i32, Op.getOperand(0)));
9109     return SDValue();
9110   }
9111
9112   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9113     /*IsSigned=*/ true, /*IsReplace=*/ false);
9114   SDValue FIST = Vals.first, StackSlot = Vals.second;
9115   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9116   if (FIST.getNode() == 0) return Op;
9117
9118   if (StackSlot.getNode())
9119     // Load the result.
9120     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9121                        FIST, StackSlot, MachinePointerInfo(),
9122                        false, false, false, 0);
9123
9124   // The node is the result.
9125   return FIST;
9126 }
9127
9128 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9129                                            SelectionDAG &DAG) const {
9130   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9131     /*IsSigned=*/ false, /*IsReplace=*/ false);
9132   SDValue FIST = Vals.first, StackSlot = Vals.second;
9133   assert(FIST.getNode() && "Unexpected failure");
9134
9135   if (StackSlot.getNode())
9136     // Load the result.
9137     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9138                        FIST, StackSlot, MachinePointerInfo(),
9139                        false, false, false, 0);
9140
9141   // The node is the result.
9142   return FIST;
9143 }
9144
9145 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9146   SDLoc DL(Op);
9147   MVT VT = Op.getSimpleValueType();
9148   SDValue In = Op.getOperand(0);
9149   MVT SVT = In.getSimpleValueType();
9150
9151   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9152
9153   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9154                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9155                                  In, DAG.getUNDEF(SVT)));
9156 }
9157
9158 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9159   LLVMContext *Context = DAG.getContext();
9160   SDLoc dl(Op);
9161   MVT VT = Op.getSimpleValueType();
9162   MVT EltVT = VT;
9163   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9164   if (VT.isVector()) {
9165     EltVT = VT.getVectorElementType();
9166     NumElts = VT.getVectorNumElements();
9167   }
9168   Constant *C;
9169   if (EltVT == MVT::f64)
9170     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9171                                           APInt(64, ~(1ULL << 63))));
9172   else
9173     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9174                                           APInt(32, ~(1U << 31))));
9175   C = ConstantVector::getSplat(NumElts, C);
9176   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9177   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9178   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9179                              MachinePointerInfo::getConstantPool(),
9180                              false, false, false, Alignment);
9181   if (VT.isVector()) {
9182     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9183     return DAG.getNode(ISD::BITCAST, dl, VT,
9184                        DAG.getNode(ISD::AND, dl, ANDVT,
9185                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9186                                                Op.getOperand(0)),
9187                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9188   }
9189   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9190 }
9191
9192 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9193   LLVMContext *Context = DAG.getContext();
9194   SDLoc dl(Op);
9195   MVT VT = Op.getSimpleValueType();
9196   MVT EltVT = VT;
9197   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9198   if (VT.isVector()) {
9199     EltVT = VT.getVectorElementType();
9200     NumElts = VT.getVectorNumElements();
9201   }
9202   Constant *C;
9203   if (EltVT == MVT::f64)
9204     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9205                                           APInt(64, 1ULL << 63)));
9206   else
9207     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9208                                           APInt(32, 1U << 31)));
9209   C = ConstantVector::getSplat(NumElts, C);
9210   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9211   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9212   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9213                              MachinePointerInfo::getConstantPool(),
9214                              false, false, false, Alignment);
9215   if (VT.isVector()) {
9216     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9217     return DAG.getNode(ISD::BITCAST, dl, VT,
9218                        DAG.getNode(ISD::XOR, dl, XORVT,
9219                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9220                                                Op.getOperand(0)),
9221                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9222   }
9223
9224   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9225 }
9226
9227 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9228   LLVMContext *Context = DAG.getContext();
9229   SDValue Op0 = Op.getOperand(0);
9230   SDValue Op1 = Op.getOperand(1);
9231   SDLoc dl(Op);
9232   MVT VT = Op.getSimpleValueType();
9233   MVT SrcVT = Op1.getSimpleValueType();
9234
9235   // If second operand is smaller, extend it first.
9236   if (SrcVT.bitsLT(VT)) {
9237     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9238     SrcVT = VT;
9239   }
9240   // And if it is bigger, shrink it first.
9241   if (SrcVT.bitsGT(VT)) {
9242     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9243     SrcVT = VT;
9244   }
9245
9246   // At this point the operands and the result should have the same
9247   // type, and that won't be f80 since that is not custom lowered.
9248
9249   // First get the sign bit of second operand.
9250   SmallVector<Constant*,4> CV;
9251   if (SrcVT == MVT::f64) {
9252     const fltSemantics &Sem = APFloat::IEEEdouble;
9253     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9254     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9255   } else {
9256     const fltSemantics &Sem = APFloat::IEEEsingle;
9257     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9258     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9259     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9260     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9261   }
9262   Constant *C = ConstantVector::get(CV);
9263   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9264   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9265                               MachinePointerInfo::getConstantPool(),
9266                               false, false, false, 16);
9267   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9268
9269   // Shift sign bit right or left if the two operands have different types.
9270   if (SrcVT.bitsGT(VT)) {
9271     // Op0 is MVT::f32, Op1 is MVT::f64.
9272     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9273     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9274                           DAG.getConstant(32, MVT::i32));
9275     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9276     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9277                           DAG.getIntPtrConstant(0));
9278   }
9279
9280   // Clear first operand sign bit.
9281   CV.clear();
9282   if (VT == MVT::f64) {
9283     const fltSemantics &Sem = APFloat::IEEEdouble;
9284     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9285                                                    APInt(64, ~(1ULL << 63)))));
9286     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9287   } else {
9288     const fltSemantics &Sem = APFloat::IEEEsingle;
9289     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9290                                                    APInt(32, ~(1U << 31)))));
9291     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9292     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9293     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9294   }
9295   C = ConstantVector::get(CV);
9296   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9297   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9298                               MachinePointerInfo::getConstantPool(),
9299                               false, false, false, 16);
9300   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9301
9302   // Or the value with the sign bit.
9303   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9304 }
9305
9306 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9307   SDValue N0 = Op.getOperand(0);
9308   SDLoc dl(Op);
9309   MVT VT = Op.getSimpleValueType();
9310
9311   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9312   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9313                                   DAG.getConstant(1, VT));
9314   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9315 }
9316
9317 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9318 //
9319 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9320                                       SelectionDAG &DAG) {
9321   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9322
9323   if (!Subtarget->hasSSE41())
9324     return SDValue();
9325
9326   if (!Op->hasOneUse())
9327     return SDValue();
9328
9329   SDNode *N = Op.getNode();
9330   SDLoc DL(N);
9331
9332   SmallVector<SDValue, 8> Opnds;
9333   DenseMap<SDValue, unsigned> VecInMap;
9334   EVT VT = MVT::Other;
9335
9336   // Recognize a special case where a vector is casted into wide integer to
9337   // test all 0s.
9338   Opnds.push_back(N->getOperand(0));
9339   Opnds.push_back(N->getOperand(1));
9340
9341   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9342     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9343     // BFS traverse all OR'd operands.
9344     if (I->getOpcode() == ISD::OR) {
9345       Opnds.push_back(I->getOperand(0));
9346       Opnds.push_back(I->getOperand(1));
9347       // Re-evaluate the number of nodes to be traversed.
9348       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9349       continue;
9350     }
9351
9352     // Quit if a non-EXTRACT_VECTOR_ELT
9353     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9354       return SDValue();
9355
9356     // Quit if without a constant index.
9357     SDValue Idx = I->getOperand(1);
9358     if (!isa<ConstantSDNode>(Idx))
9359       return SDValue();
9360
9361     SDValue ExtractedFromVec = I->getOperand(0);
9362     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9363     if (M == VecInMap.end()) {
9364       VT = ExtractedFromVec.getValueType();
9365       // Quit if not 128/256-bit vector.
9366       if (!VT.is128BitVector() && !VT.is256BitVector())
9367         return SDValue();
9368       // Quit if not the same type.
9369       if (VecInMap.begin() != VecInMap.end() &&
9370           VT != VecInMap.begin()->first.getValueType())
9371         return SDValue();
9372       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9373     }
9374     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9375   }
9376
9377   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9378          "Not extracted from 128-/256-bit vector.");
9379
9380   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9381   SmallVector<SDValue, 8> VecIns;
9382
9383   for (DenseMap<SDValue, unsigned>::const_iterator
9384         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9385     // Quit if not all elements are used.
9386     if (I->second != FullMask)
9387       return SDValue();
9388     VecIns.push_back(I->first);
9389   }
9390
9391   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9392
9393   // Cast all vectors into TestVT for PTEST.
9394   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9395     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9396
9397   // If more than one full vectors are evaluated, OR them first before PTEST.
9398   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9399     // Each iteration will OR 2 nodes and append the result until there is only
9400     // 1 node left, i.e. the final OR'd value of all vectors.
9401     SDValue LHS = VecIns[Slot];
9402     SDValue RHS = VecIns[Slot + 1];
9403     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9404   }
9405
9406   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9407                      VecIns.back(), VecIns.back());
9408 }
9409
9410 /// Emit nodes that will be selected as "test Op0,Op0", or something
9411 /// equivalent.
9412 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9413                                     SelectionDAG &DAG) const {
9414   SDLoc dl(Op);
9415
9416   // CF and OF aren't always set the way we want. Determine which
9417   // of these we need.
9418   bool NeedCF = false;
9419   bool NeedOF = false;
9420   switch (X86CC) {
9421   default: break;
9422   case X86::COND_A: case X86::COND_AE:
9423   case X86::COND_B: case X86::COND_BE:
9424     NeedCF = true;
9425     break;
9426   case X86::COND_G: case X86::COND_GE:
9427   case X86::COND_L: case X86::COND_LE:
9428   case X86::COND_O: case X86::COND_NO:
9429     NeedOF = true;
9430     break;
9431   }
9432
9433   // See if we can use the EFLAGS value from the operand instead of
9434   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9435   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9436   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9437     // Emit a CMP with 0, which is the TEST pattern.
9438     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9439                        DAG.getConstant(0, Op.getValueType()));
9440
9441   unsigned Opcode = 0;
9442   unsigned NumOperands = 0;
9443
9444   // Truncate operations may prevent the merge of the SETCC instruction
9445   // and the arithmetic intruction before it. Attempt to truncate the operands
9446   // of the arithmetic instruction and use a reduced bit-width instruction.
9447   bool NeedTruncation = false;
9448   SDValue ArithOp = Op;
9449   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9450     SDValue Arith = Op->getOperand(0);
9451     // Both the trunc and the arithmetic op need to have one user each.
9452     if (Arith->hasOneUse())
9453       switch (Arith.getOpcode()) {
9454         default: break;
9455         case ISD::ADD:
9456         case ISD::SUB:
9457         case ISD::AND:
9458         case ISD::OR:
9459         case ISD::XOR: {
9460           NeedTruncation = true;
9461           ArithOp = Arith;
9462         }
9463       }
9464   }
9465
9466   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9467   // which may be the result of a CAST.  We use the variable 'Op', which is the
9468   // non-casted variable when we check for possible users.
9469   switch (ArithOp.getOpcode()) {
9470   case ISD::ADD:
9471     // Due to an isel shortcoming, be conservative if this add is likely to be
9472     // selected as part of a load-modify-store instruction. When the root node
9473     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9474     // uses of other nodes in the match, such as the ADD in this case. This
9475     // leads to the ADD being left around and reselected, with the result being
9476     // two adds in the output.  Alas, even if none our users are stores, that
9477     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9478     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9479     // climbing the DAG back to the root, and it doesn't seem to be worth the
9480     // effort.
9481     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9482          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9483       if (UI->getOpcode() != ISD::CopyToReg &&
9484           UI->getOpcode() != ISD::SETCC &&
9485           UI->getOpcode() != ISD::STORE)
9486         goto default_case;
9487
9488     if (ConstantSDNode *C =
9489         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9490       // An add of one will be selected as an INC.
9491       if (C->getAPIntValue() == 1) {
9492         Opcode = X86ISD::INC;
9493         NumOperands = 1;
9494         break;
9495       }
9496
9497       // An add of negative one (subtract of one) will be selected as a DEC.
9498       if (C->getAPIntValue().isAllOnesValue()) {
9499         Opcode = X86ISD::DEC;
9500         NumOperands = 1;
9501         break;
9502       }
9503     }
9504
9505     // Otherwise use a regular EFLAGS-setting add.
9506     Opcode = X86ISD::ADD;
9507     NumOperands = 2;
9508     break;
9509   case ISD::AND: {
9510     // If the primary and result isn't used, don't bother using X86ISD::AND,
9511     // because a TEST instruction will be better.
9512     bool NonFlagUse = false;
9513     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9514            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9515       SDNode *User = *UI;
9516       unsigned UOpNo = UI.getOperandNo();
9517       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9518         // Look pass truncate.
9519         UOpNo = User->use_begin().getOperandNo();
9520         User = *User->use_begin();
9521       }
9522
9523       if (User->getOpcode() != ISD::BRCOND &&
9524           User->getOpcode() != ISD::SETCC &&
9525           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9526         NonFlagUse = true;
9527         break;
9528       }
9529     }
9530
9531     if (!NonFlagUse)
9532       break;
9533   }
9534     // FALL THROUGH
9535   case ISD::SUB:
9536   case ISD::OR:
9537   case ISD::XOR:
9538     // Due to the ISEL shortcoming noted above, be conservative if this op is
9539     // likely to be selected as part of a load-modify-store instruction.
9540     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9541            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9542       if (UI->getOpcode() == ISD::STORE)
9543         goto default_case;
9544
9545     // Otherwise use a regular EFLAGS-setting instruction.
9546     switch (ArithOp.getOpcode()) {
9547     default: llvm_unreachable("unexpected operator!");
9548     case ISD::SUB: Opcode = X86ISD::SUB; break;
9549     case ISD::XOR: Opcode = X86ISD::XOR; break;
9550     case ISD::AND: Opcode = X86ISD::AND; break;
9551     case ISD::OR: {
9552       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9553         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9554         if (EFLAGS.getNode())
9555           return EFLAGS;
9556       }
9557       Opcode = X86ISD::OR;
9558       break;
9559     }
9560     }
9561
9562     NumOperands = 2;
9563     break;
9564   case X86ISD::ADD:
9565   case X86ISD::SUB:
9566   case X86ISD::INC:
9567   case X86ISD::DEC:
9568   case X86ISD::OR:
9569   case X86ISD::XOR:
9570   case X86ISD::AND:
9571     return SDValue(Op.getNode(), 1);
9572   default:
9573   default_case:
9574     break;
9575   }
9576
9577   // If we found that truncation is beneficial, perform the truncation and
9578   // update 'Op'.
9579   if (NeedTruncation) {
9580     EVT VT = Op.getValueType();
9581     SDValue WideVal = Op->getOperand(0);
9582     EVT WideVT = WideVal.getValueType();
9583     unsigned ConvertedOp = 0;
9584     // Use a target machine opcode to prevent further DAGCombine
9585     // optimizations that may separate the arithmetic operations
9586     // from the setcc node.
9587     switch (WideVal.getOpcode()) {
9588       default: break;
9589       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9590       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9591       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9592       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9593       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9594     }
9595
9596     if (ConvertedOp) {
9597       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9598       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9599         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9600         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9601         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9602       }
9603     }
9604   }
9605
9606   if (Opcode == 0)
9607     // Emit a CMP with 0, which is the TEST pattern.
9608     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9609                        DAG.getConstant(0, Op.getValueType()));
9610
9611   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9612   SmallVector<SDValue, 4> Ops;
9613   for (unsigned i = 0; i != NumOperands; ++i)
9614     Ops.push_back(Op.getOperand(i));
9615
9616   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9617   DAG.ReplaceAllUsesWith(Op, New);
9618   return SDValue(New.getNode(), 1);
9619 }
9620
9621 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9622 /// equivalent.
9623 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9624                                    SelectionDAG &DAG) const {
9625   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9626     if (C->getAPIntValue() == 0)
9627       return EmitTest(Op0, X86CC, DAG);
9628
9629   SDLoc dl(Op0);
9630   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9631        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9632     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9633     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9634     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9635                               Op0, Op1);
9636     return SDValue(Sub.getNode(), 1);
9637   }
9638   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9639 }
9640
9641 /// Convert a comparison if required by the subtarget.
9642 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9643                                                  SelectionDAG &DAG) const {
9644   // If the subtarget does not support the FUCOMI instruction, floating-point
9645   // comparisons have to be converted.
9646   if (Subtarget->hasCMov() ||
9647       Cmp.getOpcode() != X86ISD::CMP ||
9648       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9649       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9650     return Cmp;
9651
9652   // The instruction selector will select an FUCOM instruction instead of
9653   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9654   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9655   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9656   SDLoc dl(Cmp);
9657   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9658   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9659   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9660                             DAG.getConstant(8, MVT::i8));
9661   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9662   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9663 }
9664
9665 static bool isAllOnes(SDValue V) {
9666   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9667   return C && C->isAllOnesValue();
9668 }
9669
9670 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9671 /// if it's possible.
9672 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9673                                      SDLoc dl, SelectionDAG &DAG) const {
9674   SDValue Op0 = And.getOperand(0);
9675   SDValue Op1 = And.getOperand(1);
9676   if (Op0.getOpcode() == ISD::TRUNCATE)
9677     Op0 = Op0.getOperand(0);
9678   if (Op1.getOpcode() == ISD::TRUNCATE)
9679     Op1 = Op1.getOperand(0);
9680
9681   SDValue LHS, RHS;
9682   if (Op1.getOpcode() == ISD::SHL)
9683     std::swap(Op0, Op1);
9684   if (Op0.getOpcode() == ISD::SHL) {
9685     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9686       if (And00C->getZExtValue() == 1) {
9687         // If we looked past a truncate, check that it's only truncating away
9688         // known zeros.
9689         unsigned BitWidth = Op0.getValueSizeInBits();
9690         unsigned AndBitWidth = And.getValueSizeInBits();
9691         if (BitWidth > AndBitWidth) {
9692           APInt Zeros, Ones;
9693           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9694           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9695             return SDValue();
9696         }
9697         LHS = Op1;
9698         RHS = Op0.getOperand(1);
9699       }
9700   } else if (Op1.getOpcode() == ISD::Constant) {
9701     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9702     uint64_t AndRHSVal = AndRHS->getZExtValue();
9703     SDValue AndLHS = Op0;
9704
9705     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9706       LHS = AndLHS.getOperand(0);
9707       RHS = AndLHS.getOperand(1);
9708     }
9709
9710     // Use BT if the immediate can't be encoded in a TEST instruction.
9711     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9712       LHS = AndLHS;
9713       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9714     }
9715   }
9716
9717   if (LHS.getNode()) {
9718     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9719     // instruction.  Since the shift amount is in-range-or-undefined, we know
9720     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9721     // the encoding for the i16 version is larger than the i32 version.
9722     // Also promote i16 to i32 for performance / code size reason.
9723     if (LHS.getValueType() == MVT::i8 ||
9724         LHS.getValueType() == MVT::i16)
9725       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9726
9727     // If the operand types disagree, extend the shift amount to match.  Since
9728     // BT ignores high bits (like shifts) we can use anyextend.
9729     if (LHS.getValueType() != RHS.getValueType())
9730       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9731
9732     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9733     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9734     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9735                        DAG.getConstant(Cond, MVT::i8), BT);
9736   }
9737
9738   return SDValue();
9739 }
9740
9741 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9742 /// mask CMPs.
9743 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9744                               SDValue &Op1) {
9745   unsigned SSECC;
9746   bool Swap = false;
9747
9748   // SSE Condition code mapping:
9749   //  0 - EQ
9750   //  1 - LT
9751   //  2 - LE
9752   //  3 - UNORD
9753   //  4 - NEQ
9754   //  5 - NLT
9755   //  6 - NLE
9756   //  7 - ORD
9757   switch (SetCCOpcode) {
9758   default: llvm_unreachable("Unexpected SETCC condition");
9759   case ISD::SETOEQ:
9760   case ISD::SETEQ:  SSECC = 0; break;
9761   case ISD::SETOGT:
9762   case ISD::SETGT:  Swap = true; // Fallthrough
9763   case ISD::SETLT:
9764   case ISD::SETOLT: SSECC = 1; break;
9765   case ISD::SETOGE:
9766   case ISD::SETGE:  Swap = true; // Fallthrough
9767   case ISD::SETLE:
9768   case ISD::SETOLE: SSECC = 2; break;
9769   case ISD::SETUO:  SSECC = 3; break;
9770   case ISD::SETUNE:
9771   case ISD::SETNE:  SSECC = 4; break;
9772   case ISD::SETULE: Swap = true; // Fallthrough
9773   case ISD::SETUGE: SSECC = 5; break;
9774   case ISD::SETULT: Swap = true; // Fallthrough
9775   case ISD::SETUGT: SSECC = 6; break;
9776   case ISD::SETO:   SSECC = 7; break;
9777   case ISD::SETUEQ:
9778   case ISD::SETONE: SSECC = 8; break;
9779   }
9780   if (Swap)
9781     std::swap(Op0, Op1);
9782
9783   return SSECC;
9784 }
9785
9786 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9787 // ones, and then concatenate the result back.
9788 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9789   MVT VT = Op.getSimpleValueType();
9790
9791   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9792          "Unsupported value type for operation");
9793
9794   unsigned NumElems = VT.getVectorNumElements();
9795   SDLoc dl(Op);
9796   SDValue CC = Op.getOperand(2);
9797
9798   // Extract the LHS vectors
9799   SDValue LHS = Op.getOperand(0);
9800   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9801   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9802
9803   // Extract the RHS vectors
9804   SDValue RHS = Op.getOperand(1);
9805   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9806   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9807
9808   // Issue the operation on the smaller types and concatenate the result back
9809   MVT EltVT = VT.getVectorElementType();
9810   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9811   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9812                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9813                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9814 }
9815
9816 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9817   SDValue Cond;
9818   SDValue Op0 = Op.getOperand(0);
9819   SDValue Op1 = Op.getOperand(1);
9820   SDValue CC = Op.getOperand(2);
9821   MVT VT = Op.getSimpleValueType();
9822
9823   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9824          Op.getValueType().getScalarType() == MVT::i1 &&
9825          "Cannot set masked compare for this operation");
9826
9827   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9828   SDLoc dl(Op);
9829
9830   bool Unsigned = false;
9831   unsigned SSECC;
9832   switch (SetCCOpcode) {
9833   default: llvm_unreachable("Unexpected SETCC condition");
9834   case ISD::SETNE:  SSECC = 4; break;
9835   case ISD::SETEQ:  SSECC = 0; break;
9836   case ISD::SETUGT: Unsigned = true;
9837   case ISD::SETGT:  SSECC = 6; break; // NLE
9838   case ISD::SETULT: Unsigned = true;
9839   case ISD::SETLT:  SSECC = 1; break;
9840   case ISD::SETUGE: Unsigned = true;
9841   case ISD::SETGE:  SSECC = 5; break; // NLT
9842   case ISD::SETULE: Unsigned = true;
9843   case ISD::SETLE:  SSECC = 2; break;
9844   }
9845   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9846   return DAG.getNode(Opc, dl, VT, Op0, Op1,
9847                      DAG.getConstant(SSECC, MVT::i8));
9848
9849 }
9850
9851 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9852                            SelectionDAG &DAG) {
9853   SDValue Cond;
9854   SDValue Op0 = Op.getOperand(0);
9855   SDValue Op1 = Op.getOperand(1);
9856   SDValue CC = Op.getOperand(2);
9857   MVT VT = Op.getSimpleValueType();
9858   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9859   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
9860   SDLoc dl(Op);
9861
9862   if (isFP) {
9863 #ifndef NDEBUG
9864     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
9865     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9866 #endif
9867
9868     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9869     unsigned Opc = X86ISD::CMPP;
9870     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
9871       assert(VT.getVectorNumElements() <= 16);
9872       Opc = X86ISD::CMPM;
9873     }
9874     // In the two special cases we can't handle, emit two comparisons.
9875     if (SSECC == 8) {
9876       unsigned CC0, CC1;
9877       unsigned CombineOpc;
9878       if (SetCCOpcode == ISD::SETUEQ) {
9879         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9880       } else {
9881         assert(SetCCOpcode == ISD::SETONE);
9882         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9883       }
9884
9885       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9886                                  DAG.getConstant(CC0, MVT::i8));
9887       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9888                                  DAG.getConstant(CC1, MVT::i8));
9889       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9890     }
9891     // Handle all other FP comparisons here.
9892     return DAG.getNode(Opc, dl, VT, Op0, Op1,
9893                        DAG.getConstant(SSECC, MVT::i8));
9894   }
9895
9896   // Break 256-bit integer vector compare into smaller ones.
9897   if (VT.is256BitVector() && !Subtarget->hasInt256())
9898     return Lower256IntVSETCC(Op, DAG);
9899
9900   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
9901   EVT OpVT = Op1.getValueType();
9902   if (Subtarget->hasAVX512()) {
9903     if (Op1.getValueType().is512BitVector() ||
9904         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
9905       return LowerIntVSETCC_AVX512(Op, DAG);
9906
9907     // In AVX-512 architecture setcc returns mask with i1 elements,
9908     // But there is no compare instruction for i8 and i16 elements.
9909     // We are not talking about 512-bit operands in this case, these
9910     // types are illegal.
9911     if (MaskResult &&
9912         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
9913          OpVT.getVectorElementType().getSizeInBits() >= 8))
9914       return DAG.getNode(ISD::TRUNCATE, dl, VT,
9915                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
9916   }
9917
9918   // We are handling one of the integer comparisons here.  Since SSE only has
9919   // GT and EQ comparisons for integer, swapping operands and multiple
9920   // operations may be required for some comparisons.
9921   unsigned Opc;
9922   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9923   
9924   switch (SetCCOpcode) {
9925   default: llvm_unreachable("Unexpected SETCC condition");
9926   case ISD::SETNE:  Invert = true;
9927   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
9928   case ISD::SETLT:  Swap = true;
9929   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
9930   case ISD::SETGE:  Swap = true;
9931   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9932                     Invert = true; break;
9933   case ISD::SETULT: Swap = true;
9934   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9935                     FlipSigns = true; break;
9936   case ISD::SETUGE: Swap = true;
9937   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9938                     FlipSigns = true; Invert = true; break;
9939   }
9940   
9941   // Special case: Use min/max operations for SETULE/SETUGE
9942   MVT VET = VT.getVectorElementType();
9943   bool hasMinMax =
9944        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9945     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9946   
9947   if (hasMinMax) {
9948     switch (SetCCOpcode) {
9949     default: break;
9950     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9951     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9952     }
9953     
9954     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9955   }
9956   
9957   if (Swap)
9958     std::swap(Op0, Op1);
9959
9960   // Check that the operation in question is available (most are plain SSE2,
9961   // but PCMPGTQ and PCMPEQQ have different requirements).
9962   if (VT == MVT::v2i64) {
9963     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9964       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9965
9966       // First cast everything to the right type.
9967       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9968       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9969
9970       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9971       // bits of the inputs before performing those operations. The lower
9972       // compare is always unsigned.
9973       SDValue SB;
9974       if (FlipSigns) {
9975         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9976       } else {
9977         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9978         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9979         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9980                          Sign, Zero, Sign, Zero);
9981       }
9982       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9983       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9984
9985       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9986       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9987       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9988
9989       // Create masks for only the low parts/high parts of the 64 bit integers.
9990       static const int MaskHi[] = { 1, 1, 3, 3 };
9991       static const int MaskLo[] = { 0, 0, 2, 2 };
9992       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9993       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9994       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9995
9996       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9997       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9998
9999       if (Invert)
10000         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10001
10002       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10003     }
10004
10005     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10006       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10007       // pcmpeqd + pshufd + pand.
10008       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10009
10010       // First cast everything to the right type.
10011       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10012       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10013
10014       // Do the compare.
10015       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10016
10017       // Make sure the lower and upper halves are both all-ones.
10018       static const int Mask[] = { 1, 0, 3, 2 };
10019       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10020       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10021
10022       if (Invert)
10023         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10024
10025       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10026     }
10027   }
10028
10029   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10030   // bits of the inputs before performing those operations.
10031   if (FlipSigns) {
10032     EVT EltVT = VT.getVectorElementType();
10033     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10034     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10035     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10036   }
10037
10038   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10039
10040   // If the logical-not of the result is required, perform that now.
10041   if (Invert)
10042     Result = DAG.getNOT(dl, Result, VT);
10043   
10044   if (MinMax)
10045     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10046
10047   return Result;
10048 }
10049
10050 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10051
10052   MVT VT = Op.getSimpleValueType();
10053
10054   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10055
10056   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
10057   SDValue Op0 = Op.getOperand(0);
10058   SDValue Op1 = Op.getOperand(1);
10059   SDLoc dl(Op);
10060   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10061
10062   // Optimize to BT if possible.
10063   // Lower (X & (1 << N)) == 0 to BT(X, N).
10064   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10065   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10066   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10067       Op1.getOpcode() == ISD::Constant &&
10068       cast<ConstantSDNode>(Op1)->isNullValue() &&
10069       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10070     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10071     if (NewSetCC.getNode())
10072       return NewSetCC;
10073   }
10074
10075   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10076   // these.
10077   if (Op1.getOpcode() == ISD::Constant &&
10078       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10079        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10080       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10081
10082     // If the input is a setcc, then reuse the input setcc or use a new one with
10083     // the inverted condition.
10084     if (Op0.getOpcode() == X86ISD::SETCC) {
10085       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10086       bool Invert = (CC == ISD::SETNE) ^
10087         cast<ConstantSDNode>(Op1)->isNullValue();
10088       if (!Invert) return Op0;
10089
10090       CCode = X86::GetOppositeBranchCondition(CCode);
10091       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10092                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
10093     }
10094   }
10095
10096   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10097   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10098   if (X86CC == X86::COND_INVALID)
10099     return SDValue();
10100
10101   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10102   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10103   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10104                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10105 }
10106
10107 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10108 static bool isX86LogicalCmp(SDValue Op) {
10109   unsigned Opc = Op.getNode()->getOpcode();
10110   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10111       Opc == X86ISD::SAHF)
10112     return true;
10113   if (Op.getResNo() == 1 &&
10114       (Opc == X86ISD::ADD ||
10115        Opc == X86ISD::SUB ||
10116        Opc == X86ISD::ADC ||
10117        Opc == X86ISD::SBB ||
10118        Opc == X86ISD::SMUL ||
10119        Opc == X86ISD::UMUL ||
10120        Opc == X86ISD::INC ||
10121        Opc == X86ISD::DEC ||
10122        Opc == X86ISD::OR ||
10123        Opc == X86ISD::XOR ||
10124        Opc == X86ISD::AND))
10125     return true;
10126
10127   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10128     return true;
10129
10130   return false;
10131 }
10132
10133 static bool isZero(SDValue V) {
10134   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10135   return C && C->isNullValue();
10136 }
10137
10138 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10139   if (V.getOpcode() != ISD::TRUNCATE)
10140     return false;
10141
10142   SDValue VOp0 = V.getOperand(0);
10143   unsigned InBits = VOp0.getValueSizeInBits();
10144   unsigned Bits = V.getValueSizeInBits();
10145   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10146 }
10147
10148 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10149   bool addTest = true;
10150   SDValue Cond  = Op.getOperand(0);
10151   SDValue Op1 = Op.getOperand(1);
10152   SDValue Op2 = Op.getOperand(2);
10153   SDLoc DL(Op);
10154   EVT VT = Op1.getValueType();
10155   SDValue CC;
10156
10157   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10158   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10159   // sequence later on.
10160   if (Cond.getOpcode() == ISD::SETCC &&
10161       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10162        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10163       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10164     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10165     int SSECC = translateX86FSETCC(
10166         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10167
10168     if (SSECC != 8) {
10169       unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
10170       SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
10171                                 DAG.getConstant(SSECC, MVT::i8));
10172       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10173       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10174       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10175     }
10176   }
10177
10178   if (Cond.getOpcode() == ISD::SETCC) {
10179     SDValue NewCond = LowerSETCC(Cond, DAG);
10180     if (NewCond.getNode())
10181       Cond = NewCond;
10182   }
10183
10184   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10185   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10186   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10187   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10188   if (Cond.getOpcode() == X86ISD::SETCC &&
10189       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10190       isZero(Cond.getOperand(1).getOperand(1))) {
10191     SDValue Cmp = Cond.getOperand(1);
10192
10193     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10194
10195     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10196         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10197       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10198
10199       SDValue CmpOp0 = Cmp.getOperand(0);
10200       // Apply further optimizations for special cases
10201       // (select (x != 0), -1, 0) -> neg & sbb
10202       // (select (x == 0), 0, -1) -> neg & sbb
10203       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10204         if (YC->isNullValue() &&
10205             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10206           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10207           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10208                                     DAG.getConstant(0, CmpOp0.getValueType()),
10209                                     CmpOp0);
10210           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10211                                     DAG.getConstant(X86::COND_B, MVT::i8),
10212                                     SDValue(Neg.getNode(), 1));
10213           return Res;
10214         }
10215
10216       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10217                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10218       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10219
10220       SDValue Res =   // Res = 0 or -1.
10221         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10222                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10223
10224       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10225         Res = DAG.getNOT(DL, Res, Res.getValueType());
10226
10227       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10228       if (N2C == 0 || !N2C->isNullValue())
10229         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10230       return Res;
10231     }
10232   }
10233
10234   // Look past (and (setcc_carry (cmp ...)), 1).
10235   if (Cond.getOpcode() == ISD::AND &&
10236       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10237     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10238     if (C && C->getAPIntValue() == 1)
10239       Cond = Cond.getOperand(0);
10240   }
10241
10242   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10243   // setting operand in place of the X86ISD::SETCC.
10244   unsigned CondOpcode = Cond.getOpcode();
10245   if (CondOpcode == X86ISD::SETCC ||
10246       CondOpcode == X86ISD::SETCC_CARRY) {
10247     CC = Cond.getOperand(0);
10248
10249     SDValue Cmp = Cond.getOperand(1);
10250     unsigned Opc = Cmp.getOpcode();
10251     MVT VT = Op.getSimpleValueType();
10252
10253     bool IllegalFPCMov = false;
10254     if (VT.isFloatingPoint() && !VT.isVector() &&
10255         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10256       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10257
10258     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10259         Opc == X86ISD::BT) { // FIXME
10260       Cond = Cmp;
10261       addTest = false;
10262     }
10263   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10264              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10265              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10266               Cond.getOperand(0).getValueType() != MVT::i8)) {
10267     SDValue LHS = Cond.getOperand(0);
10268     SDValue RHS = Cond.getOperand(1);
10269     unsigned X86Opcode;
10270     unsigned X86Cond;
10271     SDVTList VTs;
10272     switch (CondOpcode) {
10273     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10274     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10275     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10276     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10277     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10278     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10279     default: llvm_unreachable("unexpected overflowing operator");
10280     }
10281     if (CondOpcode == ISD::UMULO)
10282       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10283                           MVT::i32);
10284     else
10285       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10286
10287     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10288
10289     if (CondOpcode == ISD::UMULO)
10290       Cond = X86Op.getValue(2);
10291     else
10292       Cond = X86Op.getValue(1);
10293
10294     CC = DAG.getConstant(X86Cond, MVT::i8);
10295     addTest = false;
10296   }
10297
10298   if (addTest) {
10299     // Look pass the truncate if the high bits are known zero.
10300     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10301         Cond = Cond.getOperand(0);
10302
10303     // We know the result of AND is compared against zero. Try to match
10304     // it to BT.
10305     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10306       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10307       if (NewSetCC.getNode()) {
10308         CC = NewSetCC.getOperand(0);
10309         Cond = NewSetCC.getOperand(1);
10310         addTest = false;
10311       }
10312     }
10313   }
10314
10315   if (addTest) {
10316     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10317     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10318   }
10319
10320   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10321   // a <  b ?  0 : -1 -> RES = setcc_carry
10322   // a >= b ? -1 :  0 -> RES = setcc_carry
10323   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10324   if (Cond.getOpcode() == X86ISD::SUB) {
10325     Cond = ConvertCmpIfNecessary(Cond, DAG);
10326     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10327
10328     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10329         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10330       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10331                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10332       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10333         return DAG.getNOT(DL, Res, Res.getValueType());
10334       return Res;
10335     }
10336   }
10337
10338   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10339   // widen the cmov and push the truncate through. This avoids introducing a new
10340   // branch during isel and doesn't add any extensions.
10341   if (Op.getValueType() == MVT::i8 &&
10342       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10343     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10344     if (T1.getValueType() == T2.getValueType() &&
10345         // Blacklist CopyFromReg to avoid partial register stalls.
10346         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10347       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10348       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10349       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10350     }
10351   }
10352
10353   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10354   // condition is true.
10355   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10356   SDValue Ops[] = { Op2, Op1, CC, Cond };
10357   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10358 }
10359
10360 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10361   MVT VT = Op->getSimpleValueType(0);
10362   SDValue In = Op->getOperand(0);
10363   MVT InVT = In.getSimpleValueType();
10364   SDLoc dl(Op);
10365
10366   unsigned int NumElts = VT.getVectorNumElements();
10367   if (NumElts != 8 && NumElts != 16)
10368     return SDValue();
10369
10370   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10371     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10372
10373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10374   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10375
10376   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10377   Constant *C = ConstantInt::get(*DAG.getContext(),
10378     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10379
10380   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10381   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10382   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10383                           MachinePointerInfo::getConstantPool(),
10384                           false, false, false, Alignment);
10385   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10386   if (VT.is512BitVector())
10387     return Brcst;
10388   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10389 }
10390
10391 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10392                                 SelectionDAG &DAG) {
10393   MVT VT = Op->getSimpleValueType(0);
10394   SDValue In = Op->getOperand(0);
10395   MVT InVT = In.getSimpleValueType();
10396   SDLoc dl(Op);
10397
10398   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10399     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10400
10401   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10402       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10403     return SDValue();
10404
10405   if (Subtarget->hasInt256())
10406     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10407
10408   // Optimize vectors in AVX mode
10409   // Sign extend  v8i16 to v8i32 and
10410   //              v4i32 to v4i64
10411   //
10412   // Divide input vector into two parts
10413   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10414   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10415   // concat the vectors to original VT
10416
10417   unsigned NumElems = InVT.getVectorNumElements();
10418   SDValue Undef = DAG.getUNDEF(InVT);
10419
10420   SmallVector<int,8> ShufMask1(NumElems, -1);
10421   for (unsigned i = 0; i != NumElems/2; ++i)
10422     ShufMask1[i] = i;
10423
10424   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10425
10426   SmallVector<int,8> ShufMask2(NumElems, -1);
10427   for (unsigned i = 0; i != NumElems/2; ++i)
10428     ShufMask2[i] = i + NumElems/2;
10429
10430   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10431
10432   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10433                                 VT.getVectorNumElements()/2);
10434
10435   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10436   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10437
10438   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10439 }
10440
10441 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10442 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10443 // from the AND / OR.
10444 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10445   Opc = Op.getOpcode();
10446   if (Opc != ISD::OR && Opc != ISD::AND)
10447     return false;
10448   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10449           Op.getOperand(0).hasOneUse() &&
10450           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10451           Op.getOperand(1).hasOneUse());
10452 }
10453
10454 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10455 // 1 and that the SETCC node has a single use.
10456 static bool isXor1OfSetCC(SDValue Op) {
10457   if (Op.getOpcode() != ISD::XOR)
10458     return false;
10459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10460   if (N1C && N1C->getAPIntValue() == 1) {
10461     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10462       Op.getOperand(0).hasOneUse();
10463   }
10464   return false;
10465 }
10466
10467 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10468   bool addTest = true;
10469   SDValue Chain = Op.getOperand(0);
10470   SDValue Cond  = Op.getOperand(1);
10471   SDValue Dest  = Op.getOperand(2);
10472   SDLoc dl(Op);
10473   SDValue CC;
10474   bool Inverted = false;
10475
10476   if (Cond.getOpcode() == ISD::SETCC) {
10477     // Check for setcc([su]{add,sub,mul}o == 0).
10478     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10479         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10480         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10481         Cond.getOperand(0).getResNo() == 1 &&
10482         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10483          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10484          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10485          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10486          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10487          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10488       Inverted = true;
10489       Cond = Cond.getOperand(0);
10490     } else {
10491       SDValue NewCond = LowerSETCC(Cond, DAG);
10492       if (NewCond.getNode())
10493         Cond = NewCond;
10494     }
10495   }
10496 #if 0
10497   // FIXME: LowerXALUO doesn't handle these!!
10498   else if (Cond.getOpcode() == X86ISD::ADD  ||
10499            Cond.getOpcode() == X86ISD::SUB  ||
10500            Cond.getOpcode() == X86ISD::SMUL ||
10501            Cond.getOpcode() == X86ISD::UMUL)
10502     Cond = LowerXALUO(Cond, DAG);
10503 #endif
10504
10505   // Look pass (and (setcc_carry (cmp ...)), 1).
10506   if (Cond.getOpcode() == ISD::AND &&
10507       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10508     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10509     if (C && C->getAPIntValue() == 1)
10510       Cond = Cond.getOperand(0);
10511   }
10512
10513   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10514   // setting operand in place of the X86ISD::SETCC.
10515   unsigned CondOpcode = Cond.getOpcode();
10516   if (CondOpcode == X86ISD::SETCC ||
10517       CondOpcode == X86ISD::SETCC_CARRY) {
10518     CC = Cond.getOperand(0);
10519
10520     SDValue Cmp = Cond.getOperand(1);
10521     unsigned Opc = Cmp.getOpcode();
10522     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10523     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10524       Cond = Cmp;
10525       addTest = false;
10526     } else {
10527       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10528       default: break;
10529       case X86::COND_O:
10530       case X86::COND_B:
10531         // These can only come from an arithmetic instruction with overflow,
10532         // e.g. SADDO, UADDO.
10533         Cond = Cond.getNode()->getOperand(1);
10534         addTest = false;
10535         break;
10536       }
10537     }
10538   }
10539   CondOpcode = Cond.getOpcode();
10540   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10541       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10542       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10543        Cond.getOperand(0).getValueType() != MVT::i8)) {
10544     SDValue LHS = Cond.getOperand(0);
10545     SDValue RHS = Cond.getOperand(1);
10546     unsigned X86Opcode;
10547     unsigned X86Cond;
10548     SDVTList VTs;
10549     switch (CondOpcode) {
10550     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10551     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10552     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10553     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10554     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10555     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10556     default: llvm_unreachable("unexpected overflowing operator");
10557     }
10558     if (Inverted)
10559       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10560     if (CondOpcode == ISD::UMULO)
10561       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10562                           MVT::i32);
10563     else
10564       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10565
10566     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10567
10568     if (CondOpcode == ISD::UMULO)
10569       Cond = X86Op.getValue(2);
10570     else
10571       Cond = X86Op.getValue(1);
10572
10573     CC = DAG.getConstant(X86Cond, MVT::i8);
10574     addTest = false;
10575   } else {
10576     unsigned CondOpc;
10577     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10578       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10579       if (CondOpc == ISD::OR) {
10580         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10581         // two branches instead of an explicit OR instruction with a
10582         // separate test.
10583         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10584             isX86LogicalCmp(Cmp)) {
10585           CC = Cond.getOperand(0).getOperand(0);
10586           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10587                               Chain, Dest, CC, Cmp);
10588           CC = Cond.getOperand(1).getOperand(0);
10589           Cond = Cmp;
10590           addTest = false;
10591         }
10592       } else { // ISD::AND
10593         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10594         // two branches instead of an explicit AND instruction with a
10595         // separate test. However, we only do this if this block doesn't
10596         // have a fall-through edge, because this requires an explicit
10597         // jmp when the condition is false.
10598         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10599             isX86LogicalCmp(Cmp) &&
10600             Op.getNode()->hasOneUse()) {
10601           X86::CondCode CCode =
10602             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10603           CCode = X86::GetOppositeBranchCondition(CCode);
10604           CC = DAG.getConstant(CCode, MVT::i8);
10605           SDNode *User = *Op.getNode()->use_begin();
10606           // Look for an unconditional branch following this conditional branch.
10607           // We need this because we need to reverse the successors in order
10608           // to implement FCMP_OEQ.
10609           if (User->getOpcode() == ISD::BR) {
10610             SDValue FalseBB = User->getOperand(1);
10611             SDNode *NewBR =
10612               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10613             assert(NewBR == User);
10614             (void)NewBR;
10615             Dest = FalseBB;
10616
10617             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10618                                 Chain, Dest, CC, Cmp);
10619             X86::CondCode CCode =
10620               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10621             CCode = X86::GetOppositeBranchCondition(CCode);
10622             CC = DAG.getConstant(CCode, MVT::i8);
10623             Cond = Cmp;
10624             addTest = false;
10625           }
10626         }
10627       }
10628     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10629       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10630       // It should be transformed during dag combiner except when the condition
10631       // is set by a arithmetics with overflow node.
10632       X86::CondCode CCode =
10633         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10634       CCode = X86::GetOppositeBranchCondition(CCode);
10635       CC = DAG.getConstant(CCode, MVT::i8);
10636       Cond = Cond.getOperand(0).getOperand(1);
10637       addTest = false;
10638     } else if (Cond.getOpcode() == ISD::SETCC &&
10639                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10640       // For FCMP_OEQ, we can emit
10641       // two branches instead of an explicit AND instruction with a
10642       // separate test. However, we only do this if this block doesn't
10643       // have a fall-through edge, because this requires an explicit
10644       // jmp when the condition is false.
10645       if (Op.getNode()->hasOneUse()) {
10646         SDNode *User = *Op.getNode()->use_begin();
10647         // Look for an unconditional branch following this conditional branch.
10648         // We need this because we need to reverse the successors in order
10649         // to implement FCMP_OEQ.
10650         if (User->getOpcode() == ISD::BR) {
10651           SDValue FalseBB = User->getOperand(1);
10652           SDNode *NewBR =
10653             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10654           assert(NewBR == User);
10655           (void)NewBR;
10656           Dest = FalseBB;
10657
10658           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10659                                     Cond.getOperand(0), Cond.getOperand(1));
10660           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10661           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10662           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10663                               Chain, Dest, CC, Cmp);
10664           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10665           Cond = Cmp;
10666           addTest = false;
10667         }
10668       }
10669     } else if (Cond.getOpcode() == ISD::SETCC &&
10670                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10671       // For FCMP_UNE, we can emit
10672       // two branches instead of an explicit AND instruction with a
10673       // separate test. However, we only do this if this block doesn't
10674       // have a fall-through edge, because this requires an explicit
10675       // jmp when the condition is false.
10676       if (Op.getNode()->hasOneUse()) {
10677         SDNode *User = *Op.getNode()->use_begin();
10678         // Look for an unconditional branch following this conditional branch.
10679         // We need this because we need to reverse the successors in order
10680         // to implement FCMP_UNE.
10681         if (User->getOpcode() == ISD::BR) {
10682           SDValue FalseBB = User->getOperand(1);
10683           SDNode *NewBR =
10684             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10685           assert(NewBR == User);
10686           (void)NewBR;
10687
10688           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10689                                     Cond.getOperand(0), Cond.getOperand(1));
10690           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10691           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10692           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10693                               Chain, Dest, CC, Cmp);
10694           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10695           Cond = Cmp;
10696           addTest = false;
10697           Dest = FalseBB;
10698         }
10699       }
10700     }
10701   }
10702
10703   if (addTest) {
10704     // Look pass the truncate if the high bits are known zero.
10705     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10706         Cond = Cond.getOperand(0);
10707
10708     // We know the result of AND is compared against zero. Try to match
10709     // it to BT.
10710     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10711       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10712       if (NewSetCC.getNode()) {
10713         CC = NewSetCC.getOperand(0);
10714         Cond = NewSetCC.getOperand(1);
10715         addTest = false;
10716       }
10717     }
10718   }
10719
10720   if (addTest) {
10721     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10722     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10723   }
10724   Cond = ConvertCmpIfNecessary(Cond, DAG);
10725   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10726                      Chain, Dest, CC, Cond);
10727 }
10728
10729 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10730 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10731 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10732 // that the guard pages used by the OS virtual memory manager are allocated in
10733 // correct sequence.
10734 SDValue
10735 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10736                                            SelectionDAG &DAG) const {
10737   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10738           getTargetMachine().Options.EnableSegmentedStacks) &&
10739          "This should be used only on Windows targets or when segmented stacks "
10740          "are being used");
10741   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10742   SDLoc dl(Op);
10743
10744   // Get the inputs.
10745   SDValue Chain = Op.getOperand(0);
10746   SDValue Size  = Op.getOperand(1);
10747   // FIXME: Ensure alignment here
10748
10749   bool Is64Bit = Subtarget->is64Bit();
10750   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10751
10752   if (getTargetMachine().Options.EnableSegmentedStacks) {
10753     MachineFunction &MF = DAG.getMachineFunction();
10754     MachineRegisterInfo &MRI = MF.getRegInfo();
10755
10756     if (Is64Bit) {
10757       // The 64 bit implementation of segmented stacks needs to clobber both r10
10758       // r11. This makes it impossible to use it along with nested parameters.
10759       const Function *F = MF.getFunction();
10760
10761       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10762            I != E; ++I)
10763         if (I->hasNestAttr())
10764           report_fatal_error("Cannot use segmented stacks with functions that "
10765                              "have nested arguments.");
10766     }
10767
10768     const TargetRegisterClass *AddrRegClass =
10769       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10770     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10771     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10772     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10773                                 DAG.getRegister(Vreg, SPTy));
10774     SDValue Ops1[2] = { Value, Chain };
10775     return DAG.getMergeValues(Ops1, 2, dl);
10776   } else {
10777     SDValue Flag;
10778     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10779
10780     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10781     Flag = Chain.getValue(1);
10782     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10783
10784     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10785     Flag = Chain.getValue(1);
10786
10787     const X86RegisterInfo *RegInfo =
10788       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10789     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10790                                SPTy).getValue(1);
10791
10792     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10793     return DAG.getMergeValues(Ops1, 2, dl);
10794   }
10795 }
10796
10797 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10798   MachineFunction &MF = DAG.getMachineFunction();
10799   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10800
10801   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10802   SDLoc DL(Op);
10803
10804   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10805     // vastart just stores the address of the VarArgsFrameIndex slot into the
10806     // memory location argument.
10807     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10808                                    getPointerTy());
10809     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10810                         MachinePointerInfo(SV), false, false, 0);
10811   }
10812
10813   // __va_list_tag:
10814   //   gp_offset         (0 - 6 * 8)
10815   //   fp_offset         (48 - 48 + 8 * 16)
10816   //   overflow_arg_area (point to parameters coming in memory).
10817   //   reg_save_area
10818   SmallVector<SDValue, 8> MemOps;
10819   SDValue FIN = Op.getOperand(1);
10820   // Store gp_offset
10821   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10822                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10823                                                MVT::i32),
10824                                FIN, MachinePointerInfo(SV), false, false, 0);
10825   MemOps.push_back(Store);
10826
10827   // Store fp_offset
10828   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10829                     FIN, DAG.getIntPtrConstant(4));
10830   Store = DAG.getStore(Op.getOperand(0), DL,
10831                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10832                                        MVT::i32),
10833                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10834   MemOps.push_back(Store);
10835
10836   // Store ptr to overflow_arg_area
10837   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10838                     FIN, DAG.getIntPtrConstant(4));
10839   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10840                                     getPointerTy());
10841   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10842                        MachinePointerInfo(SV, 8),
10843                        false, false, 0);
10844   MemOps.push_back(Store);
10845
10846   // Store ptr to reg_save_area.
10847   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10848                     FIN, DAG.getIntPtrConstant(8));
10849   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10850                                     getPointerTy());
10851   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10852                        MachinePointerInfo(SV, 16), false, false, 0);
10853   MemOps.push_back(Store);
10854   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10855                      &MemOps[0], MemOps.size());
10856 }
10857
10858 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10859   assert(Subtarget->is64Bit() &&
10860          "LowerVAARG only handles 64-bit va_arg!");
10861   assert((Subtarget->isTargetLinux() ||
10862           Subtarget->isTargetDarwin()) &&
10863           "Unhandled target in LowerVAARG");
10864   assert(Op.getNode()->getNumOperands() == 4);
10865   SDValue Chain = Op.getOperand(0);
10866   SDValue SrcPtr = Op.getOperand(1);
10867   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10868   unsigned Align = Op.getConstantOperandVal(3);
10869   SDLoc dl(Op);
10870
10871   EVT ArgVT = Op.getNode()->getValueType(0);
10872   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10873   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10874   uint8_t ArgMode;
10875
10876   // Decide which area this value should be read from.
10877   // TODO: Implement the AMD64 ABI in its entirety. This simple
10878   // selection mechanism works only for the basic types.
10879   if (ArgVT == MVT::f80) {
10880     llvm_unreachable("va_arg for f80 not yet implemented");
10881   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10882     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10883   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10884     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10885   } else {
10886     llvm_unreachable("Unhandled argument type in LowerVAARG");
10887   }
10888
10889   if (ArgMode == 2) {
10890     // Sanity Check: Make sure using fp_offset makes sense.
10891     assert(!getTargetMachine().Options.UseSoftFloat &&
10892            !(DAG.getMachineFunction()
10893                 .getFunction()->getAttributes()
10894                 .hasAttribute(AttributeSet::FunctionIndex,
10895                               Attribute::NoImplicitFloat)) &&
10896            Subtarget->hasSSE1());
10897   }
10898
10899   // Insert VAARG_64 node into the DAG
10900   // VAARG_64 returns two values: Variable Argument Address, Chain
10901   SmallVector<SDValue, 11> InstOps;
10902   InstOps.push_back(Chain);
10903   InstOps.push_back(SrcPtr);
10904   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10905   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10906   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10907   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10908   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10909                                           VTs, &InstOps[0], InstOps.size(),
10910                                           MVT::i64,
10911                                           MachinePointerInfo(SV),
10912                                           /*Align=*/0,
10913                                           /*Volatile=*/false,
10914                                           /*ReadMem=*/true,
10915                                           /*WriteMem=*/true);
10916   Chain = VAARG.getValue(1);
10917
10918   // Load the next argument and return it
10919   return DAG.getLoad(ArgVT, dl,
10920                      Chain,
10921                      VAARG,
10922                      MachinePointerInfo(),
10923                      false, false, false, 0);
10924 }
10925
10926 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10927                            SelectionDAG &DAG) {
10928   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10929   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10930   SDValue Chain = Op.getOperand(0);
10931   SDValue DstPtr = Op.getOperand(1);
10932   SDValue SrcPtr = Op.getOperand(2);
10933   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10934   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10935   SDLoc DL(Op);
10936
10937   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10938                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10939                        false,
10940                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10941 }
10942
10943 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10944 // may or may not be a constant. Takes immediate version of shift as input.
10945 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10946                                    SDValue SrcOp, SDValue ShAmt,
10947                                    SelectionDAG &DAG) {
10948   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10949
10950   if (isa<ConstantSDNode>(ShAmt)) {
10951     // Constant may be a TargetConstant. Use a regular constant.
10952     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10953     switch (Opc) {
10954       default: llvm_unreachable("Unknown target vector shift node");
10955       case X86ISD::VSHLI:
10956       case X86ISD::VSRLI:
10957       case X86ISD::VSRAI:
10958         return DAG.getNode(Opc, dl, VT, SrcOp,
10959                            DAG.getConstant(ShiftAmt, MVT::i32));
10960     }
10961   }
10962
10963   // Change opcode to non-immediate version
10964   switch (Opc) {
10965     default: llvm_unreachable("Unknown target vector shift node");
10966     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10967     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10968     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10969   }
10970
10971   // Need to build a vector containing shift amount
10972   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10973   SDValue ShOps[4];
10974   ShOps[0] = ShAmt;
10975   ShOps[1] = DAG.getConstant(0, MVT::i32);
10976   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10977   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10978
10979   // The return type has to be a 128-bit type with the same element
10980   // type as the input type.
10981   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10982   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10983
10984   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10985   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10986 }
10987
10988 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10989   SDLoc dl(Op);
10990   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10991   switch (IntNo) {
10992   default: return SDValue();    // Don't custom lower most intrinsics.
10993   // Comparison intrinsics.
10994   case Intrinsic::x86_sse_comieq_ss:
10995   case Intrinsic::x86_sse_comilt_ss:
10996   case Intrinsic::x86_sse_comile_ss:
10997   case Intrinsic::x86_sse_comigt_ss:
10998   case Intrinsic::x86_sse_comige_ss:
10999   case Intrinsic::x86_sse_comineq_ss:
11000   case Intrinsic::x86_sse_ucomieq_ss:
11001   case Intrinsic::x86_sse_ucomilt_ss:
11002   case Intrinsic::x86_sse_ucomile_ss:
11003   case Intrinsic::x86_sse_ucomigt_ss:
11004   case Intrinsic::x86_sse_ucomige_ss:
11005   case Intrinsic::x86_sse_ucomineq_ss:
11006   case Intrinsic::x86_sse2_comieq_sd:
11007   case Intrinsic::x86_sse2_comilt_sd:
11008   case Intrinsic::x86_sse2_comile_sd:
11009   case Intrinsic::x86_sse2_comigt_sd:
11010   case Intrinsic::x86_sse2_comige_sd:
11011   case Intrinsic::x86_sse2_comineq_sd:
11012   case Intrinsic::x86_sse2_ucomieq_sd:
11013   case Intrinsic::x86_sse2_ucomilt_sd:
11014   case Intrinsic::x86_sse2_ucomile_sd:
11015   case Intrinsic::x86_sse2_ucomigt_sd:
11016   case Intrinsic::x86_sse2_ucomige_sd:
11017   case Intrinsic::x86_sse2_ucomineq_sd: {
11018     unsigned Opc;
11019     ISD::CondCode CC;
11020     switch (IntNo) {
11021     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11022     case Intrinsic::x86_sse_comieq_ss:
11023     case Intrinsic::x86_sse2_comieq_sd:
11024       Opc = X86ISD::COMI;
11025       CC = ISD::SETEQ;
11026       break;
11027     case Intrinsic::x86_sse_comilt_ss:
11028     case Intrinsic::x86_sse2_comilt_sd:
11029       Opc = X86ISD::COMI;
11030       CC = ISD::SETLT;
11031       break;
11032     case Intrinsic::x86_sse_comile_ss:
11033     case Intrinsic::x86_sse2_comile_sd:
11034       Opc = X86ISD::COMI;
11035       CC = ISD::SETLE;
11036       break;
11037     case Intrinsic::x86_sse_comigt_ss:
11038     case Intrinsic::x86_sse2_comigt_sd:
11039       Opc = X86ISD::COMI;
11040       CC = ISD::SETGT;
11041       break;
11042     case Intrinsic::x86_sse_comige_ss:
11043     case Intrinsic::x86_sse2_comige_sd:
11044       Opc = X86ISD::COMI;
11045       CC = ISD::SETGE;
11046       break;
11047     case Intrinsic::x86_sse_comineq_ss:
11048     case Intrinsic::x86_sse2_comineq_sd:
11049       Opc = X86ISD::COMI;
11050       CC = ISD::SETNE;
11051       break;
11052     case Intrinsic::x86_sse_ucomieq_ss:
11053     case Intrinsic::x86_sse2_ucomieq_sd:
11054       Opc = X86ISD::UCOMI;
11055       CC = ISD::SETEQ;
11056       break;
11057     case Intrinsic::x86_sse_ucomilt_ss:
11058     case Intrinsic::x86_sse2_ucomilt_sd:
11059       Opc = X86ISD::UCOMI;
11060       CC = ISD::SETLT;
11061       break;
11062     case Intrinsic::x86_sse_ucomile_ss:
11063     case Intrinsic::x86_sse2_ucomile_sd:
11064       Opc = X86ISD::UCOMI;
11065       CC = ISD::SETLE;
11066       break;
11067     case Intrinsic::x86_sse_ucomigt_ss:
11068     case Intrinsic::x86_sse2_ucomigt_sd:
11069       Opc = X86ISD::UCOMI;
11070       CC = ISD::SETGT;
11071       break;
11072     case Intrinsic::x86_sse_ucomige_ss:
11073     case Intrinsic::x86_sse2_ucomige_sd:
11074       Opc = X86ISD::UCOMI;
11075       CC = ISD::SETGE;
11076       break;
11077     case Intrinsic::x86_sse_ucomineq_ss:
11078     case Intrinsic::x86_sse2_ucomineq_sd:
11079       Opc = X86ISD::UCOMI;
11080       CC = ISD::SETNE;
11081       break;
11082     }
11083
11084     SDValue LHS = Op.getOperand(1);
11085     SDValue RHS = Op.getOperand(2);
11086     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11087     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11088     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11089     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11090                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11091     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11092   }
11093
11094   // Arithmetic intrinsics.
11095   case Intrinsic::x86_sse2_pmulu_dq:
11096   case Intrinsic::x86_avx2_pmulu_dq:
11097     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11098                        Op.getOperand(1), Op.getOperand(2));
11099
11100   // SSE2/AVX2 sub with unsigned saturation intrinsics
11101   case Intrinsic::x86_sse2_psubus_b:
11102   case Intrinsic::x86_sse2_psubus_w:
11103   case Intrinsic::x86_avx2_psubus_b:
11104   case Intrinsic::x86_avx2_psubus_w:
11105     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11106                        Op.getOperand(1), Op.getOperand(2));
11107
11108   // SSE3/AVX horizontal add/sub intrinsics
11109   case Intrinsic::x86_sse3_hadd_ps:
11110   case Intrinsic::x86_sse3_hadd_pd:
11111   case Intrinsic::x86_avx_hadd_ps_256:
11112   case Intrinsic::x86_avx_hadd_pd_256:
11113   case Intrinsic::x86_sse3_hsub_ps:
11114   case Intrinsic::x86_sse3_hsub_pd:
11115   case Intrinsic::x86_avx_hsub_ps_256:
11116   case Intrinsic::x86_avx_hsub_pd_256:
11117   case Intrinsic::x86_ssse3_phadd_w_128:
11118   case Intrinsic::x86_ssse3_phadd_d_128:
11119   case Intrinsic::x86_avx2_phadd_w:
11120   case Intrinsic::x86_avx2_phadd_d:
11121   case Intrinsic::x86_ssse3_phsub_w_128:
11122   case Intrinsic::x86_ssse3_phsub_d_128:
11123   case Intrinsic::x86_avx2_phsub_w:
11124   case Intrinsic::x86_avx2_phsub_d: {
11125     unsigned Opcode;
11126     switch (IntNo) {
11127     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11128     case Intrinsic::x86_sse3_hadd_ps:
11129     case Intrinsic::x86_sse3_hadd_pd:
11130     case Intrinsic::x86_avx_hadd_ps_256:
11131     case Intrinsic::x86_avx_hadd_pd_256:
11132       Opcode = X86ISD::FHADD;
11133       break;
11134     case Intrinsic::x86_sse3_hsub_ps:
11135     case Intrinsic::x86_sse3_hsub_pd:
11136     case Intrinsic::x86_avx_hsub_ps_256:
11137     case Intrinsic::x86_avx_hsub_pd_256:
11138       Opcode = X86ISD::FHSUB;
11139       break;
11140     case Intrinsic::x86_ssse3_phadd_w_128:
11141     case Intrinsic::x86_ssse3_phadd_d_128:
11142     case Intrinsic::x86_avx2_phadd_w:
11143     case Intrinsic::x86_avx2_phadd_d:
11144       Opcode = X86ISD::HADD;
11145       break;
11146     case Intrinsic::x86_ssse3_phsub_w_128:
11147     case Intrinsic::x86_ssse3_phsub_d_128:
11148     case Intrinsic::x86_avx2_phsub_w:
11149     case Intrinsic::x86_avx2_phsub_d:
11150       Opcode = X86ISD::HSUB;
11151       break;
11152     }
11153     return DAG.getNode(Opcode, dl, Op.getValueType(),
11154                        Op.getOperand(1), Op.getOperand(2));
11155   }
11156
11157   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11158   case Intrinsic::x86_sse2_pmaxu_b:
11159   case Intrinsic::x86_sse41_pmaxuw:
11160   case Intrinsic::x86_sse41_pmaxud:
11161   case Intrinsic::x86_avx2_pmaxu_b:
11162   case Intrinsic::x86_avx2_pmaxu_w:
11163   case Intrinsic::x86_avx2_pmaxu_d:
11164   case Intrinsic::x86_sse2_pminu_b:
11165   case Intrinsic::x86_sse41_pminuw:
11166   case Intrinsic::x86_sse41_pminud:
11167   case Intrinsic::x86_avx2_pminu_b:
11168   case Intrinsic::x86_avx2_pminu_w:
11169   case Intrinsic::x86_avx2_pminu_d:
11170   case Intrinsic::x86_sse41_pmaxsb:
11171   case Intrinsic::x86_sse2_pmaxs_w:
11172   case Intrinsic::x86_sse41_pmaxsd:
11173   case Intrinsic::x86_avx2_pmaxs_b:
11174   case Intrinsic::x86_avx2_pmaxs_w:
11175   case Intrinsic::x86_avx2_pmaxs_d:
11176   case Intrinsic::x86_sse41_pminsb:
11177   case Intrinsic::x86_sse2_pmins_w:
11178   case Intrinsic::x86_sse41_pminsd:
11179   case Intrinsic::x86_avx2_pmins_b:
11180   case Intrinsic::x86_avx2_pmins_w:
11181   case Intrinsic::x86_avx2_pmins_d: {
11182     unsigned Opcode;
11183     switch (IntNo) {
11184     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11185     case Intrinsic::x86_sse2_pmaxu_b:
11186     case Intrinsic::x86_sse41_pmaxuw:
11187     case Intrinsic::x86_sse41_pmaxud:
11188     case Intrinsic::x86_avx2_pmaxu_b:
11189     case Intrinsic::x86_avx2_pmaxu_w:
11190     case Intrinsic::x86_avx2_pmaxu_d:
11191       Opcode = X86ISD::UMAX;
11192       break;
11193     case Intrinsic::x86_sse2_pminu_b:
11194     case Intrinsic::x86_sse41_pminuw:
11195     case Intrinsic::x86_sse41_pminud:
11196     case Intrinsic::x86_avx2_pminu_b:
11197     case Intrinsic::x86_avx2_pminu_w:
11198     case Intrinsic::x86_avx2_pminu_d:
11199       Opcode = X86ISD::UMIN;
11200       break;
11201     case Intrinsic::x86_sse41_pmaxsb:
11202     case Intrinsic::x86_sse2_pmaxs_w:
11203     case Intrinsic::x86_sse41_pmaxsd:
11204     case Intrinsic::x86_avx2_pmaxs_b:
11205     case Intrinsic::x86_avx2_pmaxs_w:
11206     case Intrinsic::x86_avx2_pmaxs_d:
11207       Opcode = X86ISD::SMAX;
11208       break;
11209     case Intrinsic::x86_sse41_pminsb:
11210     case Intrinsic::x86_sse2_pmins_w:
11211     case Intrinsic::x86_sse41_pminsd:
11212     case Intrinsic::x86_avx2_pmins_b:
11213     case Intrinsic::x86_avx2_pmins_w:
11214     case Intrinsic::x86_avx2_pmins_d:
11215       Opcode = X86ISD::SMIN;
11216       break;
11217     }
11218     return DAG.getNode(Opcode, dl, Op.getValueType(),
11219                        Op.getOperand(1), Op.getOperand(2));
11220   }
11221
11222   // SSE/SSE2/AVX floating point max/min intrinsics.
11223   case Intrinsic::x86_sse_max_ps:
11224   case Intrinsic::x86_sse2_max_pd:
11225   case Intrinsic::x86_avx_max_ps_256:
11226   case Intrinsic::x86_avx_max_pd_256:
11227   case Intrinsic::x86_avx512_max_ps_512:
11228   case Intrinsic::x86_avx512_max_pd_512:
11229   case Intrinsic::x86_sse_min_ps:
11230   case Intrinsic::x86_sse2_min_pd:
11231   case Intrinsic::x86_avx_min_ps_256:
11232   case Intrinsic::x86_avx_min_pd_256:
11233   case Intrinsic::x86_avx512_min_ps_512:
11234   case Intrinsic::x86_avx512_min_pd_512:  {
11235     unsigned Opcode;
11236     switch (IntNo) {
11237     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11238     case Intrinsic::x86_sse_max_ps:
11239     case Intrinsic::x86_sse2_max_pd:
11240     case Intrinsic::x86_avx_max_ps_256:
11241     case Intrinsic::x86_avx_max_pd_256:
11242     case Intrinsic::x86_avx512_max_ps_512:
11243     case Intrinsic::x86_avx512_max_pd_512:
11244       Opcode = X86ISD::FMAX;
11245       break;
11246     case Intrinsic::x86_sse_min_ps:
11247     case Intrinsic::x86_sse2_min_pd:
11248     case Intrinsic::x86_avx_min_ps_256:
11249     case Intrinsic::x86_avx_min_pd_256:
11250     case Intrinsic::x86_avx512_min_ps_512:
11251     case Intrinsic::x86_avx512_min_pd_512:
11252       Opcode = X86ISD::FMIN;
11253       break;
11254     }
11255     return DAG.getNode(Opcode, dl, Op.getValueType(),
11256                        Op.getOperand(1), Op.getOperand(2));
11257   }
11258
11259   // AVX2 variable shift intrinsics
11260   case Intrinsic::x86_avx2_psllv_d:
11261   case Intrinsic::x86_avx2_psllv_q:
11262   case Intrinsic::x86_avx2_psllv_d_256:
11263   case Intrinsic::x86_avx2_psllv_q_256:
11264   case Intrinsic::x86_avx2_psrlv_d:
11265   case Intrinsic::x86_avx2_psrlv_q:
11266   case Intrinsic::x86_avx2_psrlv_d_256:
11267   case Intrinsic::x86_avx2_psrlv_q_256:
11268   case Intrinsic::x86_avx2_psrav_d:
11269   case Intrinsic::x86_avx2_psrav_d_256: {
11270     unsigned Opcode;
11271     switch (IntNo) {
11272     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11273     case Intrinsic::x86_avx2_psllv_d:
11274     case Intrinsic::x86_avx2_psllv_q:
11275     case Intrinsic::x86_avx2_psllv_d_256:
11276     case Intrinsic::x86_avx2_psllv_q_256:
11277       Opcode = ISD::SHL;
11278       break;
11279     case Intrinsic::x86_avx2_psrlv_d:
11280     case Intrinsic::x86_avx2_psrlv_q:
11281     case Intrinsic::x86_avx2_psrlv_d_256:
11282     case Intrinsic::x86_avx2_psrlv_q_256:
11283       Opcode = ISD::SRL;
11284       break;
11285     case Intrinsic::x86_avx2_psrav_d:
11286     case Intrinsic::x86_avx2_psrav_d_256:
11287       Opcode = ISD::SRA;
11288       break;
11289     }
11290     return DAG.getNode(Opcode, dl, Op.getValueType(),
11291                        Op.getOperand(1), Op.getOperand(2));
11292   }
11293
11294   case Intrinsic::x86_ssse3_pshuf_b_128:
11295   case Intrinsic::x86_avx2_pshuf_b:
11296     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11297                        Op.getOperand(1), Op.getOperand(2));
11298
11299   case Intrinsic::x86_ssse3_psign_b_128:
11300   case Intrinsic::x86_ssse3_psign_w_128:
11301   case Intrinsic::x86_ssse3_psign_d_128:
11302   case Intrinsic::x86_avx2_psign_b:
11303   case Intrinsic::x86_avx2_psign_w:
11304   case Intrinsic::x86_avx2_psign_d:
11305     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11306                        Op.getOperand(1), Op.getOperand(2));
11307
11308   case Intrinsic::x86_sse41_insertps:
11309     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11310                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11311
11312   case Intrinsic::x86_avx_vperm2f128_ps_256:
11313   case Intrinsic::x86_avx_vperm2f128_pd_256:
11314   case Intrinsic::x86_avx_vperm2f128_si_256:
11315   case Intrinsic::x86_avx2_vperm2i128:
11316     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11317                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11318
11319   case Intrinsic::x86_avx2_permd:
11320   case Intrinsic::x86_avx2_permps:
11321     // Operands intentionally swapped. Mask is last operand to intrinsic,
11322     // but second operand for node/intruction.
11323     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11324                        Op.getOperand(2), Op.getOperand(1));
11325
11326   case Intrinsic::x86_sse_sqrt_ps:
11327   case Intrinsic::x86_sse2_sqrt_pd:
11328   case Intrinsic::x86_avx_sqrt_ps_256:
11329   case Intrinsic::x86_avx_sqrt_pd_256:
11330     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11331
11332   // ptest and testp intrinsics. The intrinsic these come from are designed to
11333   // return an integer value, not just an instruction so lower it to the ptest
11334   // or testp pattern and a setcc for the result.
11335   case Intrinsic::x86_sse41_ptestz:
11336   case Intrinsic::x86_sse41_ptestc:
11337   case Intrinsic::x86_sse41_ptestnzc:
11338   case Intrinsic::x86_avx_ptestz_256:
11339   case Intrinsic::x86_avx_ptestc_256:
11340   case Intrinsic::x86_avx_ptestnzc_256:
11341   case Intrinsic::x86_avx_vtestz_ps:
11342   case Intrinsic::x86_avx_vtestc_ps:
11343   case Intrinsic::x86_avx_vtestnzc_ps:
11344   case Intrinsic::x86_avx_vtestz_pd:
11345   case Intrinsic::x86_avx_vtestc_pd:
11346   case Intrinsic::x86_avx_vtestnzc_pd:
11347   case Intrinsic::x86_avx_vtestz_ps_256:
11348   case Intrinsic::x86_avx_vtestc_ps_256:
11349   case Intrinsic::x86_avx_vtestnzc_ps_256:
11350   case Intrinsic::x86_avx_vtestz_pd_256:
11351   case Intrinsic::x86_avx_vtestc_pd_256:
11352   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11353     bool IsTestPacked = false;
11354     unsigned X86CC;
11355     switch (IntNo) {
11356     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11357     case Intrinsic::x86_avx_vtestz_ps:
11358     case Intrinsic::x86_avx_vtestz_pd:
11359     case Intrinsic::x86_avx_vtestz_ps_256:
11360     case Intrinsic::x86_avx_vtestz_pd_256:
11361       IsTestPacked = true; // Fallthrough
11362     case Intrinsic::x86_sse41_ptestz:
11363     case Intrinsic::x86_avx_ptestz_256:
11364       // ZF = 1
11365       X86CC = X86::COND_E;
11366       break;
11367     case Intrinsic::x86_avx_vtestc_ps:
11368     case Intrinsic::x86_avx_vtestc_pd:
11369     case Intrinsic::x86_avx_vtestc_ps_256:
11370     case Intrinsic::x86_avx_vtestc_pd_256:
11371       IsTestPacked = true; // Fallthrough
11372     case Intrinsic::x86_sse41_ptestc:
11373     case Intrinsic::x86_avx_ptestc_256:
11374       // CF = 1
11375       X86CC = X86::COND_B;
11376       break;
11377     case Intrinsic::x86_avx_vtestnzc_ps:
11378     case Intrinsic::x86_avx_vtestnzc_pd:
11379     case Intrinsic::x86_avx_vtestnzc_ps_256:
11380     case Intrinsic::x86_avx_vtestnzc_pd_256:
11381       IsTestPacked = true; // Fallthrough
11382     case Intrinsic::x86_sse41_ptestnzc:
11383     case Intrinsic::x86_avx_ptestnzc_256:
11384       // ZF and CF = 0
11385       X86CC = X86::COND_A;
11386       break;
11387     }
11388
11389     SDValue LHS = Op.getOperand(1);
11390     SDValue RHS = Op.getOperand(2);
11391     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11392     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11393     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11394     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11395     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11396   }
11397   case Intrinsic::x86_avx512_kortestz:
11398   case Intrinsic::x86_avx512_kortestc: {
11399     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz)? X86::COND_E: X86::COND_B;
11400     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11401     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11402     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11403     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11404     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11405     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11406   }
11407
11408   // SSE/AVX shift intrinsics
11409   case Intrinsic::x86_sse2_psll_w:
11410   case Intrinsic::x86_sse2_psll_d:
11411   case Intrinsic::x86_sse2_psll_q:
11412   case Intrinsic::x86_avx2_psll_w:
11413   case Intrinsic::x86_avx2_psll_d:
11414   case Intrinsic::x86_avx2_psll_q:
11415   case Intrinsic::x86_sse2_psrl_w:
11416   case Intrinsic::x86_sse2_psrl_d:
11417   case Intrinsic::x86_sse2_psrl_q:
11418   case Intrinsic::x86_avx2_psrl_w:
11419   case Intrinsic::x86_avx2_psrl_d:
11420   case Intrinsic::x86_avx2_psrl_q:
11421   case Intrinsic::x86_sse2_psra_w:
11422   case Intrinsic::x86_sse2_psra_d:
11423   case Intrinsic::x86_avx2_psra_w:
11424   case Intrinsic::x86_avx2_psra_d: {
11425     unsigned Opcode;
11426     switch (IntNo) {
11427     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11428     case Intrinsic::x86_sse2_psll_w:
11429     case Intrinsic::x86_sse2_psll_d:
11430     case Intrinsic::x86_sse2_psll_q:
11431     case Intrinsic::x86_avx2_psll_w:
11432     case Intrinsic::x86_avx2_psll_d:
11433     case Intrinsic::x86_avx2_psll_q:
11434       Opcode = X86ISD::VSHL;
11435       break;
11436     case Intrinsic::x86_sse2_psrl_w:
11437     case Intrinsic::x86_sse2_psrl_d:
11438     case Intrinsic::x86_sse2_psrl_q:
11439     case Intrinsic::x86_avx2_psrl_w:
11440     case Intrinsic::x86_avx2_psrl_d:
11441     case Intrinsic::x86_avx2_psrl_q:
11442       Opcode = X86ISD::VSRL;
11443       break;
11444     case Intrinsic::x86_sse2_psra_w:
11445     case Intrinsic::x86_sse2_psra_d:
11446     case Intrinsic::x86_avx2_psra_w:
11447     case Intrinsic::x86_avx2_psra_d:
11448       Opcode = X86ISD::VSRA;
11449       break;
11450     }
11451     return DAG.getNode(Opcode, dl, Op.getValueType(),
11452                        Op.getOperand(1), Op.getOperand(2));
11453   }
11454
11455   // SSE/AVX immediate shift intrinsics
11456   case Intrinsic::x86_sse2_pslli_w:
11457   case Intrinsic::x86_sse2_pslli_d:
11458   case Intrinsic::x86_sse2_pslli_q:
11459   case Intrinsic::x86_avx2_pslli_w:
11460   case Intrinsic::x86_avx2_pslli_d:
11461   case Intrinsic::x86_avx2_pslli_q:
11462   case Intrinsic::x86_sse2_psrli_w:
11463   case Intrinsic::x86_sse2_psrli_d:
11464   case Intrinsic::x86_sse2_psrli_q:
11465   case Intrinsic::x86_avx2_psrli_w:
11466   case Intrinsic::x86_avx2_psrli_d:
11467   case Intrinsic::x86_avx2_psrli_q:
11468   case Intrinsic::x86_sse2_psrai_w:
11469   case Intrinsic::x86_sse2_psrai_d:
11470   case Intrinsic::x86_avx2_psrai_w:
11471   case Intrinsic::x86_avx2_psrai_d: {
11472     unsigned Opcode;
11473     switch (IntNo) {
11474     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11475     case Intrinsic::x86_sse2_pslli_w:
11476     case Intrinsic::x86_sse2_pslli_d:
11477     case Intrinsic::x86_sse2_pslli_q:
11478     case Intrinsic::x86_avx2_pslli_w:
11479     case Intrinsic::x86_avx2_pslli_d:
11480     case Intrinsic::x86_avx2_pslli_q:
11481       Opcode = X86ISD::VSHLI;
11482       break;
11483     case Intrinsic::x86_sse2_psrli_w:
11484     case Intrinsic::x86_sse2_psrli_d:
11485     case Intrinsic::x86_sse2_psrli_q:
11486     case Intrinsic::x86_avx2_psrli_w:
11487     case Intrinsic::x86_avx2_psrli_d:
11488     case Intrinsic::x86_avx2_psrli_q:
11489       Opcode = X86ISD::VSRLI;
11490       break;
11491     case Intrinsic::x86_sse2_psrai_w:
11492     case Intrinsic::x86_sse2_psrai_d:
11493     case Intrinsic::x86_avx2_psrai_w:
11494     case Intrinsic::x86_avx2_psrai_d:
11495       Opcode = X86ISD::VSRAI;
11496       break;
11497     }
11498     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11499                                Op.getOperand(1), Op.getOperand(2), DAG);
11500   }
11501
11502   case Intrinsic::x86_sse42_pcmpistria128:
11503   case Intrinsic::x86_sse42_pcmpestria128:
11504   case Intrinsic::x86_sse42_pcmpistric128:
11505   case Intrinsic::x86_sse42_pcmpestric128:
11506   case Intrinsic::x86_sse42_pcmpistrio128:
11507   case Intrinsic::x86_sse42_pcmpestrio128:
11508   case Intrinsic::x86_sse42_pcmpistris128:
11509   case Intrinsic::x86_sse42_pcmpestris128:
11510   case Intrinsic::x86_sse42_pcmpistriz128:
11511   case Intrinsic::x86_sse42_pcmpestriz128: {
11512     unsigned Opcode;
11513     unsigned X86CC;
11514     switch (IntNo) {
11515     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11516     case Intrinsic::x86_sse42_pcmpistria128:
11517       Opcode = X86ISD::PCMPISTRI;
11518       X86CC = X86::COND_A;
11519       break;
11520     case Intrinsic::x86_sse42_pcmpestria128:
11521       Opcode = X86ISD::PCMPESTRI;
11522       X86CC = X86::COND_A;
11523       break;
11524     case Intrinsic::x86_sse42_pcmpistric128:
11525       Opcode = X86ISD::PCMPISTRI;
11526       X86CC = X86::COND_B;
11527       break;
11528     case Intrinsic::x86_sse42_pcmpestric128:
11529       Opcode = X86ISD::PCMPESTRI;
11530       X86CC = X86::COND_B;
11531       break;
11532     case Intrinsic::x86_sse42_pcmpistrio128:
11533       Opcode = X86ISD::PCMPISTRI;
11534       X86CC = X86::COND_O;
11535       break;
11536     case Intrinsic::x86_sse42_pcmpestrio128:
11537       Opcode = X86ISD::PCMPESTRI;
11538       X86CC = X86::COND_O;
11539       break;
11540     case Intrinsic::x86_sse42_pcmpistris128:
11541       Opcode = X86ISD::PCMPISTRI;
11542       X86CC = X86::COND_S;
11543       break;
11544     case Intrinsic::x86_sse42_pcmpestris128:
11545       Opcode = X86ISD::PCMPESTRI;
11546       X86CC = X86::COND_S;
11547       break;
11548     case Intrinsic::x86_sse42_pcmpistriz128:
11549       Opcode = X86ISD::PCMPISTRI;
11550       X86CC = X86::COND_E;
11551       break;
11552     case Intrinsic::x86_sse42_pcmpestriz128:
11553       Opcode = X86ISD::PCMPESTRI;
11554       X86CC = X86::COND_E;
11555       break;
11556     }
11557     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11558     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11559     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11560     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11561                                 DAG.getConstant(X86CC, MVT::i8),
11562                                 SDValue(PCMP.getNode(), 1));
11563     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11564   }
11565
11566   case Intrinsic::x86_sse42_pcmpistri128:
11567   case Intrinsic::x86_sse42_pcmpestri128: {
11568     unsigned Opcode;
11569     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11570       Opcode = X86ISD::PCMPISTRI;
11571     else
11572       Opcode = X86ISD::PCMPESTRI;
11573
11574     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11575     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11576     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11577   }
11578   case Intrinsic::x86_fma_vfmadd_ps:
11579   case Intrinsic::x86_fma_vfmadd_pd:
11580   case Intrinsic::x86_fma_vfmsub_ps:
11581   case Intrinsic::x86_fma_vfmsub_pd:
11582   case Intrinsic::x86_fma_vfnmadd_ps:
11583   case Intrinsic::x86_fma_vfnmadd_pd:
11584   case Intrinsic::x86_fma_vfnmsub_ps:
11585   case Intrinsic::x86_fma_vfnmsub_pd:
11586   case Intrinsic::x86_fma_vfmaddsub_ps:
11587   case Intrinsic::x86_fma_vfmaddsub_pd:
11588   case Intrinsic::x86_fma_vfmsubadd_ps:
11589   case Intrinsic::x86_fma_vfmsubadd_pd:
11590   case Intrinsic::x86_fma_vfmadd_ps_256:
11591   case Intrinsic::x86_fma_vfmadd_pd_256:
11592   case Intrinsic::x86_fma_vfmsub_ps_256:
11593   case Intrinsic::x86_fma_vfmsub_pd_256:
11594   case Intrinsic::x86_fma_vfnmadd_ps_256:
11595   case Intrinsic::x86_fma_vfnmadd_pd_256:
11596   case Intrinsic::x86_fma_vfnmsub_ps_256:
11597   case Intrinsic::x86_fma_vfnmsub_pd_256:
11598   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11599   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11600   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11601   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11602     unsigned Opc;
11603     switch (IntNo) {
11604     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11605     case Intrinsic::x86_fma_vfmadd_ps:
11606     case Intrinsic::x86_fma_vfmadd_pd:
11607     case Intrinsic::x86_fma_vfmadd_ps_256:
11608     case Intrinsic::x86_fma_vfmadd_pd_256:
11609       Opc = X86ISD::FMADD;
11610       break;
11611     case Intrinsic::x86_fma_vfmsub_ps:
11612     case Intrinsic::x86_fma_vfmsub_pd:
11613     case Intrinsic::x86_fma_vfmsub_ps_256:
11614     case Intrinsic::x86_fma_vfmsub_pd_256:
11615       Opc = X86ISD::FMSUB;
11616       break;
11617     case Intrinsic::x86_fma_vfnmadd_ps:
11618     case Intrinsic::x86_fma_vfnmadd_pd:
11619     case Intrinsic::x86_fma_vfnmadd_ps_256:
11620     case Intrinsic::x86_fma_vfnmadd_pd_256:
11621       Opc = X86ISD::FNMADD;
11622       break;
11623     case Intrinsic::x86_fma_vfnmsub_ps:
11624     case Intrinsic::x86_fma_vfnmsub_pd:
11625     case Intrinsic::x86_fma_vfnmsub_ps_256:
11626     case Intrinsic::x86_fma_vfnmsub_pd_256:
11627       Opc = X86ISD::FNMSUB;
11628       break;
11629     case Intrinsic::x86_fma_vfmaddsub_ps:
11630     case Intrinsic::x86_fma_vfmaddsub_pd:
11631     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11632     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11633       Opc = X86ISD::FMADDSUB;
11634       break;
11635     case Intrinsic::x86_fma_vfmsubadd_ps:
11636     case Intrinsic::x86_fma_vfmsubadd_pd:
11637     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11638     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11639       Opc = X86ISD::FMSUBADD;
11640       break;
11641     }
11642
11643     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11644                        Op.getOperand(2), Op.getOperand(3));
11645   }
11646   }
11647 }
11648
11649 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11650                              SDValue Base, SDValue Index,
11651                              SDValue ScaleOp, SDValue Chain,
11652                              const X86Subtarget * Subtarget) {
11653   SDLoc dl(Op);
11654   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11655   assert(C && "Invalid scale type");
11656   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11657   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl); 
11658   EVT MaskVT = MVT::getVectorVT(MVT::i1, 
11659                                 Index.getValueType().getVectorNumElements());
11660   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11661   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11662   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11663   SDValue Segment = DAG.getRegister(0, MVT::i32);
11664   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11665   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11666   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11667   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11668 }
11669
11670 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11671                               SDValue Src, SDValue Mask, SDValue Base,
11672                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11673                               const X86Subtarget * Subtarget) {
11674   SDLoc dl(Op);
11675   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11676   assert(C && "Invalid scale type");
11677   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11678   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11679                                 Index.getValueType().getVectorNumElements());
11680   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11681   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11682   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11683   SDValue Segment = DAG.getRegister(0, MVT::i32);
11684   if (Src.getOpcode() == ISD::UNDEF)
11685     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl); 
11686   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11687   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11688   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11689   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11690 }
11691
11692 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11693                               SDValue Src, SDValue Base, SDValue Index,
11694                               SDValue ScaleOp, SDValue Chain) {
11695   SDLoc dl(Op);
11696   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11697   assert(C && "Invalid scale type");
11698   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11699   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11700   SDValue Segment = DAG.getRegister(0, MVT::i32);
11701   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11702                                 Index.getValueType().getVectorNumElements());
11703   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11704   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11705   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11706   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11707   return SDValue(Res, 1);
11708 }
11709
11710 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11711                                SDValue Src, SDValue Mask, SDValue Base,
11712                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
11713   SDLoc dl(Op);
11714   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11715   assert(C && "Invalid scale type");
11716   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11717   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11718   SDValue Segment = DAG.getRegister(0, MVT::i32);
11719   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11720                                 Index.getValueType().getVectorNumElements());
11721   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11722   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11723   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11724   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11725   return SDValue(Res, 1);
11726 }
11727
11728 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11729                                       SelectionDAG &DAG) {
11730   SDLoc dl(Op);
11731   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11732   switch (IntNo) {
11733   default: return SDValue();    // Don't custom lower most intrinsics.
11734
11735   // RDRAND/RDSEED intrinsics.
11736   case Intrinsic::x86_rdrand_16:
11737   case Intrinsic::x86_rdrand_32:
11738   case Intrinsic::x86_rdrand_64:
11739   case Intrinsic::x86_rdseed_16:
11740   case Intrinsic::x86_rdseed_32:
11741   case Intrinsic::x86_rdseed_64: {
11742     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11743                        IntNo == Intrinsic::x86_rdseed_32 ||
11744                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11745                                                             X86ISD::RDRAND;
11746     // Emit the node with the right value type.
11747     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11748     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11749
11750     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11751     // Otherwise return the value from Rand, which is always 0, casted to i32.
11752     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11753                       DAG.getConstant(1, Op->getValueType(1)),
11754                       DAG.getConstant(X86::COND_B, MVT::i32),
11755                       SDValue(Result.getNode(), 1) };
11756     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11757                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11758                                   Ops, array_lengthof(Ops));
11759
11760     // Return { result, isValid, chain }.
11761     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11762                        SDValue(Result.getNode(), 2));
11763   }
11764   //int_gather(index, base, scale);
11765   case Intrinsic::x86_avx512_gather_qpd_512:
11766   case Intrinsic::x86_avx512_gather_qps_512:
11767   case Intrinsic::x86_avx512_gather_dpd_512:
11768   case Intrinsic::x86_avx512_gather_qpi_512:
11769   case Intrinsic::x86_avx512_gather_qpq_512:
11770   case Intrinsic::x86_avx512_gather_dpq_512:
11771   case Intrinsic::x86_avx512_gather_dps_512:
11772   case Intrinsic::x86_avx512_gather_dpi_512: {
11773     unsigned Opc;
11774     switch (IntNo) {
11775       default: llvm_unreachable("Unexpected intrinsic!");
11776       case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
11777       case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
11778       case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
11779       case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
11780       case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
11781       case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
11782       case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
11783       case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
11784     }
11785     SDValue Chain = Op.getOperand(0);
11786     SDValue Index = Op.getOperand(2);
11787     SDValue Base  = Op.getOperand(3);
11788     SDValue Scale = Op.getOperand(4);
11789     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
11790   }
11791   //int_gather_mask(v1, mask, index, base, scale);
11792   case Intrinsic::x86_avx512_gather_qps_mask_512:
11793   case Intrinsic::x86_avx512_gather_qpd_mask_512:
11794   case Intrinsic::x86_avx512_gather_dpd_mask_512:
11795   case Intrinsic::x86_avx512_gather_dps_mask_512:
11796   case Intrinsic::x86_avx512_gather_qpi_mask_512:
11797   case Intrinsic::x86_avx512_gather_qpq_mask_512:
11798   case Intrinsic::x86_avx512_gather_dpi_mask_512:
11799   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
11800     unsigned Opc;
11801     switch (IntNo) {
11802       default: llvm_unreachable("Unexpected intrinsic!");
11803       case Intrinsic::x86_avx512_gather_qps_mask_512: 
11804         Opc = X86::VGATHERQPSZrm; break;
11805       case Intrinsic::x86_avx512_gather_qpd_mask_512:
11806         Opc = X86::VGATHERQPDZrm; break;
11807       case Intrinsic::x86_avx512_gather_dpd_mask_512:
11808         Opc = X86::VGATHERDPDZrm; break;
11809       case Intrinsic::x86_avx512_gather_dps_mask_512:
11810         Opc = X86::VGATHERDPSZrm; break;
11811       case Intrinsic::x86_avx512_gather_qpi_mask_512:
11812         Opc = X86::VPGATHERQDZrm; break;
11813       case Intrinsic::x86_avx512_gather_qpq_mask_512:
11814         Opc = X86::VPGATHERQQZrm; break;
11815       case Intrinsic::x86_avx512_gather_dpi_mask_512:
11816         Opc = X86::VPGATHERDDZrm; break;
11817       case Intrinsic::x86_avx512_gather_dpq_mask_512:
11818         Opc = X86::VPGATHERDQZrm; break;
11819     }
11820     SDValue Chain = Op.getOperand(0);
11821     SDValue Src   = Op.getOperand(2);
11822     SDValue Mask  = Op.getOperand(3);
11823     SDValue Index = Op.getOperand(4);
11824     SDValue Base  = Op.getOperand(5);
11825     SDValue Scale = Op.getOperand(6);
11826     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
11827                           Subtarget);
11828   }
11829   //int_scatter(base, index, v1, scale);
11830   case Intrinsic::x86_avx512_scatter_qpd_512:
11831   case Intrinsic::x86_avx512_scatter_qps_512:
11832   case Intrinsic::x86_avx512_scatter_dpd_512:
11833   case Intrinsic::x86_avx512_scatter_qpi_512:
11834   case Intrinsic::x86_avx512_scatter_qpq_512:
11835   case Intrinsic::x86_avx512_scatter_dpq_512:
11836   case Intrinsic::x86_avx512_scatter_dps_512:
11837   case Intrinsic::x86_avx512_scatter_dpi_512: {
11838     unsigned Opc;
11839     switch (IntNo) {
11840       default: llvm_unreachable("Unexpected intrinsic!");
11841       case Intrinsic::x86_avx512_scatter_qpd_512: 
11842         Opc = X86::VSCATTERQPDZmr; break;
11843       case Intrinsic::x86_avx512_scatter_qps_512:
11844         Opc = X86::VSCATTERQPSZmr; break;
11845       case Intrinsic::x86_avx512_scatter_dpd_512:
11846         Opc = X86::VSCATTERDPDZmr; break;
11847       case Intrinsic::x86_avx512_scatter_dps_512:
11848         Opc = X86::VSCATTERDPSZmr; break;
11849       case Intrinsic::x86_avx512_scatter_qpi_512:
11850         Opc = X86::VPSCATTERQDZmr; break;
11851       case Intrinsic::x86_avx512_scatter_qpq_512:
11852         Opc = X86::VPSCATTERQQZmr; break;
11853       case Intrinsic::x86_avx512_scatter_dpq_512:
11854         Opc = X86::VPSCATTERDQZmr; break;
11855       case Intrinsic::x86_avx512_scatter_dpi_512:
11856         Opc = X86::VPSCATTERDDZmr; break;
11857     }
11858     SDValue Chain = Op.getOperand(0);
11859     SDValue Base  = Op.getOperand(2);
11860     SDValue Index = Op.getOperand(3);
11861     SDValue Src   = Op.getOperand(4);
11862     SDValue Scale = Op.getOperand(5);
11863     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
11864   }
11865   //int_scatter_mask(base, mask, index, v1, scale);
11866   case Intrinsic::x86_avx512_scatter_qps_mask_512:
11867   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
11868   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
11869   case Intrinsic::x86_avx512_scatter_dps_mask_512:
11870   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
11871   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
11872   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
11873   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
11874     unsigned Opc;
11875     switch (IntNo) {
11876       default: llvm_unreachable("Unexpected intrinsic!");
11877       case Intrinsic::x86_avx512_scatter_qpd_mask_512: 
11878         Opc = X86::VSCATTERQPDZmr; break;
11879       case Intrinsic::x86_avx512_scatter_qps_mask_512:
11880         Opc = X86::VSCATTERQPSZmr; break;
11881       case Intrinsic::x86_avx512_scatter_dpd_mask_512:
11882         Opc = X86::VSCATTERDPDZmr; break;
11883       case Intrinsic::x86_avx512_scatter_dps_mask_512:
11884         Opc = X86::VSCATTERDPSZmr; break;
11885       case Intrinsic::x86_avx512_scatter_qpi_mask_512:
11886         Opc = X86::VPSCATTERQDZmr; break;
11887       case Intrinsic::x86_avx512_scatter_qpq_mask_512:
11888         Opc = X86::VPSCATTERQQZmr; break;
11889       case Intrinsic::x86_avx512_scatter_dpq_mask_512:
11890         Opc = X86::VPSCATTERDQZmr; break;
11891       case Intrinsic::x86_avx512_scatter_dpi_mask_512:
11892         Opc = X86::VPSCATTERDDZmr; break;
11893     }
11894     SDValue Chain = Op.getOperand(0);
11895     SDValue Base  = Op.getOperand(2);
11896     SDValue Mask  = Op.getOperand(3);
11897     SDValue Index = Op.getOperand(4);
11898     SDValue Src   = Op.getOperand(5);
11899     SDValue Scale = Op.getOperand(6);
11900     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
11901   }
11902   // XTEST intrinsics.
11903   case Intrinsic::x86_xtest: {
11904     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11905     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11906     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11907                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11908                                 InTrans);
11909     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11910     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11911                        Ret, SDValue(InTrans.getNode(), 1));
11912   }
11913   }
11914 }
11915
11916 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11917                                            SelectionDAG &DAG) const {
11918   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11919   MFI->setReturnAddressIsTaken(true);
11920
11921   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11922   SDLoc dl(Op);
11923   EVT PtrVT = getPointerTy();
11924
11925   if (Depth > 0) {
11926     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11927     const X86RegisterInfo *RegInfo =
11928       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11929     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11930     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11931                        DAG.getNode(ISD::ADD, dl, PtrVT,
11932                                    FrameAddr, Offset),
11933                        MachinePointerInfo(), false, false, false, 0);
11934   }
11935
11936   // Just load the return address.
11937   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11938   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11939                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11940 }
11941
11942 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11943   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11944   MFI->setFrameAddressIsTaken(true);
11945
11946   EVT VT = Op.getValueType();
11947   SDLoc dl(Op);  // FIXME probably not meaningful
11948   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11949   const X86RegisterInfo *RegInfo =
11950     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11951   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11952   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11953           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11954          "Invalid Frame Register!");
11955   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11956   while (Depth--)
11957     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11958                             MachinePointerInfo(),
11959                             false, false, false, 0);
11960   return FrameAddr;
11961 }
11962
11963 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11964                                                      SelectionDAG &DAG) const {
11965   const X86RegisterInfo *RegInfo =
11966     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11967   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11968 }
11969
11970 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11971   SDValue Chain     = Op.getOperand(0);
11972   SDValue Offset    = Op.getOperand(1);
11973   SDValue Handler   = Op.getOperand(2);
11974   SDLoc dl      (Op);
11975
11976   EVT PtrVT = getPointerTy();
11977   const X86RegisterInfo *RegInfo =
11978     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11979   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11980   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11981           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11982          "Invalid Frame Register!");
11983   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11984   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11985
11986   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11987                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11988   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11989   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11990                        false, false, 0);
11991   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11992
11993   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11994                      DAG.getRegister(StoreAddrReg, PtrVT));
11995 }
11996
11997 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11998                                                SelectionDAG &DAG) const {
11999   SDLoc DL(Op);
12000   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12001                      DAG.getVTList(MVT::i32, MVT::Other),
12002                      Op.getOperand(0), Op.getOperand(1));
12003 }
12004
12005 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12006                                                 SelectionDAG &DAG) const {
12007   SDLoc DL(Op);
12008   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12009                      Op.getOperand(0), Op.getOperand(1));
12010 }
12011
12012 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12013   return Op.getOperand(0);
12014 }
12015
12016 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12017                                                 SelectionDAG &DAG) const {
12018   SDValue Root = Op.getOperand(0);
12019   SDValue Trmp = Op.getOperand(1); // trampoline
12020   SDValue FPtr = Op.getOperand(2); // nested function
12021   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12022   SDLoc dl (Op);
12023
12024   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12025   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12026
12027   if (Subtarget->is64Bit()) {
12028     SDValue OutChains[6];
12029
12030     // Large code-model.
12031     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12032     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12033
12034     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12035     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12036
12037     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12038
12039     // Load the pointer to the nested function into R11.
12040     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12041     SDValue Addr = Trmp;
12042     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12043                                 Addr, MachinePointerInfo(TrmpAddr),
12044                                 false, false, 0);
12045
12046     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12047                        DAG.getConstant(2, MVT::i64));
12048     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12049                                 MachinePointerInfo(TrmpAddr, 2),
12050                                 false, false, 2);
12051
12052     // Load the 'nest' parameter value into R10.
12053     // R10 is specified in X86CallingConv.td
12054     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12055     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12056                        DAG.getConstant(10, MVT::i64));
12057     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12058                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12059                                 false, false, 0);
12060
12061     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12062                        DAG.getConstant(12, MVT::i64));
12063     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12064                                 MachinePointerInfo(TrmpAddr, 12),
12065                                 false, false, 2);
12066
12067     // Jump to the nested function.
12068     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12069     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12070                        DAG.getConstant(20, MVT::i64));
12071     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12072                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12073                                 false, false, 0);
12074
12075     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12076     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12077                        DAG.getConstant(22, MVT::i64));
12078     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12079                                 MachinePointerInfo(TrmpAddr, 22),
12080                                 false, false, 0);
12081
12082     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12083   } else {
12084     const Function *Func =
12085       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12086     CallingConv::ID CC = Func->getCallingConv();
12087     unsigned NestReg;
12088
12089     switch (CC) {
12090     default:
12091       llvm_unreachable("Unsupported calling convention");
12092     case CallingConv::C:
12093     case CallingConv::X86_StdCall: {
12094       // Pass 'nest' parameter in ECX.
12095       // Must be kept in sync with X86CallingConv.td
12096       NestReg = X86::ECX;
12097
12098       // Check that ECX wasn't needed by an 'inreg' parameter.
12099       FunctionType *FTy = Func->getFunctionType();
12100       const AttributeSet &Attrs = Func->getAttributes();
12101
12102       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12103         unsigned InRegCount = 0;
12104         unsigned Idx = 1;
12105
12106         for (FunctionType::param_iterator I = FTy->param_begin(),
12107              E = FTy->param_end(); I != E; ++I, ++Idx)
12108           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12109             // FIXME: should only count parameters that are lowered to integers.
12110             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12111
12112         if (InRegCount > 2) {
12113           report_fatal_error("Nest register in use - reduce number of inreg"
12114                              " parameters!");
12115         }
12116       }
12117       break;
12118     }
12119     case CallingConv::X86_FastCall:
12120     case CallingConv::X86_ThisCall:
12121     case CallingConv::Fast:
12122       // Pass 'nest' parameter in EAX.
12123       // Must be kept in sync with X86CallingConv.td
12124       NestReg = X86::EAX;
12125       break;
12126     }
12127
12128     SDValue OutChains[4];
12129     SDValue Addr, Disp;
12130
12131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12132                        DAG.getConstant(10, MVT::i32));
12133     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12134
12135     // This is storing the opcode for MOV32ri.
12136     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12137     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12138     OutChains[0] = DAG.getStore(Root, dl,
12139                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12140                                 Trmp, MachinePointerInfo(TrmpAddr),
12141                                 false, false, 0);
12142
12143     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12144                        DAG.getConstant(1, MVT::i32));
12145     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12146                                 MachinePointerInfo(TrmpAddr, 1),
12147                                 false, false, 1);
12148
12149     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12150     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12151                        DAG.getConstant(5, MVT::i32));
12152     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12153                                 MachinePointerInfo(TrmpAddr, 5),
12154                                 false, false, 1);
12155
12156     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12157                        DAG.getConstant(6, MVT::i32));
12158     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12159                                 MachinePointerInfo(TrmpAddr, 6),
12160                                 false, false, 1);
12161
12162     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12163   }
12164 }
12165
12166 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12167                                             SelectionDAG &DAG) const {
12168   /*
12169    The rounding mode is in bits 11:10 of FPSR, and has the following
12170    settings:
12171      00 Round to nearest
12172      01 Round to -inf
12173      10 Round to +inf
12174      11 Round to 0
12175
12176   FLT_ROUNDS, on the other hand, expects the following:
12177     -1 Undefined
12178      0 Round to 0
12179      1 Round to nearest
12180      2 Round to +inf
12181      3 Round to -inf
12182
12183   To perform the conversion, we do:
12184     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12185   */
12186
12187   MachineFunction &MF = DAG.getMachineFunction();
12188   const TargetMachine &TM = MF.getTarget();
12189   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12190   unsigned StackAlignment = TFI.getStackAlignment();
12191   EVT VT = Op.getValueType();
12192   SDLoc DL(Op);
12193
12194   // Save FP Control Word to stack slot
12195   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12196   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12197
12198   MachineMemOperand *MMO =
12199    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12200                            MachineMemOperand::MOStore, 2, 2);
12201
12202   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12203   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12204                                           DAG.getVTList(MVT::Other),
12205                                           Ops, array_lengthof(Ops), MVT::i16,
12206                                           MMO);
12207
12208   // Load FP Control Word from stack slot
12209   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12210                             MachinePointerInfo(), false, false, false, 0);
12211
12212   // Transform as necessary
12213   SDValue CWD1 =
12214     DAG.getNode(ISD::SRL, DL, MVT::i16,
12215                 DAG.getNode(ISD::AND, DL, MVT::i16,
12216                             CWD, DAG.getConstant(0x800, MVT::i16)),
12217                 DAG.getConstant(11, MVT::i8));
12218   SDValue CWD2 =
12219     DAG.getNode(ISD::SRL, DL, MVT::i16,
12220                 DAG.getNode(ISD::AND, DL, MVT::i16,
12221                             CWD, DAG.getConstant(0x400, MVT::i16)),
12222                 DAG.getConstant(9, MVT::i8));
12223
12224   SDValue RetVal =
12225     DAG.getNode(ISD::AND, DL, MVT::i16,
12226                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12227                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12228                             DAG.getConstant(1, MVT::i16)),
12229                 DAG.getConstant(3, MVT::i16));
12230
12231   return DAG.getNode((VT.getSizeInBits() < 16 ?
12232                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12233 }
12234
12235 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12236   EVT VT = Op.getValueType();
12237   EVT OpVT = VT;
12238   unsigned NumBits = VT.getSizeInBits();
12239   SDLoc dl(Op);
12240
12241   Op = Op.getOperand(0);
12242   if (VT == MVT::i8) {
12243     // Zero extend to i32 since there is not an i8 bsr.
12244     OpVT = MVT::i32;
12245     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12246   }
12247
12248   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12249   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12250   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12251
12252   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12253   SDValue Ops[] = {
12254     Op,
12255     DAG.getConstant(NumBits+NumBits-1, OpVT),
12256     DAG.getConstant(X86::COND_E, MVT::i8),
12257     Op.getValue(1)
12258   };
12259   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12260
12261   // Finally xor with NumBits-1.
12262   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12263
12264   if (VT == MVT::i8)
12265     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12266   return Op;
12267 }
12268
12269 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12270   EVT VT = Op.getValueType();
12271   EVT OpVT = VT;
12272   unsigned NumBits = VT.getSizeInBits();
12273   SDLoc dl(Op);
12274
12275   Op = Op.getOperand(0);
12276   if (VT == MVT::i8) {
12277     // Zero extend to i32 since there is not an i8 bsr.
12278     OpVT = MVT::i32;
12279     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12280   }
12281
12282   // Issue a bsr (scan bits in reverse).
12283   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12284   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12285
12286   // And xor with NumBits-1.
12287   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12288
12289   if (VT == MVT::i8)
12290     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12291   return Op;
12292 }
12293
12294 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12295   EVT VT = Op.getValueType();
12296   unsigned NumBits = VT.getSizeInBits();
12297   SDLoc dl(Op);
12298   Op = Op.getOperand(0);
12299
12300   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12301   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12302   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12303
12304   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12305   SDValue Ops[] = {
12306     Op,
12307     DAG.getConstant(NumBits, VT),
12308     DAG.getConstant(X86::COND_E, MVT::i8),
12309     Op.getValue(1)
12310   };
12311   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12312 }
12313
12314 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12315 // ones, and then concatenate the result back.
12316 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12317   EVT VT = Op.getValueType();
12318
12319   assert(VT.is256BitVector() && VT.isInteger() &&
12320          "Unsupported value type for operation");
12321
12322   unsigned NumElems = VT.getVectorNumElements();
12323   SDLoc dl(Op);
12324
12325   // Extract the LHS vectors
12326   SDValue LHS = Op.getOperand(0);
12327   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12328   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12329
12330   // Extract the RHS vectors
12331   SDValue RHS = Op.getOperand(1);
12332   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12333   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12334
12335   MVT EltVT = VT.getVectorElementType().getSimpleVT();
12336   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12337
12338   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12339                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12340                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12341 }
12342
12343 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12344   assert(Op.getValueType().is256BitVector() &&
12345          Op.getValueType().isInteger() &&
12346          "Only handle AVX 256-bit vector integer operation");
12347   return Lower256IntArith(Op, DAG);
12348 }
12349
12350 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12351   assert(Op.getValueType().is256BitVector() &&
12352          Op.getValueType().isInteger() &&
12353          "Only handle AVX 256-bit vector integer operation");
12354   return Lower256IntArith(Op, DAG);
12355 }
12356
12357 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12358                         SelectionDAG &DAG) {
12359   SDLoc dl(Op);
12360   EVT VT = Op.getValueType();
12361
12362   // Decompose 256-bit ops into smaller 128-bit ops.
12363   if (VT.is256BitVector() && !Subtarget->hasInt256())
12364     return Lower256IntArith(Op, DAG);
12365
12366   SDValue A = Op.getOperand(0);
12367   SDValue B = Op.getOperand(1);
12368
12369   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12370   if (VT == MVT::v4i32) {
12371     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12372            "Should not custom lower when pmuldq is available!");
12373
12374     // Extract the odd parts.
12375     static const int UnpackMask[] = { 1, -1, 3, -1 };
12376     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12377     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12378
12379     // Multiply the even parts.
12380     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12381     // Now multiply odd parts.
12382     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12383
12384     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12385     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12386
12387     // Merge the two vectors back together with a shuffle. This expands into 2
12388     // shuffles.
12389     static const int ShufMask[] = { 0, 4, 2, 6 };
12390     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12391   }
12392
12393   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
12394          "Only know how to lower V2I64/V4I64 multiply");
12395
12396   //  Ahi = psrlqi(a, 32);
12397   //  Bhi = psrlqi(b, 32);
12398   //
12399   //  AloBlo = pmuludq(a, b);
12400   //  AloBhi = pmuludq(a, Bhi);
12401   //  AhiBlo = pmuludq(Ahi, b);
12402
12403   //  AloBhi = psllqi(AloBhi, 32);
12404   //  AhiBlo = psllqi(AhiBlo, 32);
12405   //  return AloBlo + AloBhi + AhiBlo;
12406
12407   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
12408
12409   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
12410   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
12411
12412   // Bit cast to 32-bit vectors for MULUDQ
12413   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
12414   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12415   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12416   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12417   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12418
12419   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12420   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12421   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12422
12423   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
12424   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
12425
12426   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12427   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12428 }
12429
12430 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12431   EVT VT = Op.getValueType();
12432   EVT EltTy = VT.getVectorElementType();
12433   unsigned NumElts = VT.getVectorNumElements();
12434   SDValue N0 = Op.getOperand(0);
12435   SDLoc dl(Op);
12436
12437   // Lower sdiv X, pow2-const.
12438   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12439   if (!C)
12440     return SDValue();
12441
12442   APInt SplatValue, SplatUndef;
12443   unsigned SplatBitSize;
12444   bool HasAnyUndefs;
12445   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12446                           HasAnyUndefs) ||
12447       EltTy.getSizeInBits() < SplatBitSize)
12448     return SDValue();
12449
12450   if ((SplatValue != 0) &&
12451       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12452     unsigned lg2 = SplatValue.countTrailingZeros();
12453     // Splat the sign bit.
12454     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
12455     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
12456     // Add (N0 < 0) ? abs2 - 1 : 0;
12457     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
12458     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
12459     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12460     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
12461     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
12462
12463     // If we're dividing by a positive value, we're done.  Otherwise, we must
12464     // negate the result.
12465     if (SplatValue.isNonNegative())
12466       return SRA;
12467
12468     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12469     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12470     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12471   }
12472   return SDValue();
12473 }
12474
12475 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12476                                          const X86Subtarget *Subtarget) {
12477   EVT VT = Op.getValueType();
12478   SDLoc dl(Op);
12479   SDValue R = Op.getOperand(0);
12480   SDValue Amt = Op.getOperand(1);
12481
12482   // Optimize shl/srl/sra with constant shift amount.
12483   if (isSplatVector(Amt.getNode())) {
12484     SDValue SclrAmt = Amt->getOperand(0);
12485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12486       uint64_t ShiftAmt = C->getZExtValue();
12487
12488       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12489           (Subtarget->hasInt256() &&
12490            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12491           (Subtarget->hasAVX512() &&
12492            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12493         if (Op.getOpcode() == ISD::SHL)
12494           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12495                              DAG.getConstant(ShiftAmt, MVT::i32));
12496         if (Op.getOpcode() == ISD::SRL)
12497           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12498                              DAG.getConstant(ShiftAmt, MVT::i32));
12499         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12500           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12501                              DAG.getConstant(ShiftAmt, MVT::i32));
12502       }
12503
12504       if (VT == MVT::v16i8) {
12505         if (Op.getOpcode() == ISD::SHL) {
12506           // Make a large shift.
12507           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12508                                     DAG.getConstant(ShiftAmt, MVT::i32));
12509           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12510           // Zero out the rightmost bits.
12511           SmallVector<SDValue, 16> V(16,
12512                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12513                                                      MVT::i8));
12514           return DAG.getNode(ISD::AND, dl, VT, SHL,
12515                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12516         }
12517         if (Op.getOpcode() == ISD::SRL) {
12518           // Make a large shift.
12519           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12520                                     DAG.getConstant(ShiftAmt, MVT::i32));
12521           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12522           // Zero out the leftmost bits.
12523           SmallVector<SDValue, 16> V(16,
12524                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12525                                                      MVT::i8));
12526           return DAG.getNode(ISD::AND, dl, VT, SRL,
12527                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12528         }
12529         if (Op.getOpcode() == ISD::SRA) {
12530           if (ShiftAmt == 7) {
12531             // R s>> 7  ===  R s< 0
12532             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12533             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12534           }
12535
12536           // R s>> a === ((R u>> a) ^ m) - m
12537           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12538           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12539                                                          MVT::i8));
12540           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12541           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12542           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12543           return Res;
12544         }
12545         llvm_unreachable("Unknown shift opcode.");
12546       }
12547
12548       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12549         if (Op.getOpcode() == ISD::SHL) {
12550           // Make a large shift.
12551           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12552                                     DAG.getConstant(ShiftAmt, MVT::i32));
12553           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12554           // Zero out the rightmost bits.
12555           SmallVector<SDValue, 32> V(32,
12556                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12557                                                      MVT::i8));
12558           return DAG.getNode(ISD::AND, dl, VT, SHL,
12559                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12560         }
12561         if (Op.getOpcode() == ISD::SRL) {
12562           // Make a large shift.
12563           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12564                                     DAG.getConstant(ShiftAmt, MVT::i32));
12565           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12566           // Zero out the leftmost bits.
12567           SmallVector<SDValue, 32> V(32,
12568                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12569                                                      MVT::i8));
12570           return DAG.getNode(ISD::AND, dl, VT, SRL,
12571                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12572         }
12573         if (Op.getOpcode() == ISD::SRA) {
12574           if (ShiftAmt == 7) {
12575             // R s>> 7  ===  R s< 0
12576             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12577             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12578           }
12579
12580           // R s>> a === ((R u>> a) ^ m) - m
12581           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12582           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12583                                                          MVT::i8));
12584           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12585           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12586           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12587           return Res;
12588         }
12589         llvm_unreachable("Unknown shift opcode.");
12590       }
12591     }
12592   }
12593
12594   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12595   if (!Subtarget->is64Bit() &&
12596       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12597       Amt.getOpcode() == ISD::BITCAST &&
12598       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12599     Amt = Amt.getOperand(0);
12600     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12601                      VT.getVectorNumElements();
12602     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12603     uint64_t ShiftAmt = 0;
12604     for (unsigned i = 0; i != Ratio; ++i) {
12605       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12606       if (C == 0)
12607         return SDValue();
12608       // 6 == Log2(64)
12609       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12610     }
12611     // Check remaining shift amounts.
12612     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12613       uint64_t ShAmt = 0;
12614       for (unsigned j = 0; j != Ratio; ++j) {
12615         ConstantSDNode *C =
12616           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12617         if (C == 0)
12618           return SDValue();
12619         // 6 == Log2(64)
12620         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12621       }
12622       if (ShAmt != ShiftAmt)
12623         return SDValue();
12624     }
12625     switch (Op.getOpcode()) {
12626     default:
12627       llvm_unreachable("Unknown shift opcode!");
12628     case ISD::SHL:
12629       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12630                          DAG.getConstant(ShiftAmt, MVT::i32));
12631     case ISD::SRL:
12632       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12633                          DAG.getConstant(ShiftAmt, MVT::i32));
12634     case ISD::SRA:
12635       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12636                          DAG.getConstant(ShiftAmt, MVT::i32));
12637     }
12638   }
12639
12640   return SDValue();
12641 }
12642
12643 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12644                                         const X86Subtarget* Subtarget) {
12645   EVT VT = Op.getValueType();
12646   SDLoc dl(Op);
12647   SDValue R = Op.getOperand(0);
12648   SDValue Amt = Op.getOperand(1);
12649
12650   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12651       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12652       (Subtarget->hasInt256() &&
12653        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12654         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12655        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12656     SDValue BaseShAmt;
12657     EVT EltVT = VT.getVectorElementType();
12658
12659     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12660       unsigned NumElts = VT.getVectorNumElements();
12661       unsigned i, j;
12662       for (i = 0; i != NumElts; ++i) {
12663         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12664           continue;
12665         break;
12666       }
12667       for (j = i; j != NumElts; ++j) {
12668         SDValue Arg = Amt.getOperand(j);
12669         if (Arg.getOpcode() == ISD::UNDEF) continue;
12670         if (Arg != Amt.getOperand(i))
12671           break;
12672       }
12673       if (i != NumElts && j == NumElts)
12674         BaseShAmt = Amt.getOperand(i);
12675     } else {
12676       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12677         Amt = Amt.getOperand(0);
12678       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12679                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12680         SDValue InVec = Amt.getOperand(0);
12681         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12682           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12683           unsigned i = 0;
12684           for (; i != NumElts; ++i) {
12685             SDValue Arg = InVec.getOperand(i);
12686             if (Arg.getOpcode() == ISD::UNDEF) continue;
12687             BaseShAmt = Arg;
12688             break;
12689           }
12690         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12691            if (ConstantSDNode *C =
12692                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12693              unsigned SplatIdx =
12694                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12695              if (C->getZExtValue() == SplatIdx)
12696                BaseShAmt = InVec.getOperand(1);
12697            }
12698         }
12699         if (BaseShAmt.getNode() == 0)
12700           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12701                                   DAG.getIntPtrConstant(0));
12702       }
12703     }
12704
12705     if (BaseShAmt.getNode()) {
12706       if (EltVT.bitsGT(MVT::i32))
12707         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12708       else if (EltVT.bitsLT(MVT::i32))
12709         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12710
12711       switch (Op.getOpcode()) {
12712       default:
12713         llvm_unreachable("Unknown shift opcode!");
12714       case ISD::SHL:
12715         switch (VT.getSimpleVT().SimpleTy) {
12716         default: return SDValue();
12717         case MVT::v2i64:
12718         case MVT::v4i32:
12719         case MVT::v8i16:
12720         case MVT::v4i64:
12721         case MVT::v8i32:
12722         case MVT::v16i16:
12723         case MVT::v16i32:
12724         case MVT::v8i64:
12725           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12726         }
12727       case ISD::SRA:
12728         switch (VT.getSimpleVT().SimpleTy) {
12729         default: return SDValue();
12730         case MVT::v4i32:
12731         case MVT::v8i16:
12732         case MVT::v8i32:
12733         case MVT::v16i16:
12734         case MVT::v16i32:
12735         case MVT::v8i64:
12736           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12737         }
12738       case ISD::SRL:
12739         switch (VT.getSimpleVT().SimpleTy) {
12740         default: return SDValue();
12741         case MVT::v2i64:
12742         case MVT::v4i32:
12743         case MVT::v8i16:
12744         case MVT::v4i64:
12745         case MVT::v8i32:
12746         case MVT::v16i16:
12747         case MVT::v16i32:
12748         case MVT::v8i64:
12749           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12750         }
12751       }
12752     }
12753   }
12754
12755   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12756   if (!Subtarget->is64Bit() &&
12757       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
12758       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
12759       Amt.getOpcode() == ISD::BITCAST &&
12760       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12761     Amt = Amt.getOperand(0);
12762     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12763                      VT.getVectorNumElements();
12764     std::vector<SDValue> Vals(Ratio);
12765     for (unsigned i = 0; i != Ratio; ++i)
12766       Vals[i] = Amt.getOperand(i);
12767     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12768       for (unsigned j = 0; j != Ratio; ++j)
12769         if (Vals[j] != Amt.getOperand(i + j))
12770           return SDValue();
12771     }
12772     switch (Op.getOpcode()) {
12773     default:
12774       llvm_unreachable("Unknown shift opcode!");
12775     case ISD::SHL:
12776       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12777     case ISD::SRL:
12778       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12779     case ISD::SRA:
12780       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12781     }
12782   }
12783
12784   return SDValue();
12785 }
12786
12787 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
12788                           SelectionDAG &DAG) {
12789
12790   EVT VT = Op.getValueType();
12791   SDLoc dl(Op);
12792   SDValue R = Op.getOperand(0);
12793   SDValue Amt = Op.getOperand(1);
12794   SDValue V;
12795
12796   if (!Subtarget->hasSSE2())
12797     return SDValue();
12798
12799   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12800   if (V.getNode())
12801     return V;
12802
12803   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12804   if (V.getNode())
12805       return V;
12806
12807   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
12808     return Op;
12809   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12810   if (Subtarget->hasInt256()) {
12811     if (Op.getOpcode() == ISD::SRL &&
12812         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12813          VT == MVT::v4i64 || VT == MVT::v8i32))
12814       return Op;
12815     if (Op.getOpcode() == ISD::SHL &&
12816         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12817          VT == MVT::v4i64 || VT == MVT::v8i32))
12818       return Op;
12819     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12820       return Op;
12821   }
12822
12823   // Lower SHL with variable shift amount.
12824   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12825     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12826
12827     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12828     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12829     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12830     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12831   }
12832   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12833     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12834
12835     // a = a << 5;
12836     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12837     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12838
12839     // Turn 'a' into a mask suitable for VSELECT
12840     SDValue VSelM = DAG.getConstant(0x80, VT);
12841     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12842     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12843
12844     SDValue CM1 = DAG.getConstant(0x0f, VT);
12845     SDValue CM2 = DAG.getConstant(0x3f, VT);
12846
12847     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12848     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12849     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12850                             DAG.getConstant(4, MVT::i32), DAG);
12851     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12852     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12853
12854     // a += a
12855     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12856     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12857     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12858
12859     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12860     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12861     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12862                             DAG.getConstant(2, MVT::i32), DAG);
12863     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12864     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12865
12866     // a += a
12867     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12868     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12869     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12870
12871     // return VSELECT(r, r+r, a);
12872     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12873                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12874     return R;
12875   }
12876
12877   // Decompose 256-bit shifts into smaller 128-bit shifts.
12878   if (VT.is256BitVector()) {
12879     unsigned NumElems = VT.getVectorNumElements();
12880     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12881     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12882
12883     // Extract the two vectors
12884     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12885     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12886
12887     // Recreate the shift amount vectors
12888     SDValue Amt1, Amt2;
12889     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12890       // Constant shift amount
12891       SmallVector<SDValue, 4> Amt1Csts;
12892       SmallVector<SDValue, 4> Amt2Csts;
12893       for (unsigned i = 0; i != NumElems/2; ++i)
12894         Amt1Csts.push_back(Amt->getOperand(i));
12895       for (unsigned i = NumElems/2; i != NumElems; ++i)
12896         Amt2Csts.push_back(Amt->getOperand(i));
12897
12898       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12899                                  &Amt1Csts[0], NumElems/2);
12900       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12901                                  &Amt2Csts[0], NumElems/2);
12902     } else {
12903       // Variable shift amount
12904       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12905       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12906     }
12907
12908     // Issue new vector shifts for the smaller types
12909     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12910     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12911
12912     // Concatenate the result back
12913     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12914   }
12915
12916   return SDValue();
12917 }
12918
12919 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12920   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12921   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12922   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12923   // has only one use.
12924   SDNode *N = Op.getNode();
12925   SDValue LHS = N->getOperand(0);
12926   SDValue RHS = N->getOperand(1);
12927   unsigned BaseOp = 0;
12928   unsigned Cond = 0;
12929   SDLoc DL(Op);
12930   switch (Op.getOpcode()) {
12931   default: llvm_unreachable("Unknown ovf instruction!");
12932   case ISD::SADDO:
12933     // A subtract of one will be selected as a INC. Note that INC doesn't
12934     // set CF, so we can't do this for UADDO.
12935     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12936       if (C->isOne()) {
12937         BaseOp = X86ISD::INC;
12938         Cond = X86::COND_O;
12939         break;
12940       }
12941     BaseOp = X86ISD::ADD;
12942     Cond = X86::COND_O;
12943     break;
12944   case ISD::UADDO:
12945     BaseOp = X86ISD::ADD;
12946     Cond = X86::COND_B;
12947     break;
12948   case ISD::SSUBO:
12949     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12950     // set CF, so we can't do this for USUBO.
12951     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12952       if (C->isOne()) {
12953         BaseOp = X86ISD::DEC;
12954         Cond = X86::COND_O;
12955         break;
12956       }
12957     BaseOp = X86ISD::SUB;
12958     Cond = X86::COND_O;
12959     break;
12960   case ISD::USUBO:
12961     BaseOp = X86ISD::SUB;
12962     Cond = X86::COND_B;
12963     break;
12964   case ISD::SMULO:
12965     BaseOp = X86ISD::SMUL;
12966     Cond = X86::COND_O;
12967     break;
12968   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12969     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12970                                  MVT::i32);
12971     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12972
12973     SDValue SetCC =
12974       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12975                   DAG.getConstant(X86::COND_O, MVT::i32),
12976                   SDValue(Sum.getNode(), 2));
12977
12978     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12979   }
12980   }
12981
12982   // Also sets EFLAGS.
12983   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12984   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12985
12986   SDValue SetCC =
12987     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12988                 DAG.getConstant(Cond, MVT::i32),
12989                 SDValue(Sum.getNode(), 1));
12990
12991   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12992 }
12993
12994 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12995                                                   SelectionDAG &DAG) const {
12996   SDLoc dl(Op);
12997   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12998   EVT VT = Op.getValueType();
12999
13000   if (!Subtarget->hasSSE2() || !VT.isVector())
13001     return SDValue();
13002
13003   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13004                       ExtraVT.getScalarType().getSizeInBits();
13005   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
13006
13007   switch (VT.getSimpleVT().SimpleTy) {
13008     default: return SDValue();
13009     case MVT::v8i32:
13010     case MVT::v16i16:
13011       if (!Subtarget->hasFp256())
13012         return SDValue();
13013       if (!Subtarget->hasInt256()) {
13014         // needs to be split
13015         unsigned NumElems = VT.getVectorNumElements();
13016
13017         // Extract the LHS vectors
13018         SDValue LHS = Op.getOperand(0);
13019         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13020         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13021
13022         MVT EltVT = VT.getVectorElementType().getSimpleVT();
13023         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13024
13025         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13026         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13027         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13028                                    ExtraNumElems/2);
13029         SDValue Extra = DAG.getValueType(ExtraVT);
13030
13031         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13032         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13033
13034         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13035       }
13036       // fall through
13037     case MVT::v4i32:
13038     case MVT::v8i16: {
13039       // (sext (vzext x)) -> (vsext x)
13040       SDValue Op0 = Op.getOperand(0);
13041       SDValue Op00 = Op0.getOperand(0);
13042       SDValue Tmp1;
13043       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13044       if (Op0.getOpcode() == ISD::BITCAST &&
13045           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
13046         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13047       if (Tmp1.getNode()) {
13048         SDValue Tmp1Op0 = Tmp1.getOperand(0);
13049         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13050                "This optimization is invalid without a VZEXT.");
13051         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13052       }
13053
13054       // If the above didn't work, then just use Shift-Left + Shift-Right.
13055       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
13056       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
13057     }
13058   }
13059 }
13060
13061 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13062                                  SelectionDAG &DAG) {
13063   SDLoc dl(Op);
13064   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13065     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13066   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13067     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13068
13069   // The only fence that needs an instruction is a sequentially-consistent
13070   // cross-thread fence.
13071   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13072     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13073     // no-sse2). There isn't any reason to disable it if the target processor
13074     // supports it.
13075     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13076       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13077
13078     SDValue Chain = Op.getOperand(0);
13079     SDValue Zero = DAG.getConstant(0, MVT::i32);
13080     SDValue Ops[] = {
13081       DAG.getRegister(X86::ESP, MVT::i32), // Base
13082       DAG.getTargetConstant(1, MVT::i8),   // Scale
13083       DAG.getRegister(0, MVT::i32),        // Index
13084       DAG.getTargetConstant(0, MVT::i32),  // Disp
13085       DAG.getRegister(0, MVT::i32),        // Segment.
13086       Zero,
13087       Chain
13088     };
13089     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13090     return SDValue(Res, 0);
13091   }
13092
13093   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13094   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13095 }
13096
13097 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13098                              SelectionDAG &DAG) {
13099   EVT T = Op.getValueType();
13100   SDLoc DL(Op);
13101   unsigned Reg = 0;
13102   unsigned size = 0;
13103   switch(T.getSimpleVT().SimpleTy) {
13104   default: llvm_unreachable("Invalid value type!");
13105   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13106   case MVT::i16: Reg = X86::AX;  size = 2; break;
13107   case MVT::i32: Reg = X86::EAX; size = 4; break;
13108   case MVT::i64:
13109     assert(Subtarget->is64Bit() && "Node not type legal!");
13110     Reg = X86::RAX; size = 8;
13111     break;
13112   }
13113   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13114                                     Op.getOperand(2), SDValue());
13115   SDValue Ops[] = { cpIn.getValue(0),
13116                     Op.getOperand(1),
13117                     Op.getOperand(3),
13118                     DAG.getTargetConstant(size, MVT::i8),
13119                     cpIn.getValue(1) };
13120   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13121   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13122   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13123                                            Ops, array_lengthof(Ops), T, MMO);
13124   SDValue cpOut =
13125     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13126   return cpOut;
13127 }
13128
13129 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13130                                      SelectionDAG &DAG) {
13131   assert(Subtarget->is64Bit() && "Result not type legalized?");
13132   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13133   SDValue TheChain = Op.getOperand(0);
13134   SDLoc dl(Op);
13135   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13136   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13137   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13138                                    rax.getValue(2));
13139   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13140                             DAG.getConstant(32, MVT::i8));
13141   SDValue Ops[] = {
13142     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13143     rdx.getValue(1)
13144   };
13145   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13146 }
13147
13148 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13149                             SelectionDAG &DAG) {
13150   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13151   MVT DstVT = Op.getSimpleValueType();
13152   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13153          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13154   assert((DstVT == MVT::i64 ||
13155           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13156          "Unexpected custom BITCAST");
13157   // i64 <=> MMX conversions are Legal.
13158   if (SrcVT==MVT::i64 && DstVT.isVector())
13159     return Op;
13160   if (DstVT==MVT::i64 && SrcVT.isVector())
13161     return Op;
13162   // MMX <=> MMX conversions are Legal.
13163   if (SrcVT.isVector() && DstVT.isVector())
13164     return Op;
13165   // All other conversions need to be expanded.
13166   return SDValue();
13167 }
13168
13169 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13170   SDNode *Node = Op.getNode();
13171   SDLoc dl(Node);
13172   EVT T = Node->getValueType(0);
13173   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13174                               DAG.getConstant(0, T), Node->getOperand(2));
13175   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13176                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13177                        Node->getOperand(0),
13178                        Node->getOperand(1), negOp,
13179                        cast<AtomicSDNode>(Node)->getSrcValue(),
13180                        cast<AtomicSDNode>(Node)->getAlignment(),
13181                        cast<AtomicSDNode>(Node)->getOrdering(),
13182                        cast<AtomicSDNode>(Node)->getSynchScope());
13183 }
13184
13185 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13186   SDNode *Node = Op.getNode();
13187   SDLoc dl(Node);
13188   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13189
13190   // Convert seq_cst store -> xchg
13191   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13192   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13193   //        (The only way to get a 16-byte store is cmpxchg16b)
13194   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13195   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13196       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13197     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13198                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13199                                  Node->getOperand(0),
13200                                  Node->getOperand(1), Node->getOperand(2),
13201                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13202                                  cast<AtomicSDNode>(Node)->getOrdering(),
13203                                  cast<AtomicSDNode>(Node)->getSynchScope());
13204     return Swap.getValue(1);
13205   }
13206   // Other atomic stores have a simple pattern.
13207   return Op;
13208 }
13209
13210 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13211   EVT VT = Op.getNode()->getValueType(0);
13212
13213   // Let legalize expand this if it isn't a legal type yet.
13214   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13215     return SDValue();
13216
13217   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13218
13219   unsigned Opc;
13220   bool ExtraOp = false;
13221   switch (Op.getOpcode()) {
13222   default: llvm_unreachable("Invalid code");
13223   case ISD::ADDC: Opc = X86ISD::ADD; break;
13224   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13225   case ISD::SUBC: Opc = X86ISD::SUB; break;
13226   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13227   }
13228
13229   if (!ExtraOp)
13230     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13231                        Op.getOperand(1));
13232   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13233                      Op.getOperand(1), Op.getOperand(2));
13234 }
13235
13236 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13237                             SelectionDAG &DAG) {
13238   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13239
13240   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13241   // which returns the values as { float, float } (in XMM0) or
13242   // { double, double } (which is returned in XMM0, XMM1).
13243   SDLoc dl(Op);
13244   SDValue Arg = Op.getOperand(0);
13245   EVT ArgVT = Arg.getValueType();
13246   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13247
13248   TargetLowering::ArgListTy Args;
13249   TargetLowering::ArgListEntry Entry;
13250
13251   Entry.Node = Arg;
13252   Entry.Ty = ArgTy;
13253   Entry.isSExt = false;
13254   Entry.isZExt = false;
13255   Args.push_back(Entry);
13256
13257   bool isF64 = ArgVT == MVT::f64;
13258   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13259   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13260   // the results are returned via SRet in memory.
13261   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13263   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13264
13265   Type *RetTy = isF64
13266     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13267     : (Type*)VectorType::get(ArgTy, 4);
13268   TargetLowering::
13269     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13270                          false, false, false, false, 0,
13271                          CallingConv::C, /*isTaillCall=*/false,
13272                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13273                          Callee, Args, DAG, dl);
13274   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13275
13276   if (isF64)
13277     // Returned in xmm0 and xmm1.
13278     return CallResult.first;
13279
13280   // Returned in bits 0:31 and 32:64 xmm0.
13281   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13282                                CallResult.first, DAG.getIntPtrConstant(0));
13283   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13284                                CallResult.first, DAG.getIntPtrConstant(1));
13285   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13286   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13287 }
13288
13289 /// LowerOperation - Provide custom lowering hooks for some operations.
13290 ///
13291 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13292   switch (Op.getOpcode()) {
13293   default: llvm_unreachable("Should not custom lower this!");
13294   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13295   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13296   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13297   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13298   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13299   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13300   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13301   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13302   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13303   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13304   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13305   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13306   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13307   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13308   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13309   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13310   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13311   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13312   case ISD::SHL_PARTS:
13313   case ISD::SRA_PARTS:
13314   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13315   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13316   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13317   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13318   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13319   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13320   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13321   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13322   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13323   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13324   case ISD::FABS:               return LowerFABS(Op, DAG);
13325   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13326   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13327   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13328   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13329   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13330   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13331   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13332   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13333   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13334   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13335   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13336   case ISD::INTRINSIC_VOID:
13337   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13338   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13339   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13340   case ISD::FRAME_TO_ARGS_OFFSET:
13341                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13342   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13343   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13344   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13345   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13346   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13347   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13348   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13349   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13350   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13351   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13352   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13353   case ISD::SRA:
13354   case ISD::SRL:
13355   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13356   case ISD::SADDO:
13357   case ISD::UADDO:
13358   case ISD::SSUBO:
13359   case ISD::USUBO:
13360   case ISD::SMULO:
13361   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13362   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13363   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13364   case ISD::ADDC:
13365   case ISD::ADDE:
13366   case ISD::SUBC:
13367   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13368   case ISD::ADD:                return LowerADD(Op, DAG);
13369   case ISD::SUB:                return LowerSUB(Op, DAG);
13370   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13371   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13372   }
13373 }
13374
13375 static void ReplaceATOMIC_LOAD(SDNode *Node,
13376                                   SmallVectorImpl<SDValue> &Results,
13377                                   SelectionDAG &DAG) {
13378   SDLoc dl(Node);
13379   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13380
13381   // Convert wide load -> cmpxchg8b/cmpxchg16b
13382   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13383   //        (The only way to get a 16-byte load is cmpxchg16b)
13384   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13385   SDValue Zero = DAG.getConstant(0, VT);
13386   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13387                                Node->getOperand(0),
13388                                Node->getOperand(1), Zero, Zero,
13389                                cast<AtomicSDNode>(Node)->getMemOperand(),
13390                                cast<AtomicSDNode>(Node)->getOrdering(),
13391                                cast<AtomicSDNode>(Node)->getSynchScope());
13392   Results.push_back(Swap.getValue(0));
13393   Results.push_back(Swap.getValue(1));
13394 }
13395
13396 static void
13397 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13398                         SelectionDAG &DAG, unsigned NewOp) {
13399   SDLoc dl(Node);
13400   assert (Node->getValueType(0) == MVT::i64 &&
13401           "Only know how to expand i64 atomics");
13402
13403   SDValue Chain = Node->getOperand(0);
13404   SDValue In1 = Node->getOperand(1);
13405   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13406                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13407   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13408                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13409   SDValue Ops[] = { Chain, In1, In2L, In2H };
13410   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13411   SDValue Result =
13412     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13413                             cast<MemSDNode>(Node)->getMemOperand());
13414   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13415   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13416   Results.push_back(Result.getValue(2));
13417 }
13418
13419 /// ReplaceNodeResults - Replace a node with an illegal result type
13420 /// with a new node built out of custom code.
13421 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13422                                            SmallVectorImpl<SDValue>&Results,
13423                                            SelectionDAG &DAG) const {
13424   SDLoc dl(N);
13425   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13426   switch (N->getOpcode()) {
13427   default:
13428     llvm_unreachable("Do not know how to custom type legalize this operation!");
13429   case ISD::SIGN_EXTEND_INREG:
13430   case ISD::ADDC:
13431   case ISD::ADDE:
13432   case ISD::SUBC:
13433   case ISD::SUBE:
13434     // We don't want to expand or promote these.
13435     return;
13436   case ISD::FP_TO_SINT:
13437   case ISD::FP_TO_UINT: {
13438     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13439
13440     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13441       return;
13442
13443     std::pair<SDValue,SDValue> Vals =
13444         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13445     SDValue FIST = Vals.first, StackSlot = Vals.second;
13446     if (FIST.getNode() != 0) {
13447       EVT VT = N->getValueType(0);
13448       // Return a load from the stack slot.
13449       if (StackSlot.getNode() != 0)
13450         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13451                                       MachinePointerInfo(),
13452                                       false, false, false, 0));
13453       else
13454         Results.push_back(FIST);
13455     }
13456     return;
13457   }
13458   case ISD::UINT_TO_FP: {
13459     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13460     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13461         N->getValueType(0) != MVT::v2f32)
13462       return;
13463     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13464                                  N->getOperand(0));
13465     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13466                                      MVT::f64);
13467     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13468     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13469                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13470     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13471     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13472     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13473     return;
13474   }
13475   case ISD::FP_ROUND: {
13476     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13477         return;
13478     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13479     Results.push_back(V);
13480     return;
13481   }
13482   case ISD::READCYCLECOUNTER: {
13483     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13484     SDValue TheChain = N->getOperand(0);
13485     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13486     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13487                                      rd.getValue(1));
13488     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13489                                      eax.getValue(2));
13490     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13491     SDValue Ops[] = { eax, edx };
13492     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13493                                   array_lengthof(Ops)));
13494     Results.push_back(edx.getValue(1));
13495     return;
13496   }
13497   case ISD::ATOMIC_CMP_SWAP: {
13498     EVT T = N->getValueType(0);
13499     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13500     bool Regs64bit = T == MVT::i128;
13501     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13502     SDValue cpInL, cpInH;
13503     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13504                         DAG.getConstant(0, HalfT));
13505     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13506                         DAG.getConstant(1, HalfT));
13507     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13508                              Regs64bit ? X86::RAX : X86::EAX,
13509                              cpInL, SDValue());
13510     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13511                              Regs64bit ? X86::RDX : X86::EDX,
13512                              cpInH, cpInL.getValue(1));
13513     SDValue swapInL, swapInH;
13514     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13515                           DAG.getConstant(0, HalfT));
13516     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13517                           DAG.getConstant(1, HalfT));
13518     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13519                                Regs64bit ? X86::RBX : X86::EBX,
13520                                swapInL, cpInH.getValue(1));
13521     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13522                                Regs64bit ? X86::RCX : X86::ECX,
13523                                swapInH, swapInL.getValue(1));
13524     SDValue Ops[] = { swapInH.getValue(0),
13525                       N->getOperand(1),
13526                       swapInH.getValue(1) };
13527     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13528     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13529     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13530                                   X86ISD::LCMPXCHG8_DAG;
13531     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13532                                              Ops, array_lengthof(Ops), T, MMO);
13533     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13534                                         Regs64bit ? X86::RAX : X86::EAX,
13535                                         HalfT, Result.getValue(1));
13536     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13537                                         Regs64bit ? X86::RDX : X86::EDX,
13538                                         HalfT, cpOutL.getValue(2));
13539     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13540     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13541     Results.push_back(cpOutH.getValue(1));
13542     return;
13543   }
13544   case ISD::ATOMIC_LOAD_ADD:
13545   case ISD::ATOMIC_LOAD_AND:
13546   case ISD::ATOMIC_LOAD_NAND:
13547   case ISD::ATOMIC_LOAD_OR:
13548   case ISD::ATOMIC_LOAD_SUB:
13549   case ISD::ATOMIC_LOAD_XOR:
13550   case ISD::ATOMIC_LOAD_MAX:
13551   case ISD::ATOMIC_LOAD_MIN:
13552   case ISD::ATOMIC_LOAD_UMAX:
13553   case ISD::ATOMIC_LOAD_UMIN:
13554   case ISD::ATOMIC_SWAP: {
13555     unsigned Opc;
13556     switch (N->getOpcode()) {
13557     default: llvm_unreachable("Unexpected opcode");
13558     case ISD::ATOMIC_LOAD_ADD:
13559       Opc = X86ISD::ATOMADD64_DAG;
13560       break;
13561     case ISD::ATOMIC_LOAD_AND:
13562       Opc = X86ISD::ATOMAND64_DAG;
13563       break;
13564     case ISD::ATOMIC_LOAD_NAND:
13565       Opc = X86ISD::ATOMNAND64_DAG;
13566       break;
13567     case ISD::ATOMIC_LOAD_OR:
13568       Opc = X86ISD::ATOMOR64_DAG;
13569       break;
13570     case ISD::ATOMIC_LOAD_SUB:
13571       Opc = X86ISD::ATOMSUB64_DAG;
13572       break;
13573     case ISD::ATOMIC_LOAD_XOR:
13574       Opc = X86ISD::ATOMXOR64_DAG;
13575       break;
13576     case ISD::ATOMIC_LOAD_MAX:
13577       Opc = X86ISD::ATOMMAX64_DAG;
13578       break;
13579     case ISD::ATOMIC_LOAD_MIN:
13580       Opc = X86ISD::ATOMMIN64_DAG;
13581       break;
13582     case ISD::ATOMIC_LOAD_UMAX:
13583       Opc = X86ISD::ATOMUMAX64_DAG;
13584       break;
13585     case ISD::ATOMIC_LOAD_UMIN:
13586       Opc = X86ISD::ATOMUMIN64_DAG;
13587       break;
13588     case ISD::ATOMIC_SWAP:
13589       Opc = X86ISD::ATOMSWAP64_DAG;
13590       break;
13591     }
13592     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13593     return;
13594   }
13595   case ISD::ATOMIC_LOAD:
13596     ReplaceATOMIC_LOAD(N, Results, DAG);
13597   }
13598 }
13599
13600 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13601   switch (Opcode) {
13602   default: return NULL;
13603   case X86ISD::BSF:                return "X86ISD::BSF";
13604   case X86ISD::BSR:                return "X86ISD::BSR";
13605   case X86ISD::SHLD:               return "X86ISD::SHLD";
13606   case X86ISD::SHRD:               return "X86ISD::SHRD";
13607   case X86ISD::FAND:               return "X86ISD::FAND";
13608   case X86ISD::FANDN:              return "X86ISD::FANDN";
13609   case X86ISD::FOR:                return "X86ISD::FOR";
13610   case X86ISD::FXOR:               return "X86ISD::FXOR";
13611   case X86ISD::FSRL:               return "X86ISD::FSRL";
13612   case X86ISD::FILD:               return "X86ISD::FILD";
13613   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13614   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13615   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13616   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13617   case X86ISD::FLD:                return "X86ISD::FLD";
13618   case X86ISD::FST:                return "X86ISD::FST";
13619   case X86ISD::CALL:               return "X86ISD::CALL";
13620   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13621   case X86ISD::BT:                 return "X86ISD::BT";
13622   case X86ISD::CMP:                return "X86ISD::CMP";
13623   case X86ISD::COMI:               return "X86ISD::COMI";
13624   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13625   case X86ISD::CMPM:               return "X86ISD::CMPM";
13626   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13627   case X86ISD::SETCC:              return "X86ISD::SETCC";
13628   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13629   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13630   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13631   case X86ISD::CMOV:               return "X86ISD::CMOV";
13632   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13633   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13634   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13635   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13636   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13637   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13638   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13639   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13640   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13641   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13642   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13643   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13644   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13645   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13646   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13647   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13648   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13649   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13650   case X86ISD::HADD:               return "X86ISD::HADD";
13651   case X86ISD::HSUB:               return "X86ISD::HSUB";
13652   case X86ISD::FHADD:              return "X86ISD::FHADD";
13653   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13654   case X86ISD::UMAX:               return "X86ISD::UMAX";
13655   case X86ISD::UMIN:               return "X86ISD::UMIN";
13656   case X86ISD::SMAX:               return "X86ISD::SMAX";
13657   case X86ISD::SMIN:               return "X86ISD::SMIN";
13658   case X86ISD::FMAX:               return "X86ISD::FMAX";
13659   case X86ISD::FMIN:               return "X86ISD::FMIN";
13660   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13661   case X86ISD::FMINC:              return "X86ISD::FMINC";
13662   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13663   case X86ISD::FRCP:               return "X86ISD::FRCP";
13664   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13665   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13666   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13667   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13668   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13669   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13670   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13671   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13672   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13673   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13674   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13675   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13676   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13677   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13678   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13679   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13680   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13681   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13682   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13683   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13684   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13685   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13686   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
13687   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
13688   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
13689   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13690   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13691   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13692   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13693   case X86ISD::VSHL:               return "X86ISD::VSHL";
13694   case X86ISD::VSRL:               return "X86ISD::VSRL";
13695   case X86ISD::VSRA:               return "X86ISD::VSRA";
13696   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13697   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13698   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13699   case X86ISD::CMPP:               return "X86ISD::CMPP";
13700   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13701   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13702   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13703   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13704   case X86ISD::ADD:                return "X86ISD::ADD";
13705   case X86ISD::SUB:                return "X86ISD::SUB";
13706   case X86ISD::ADC:                return "X86ISD::ADC";
13707   case X86ISD::SBB:                return "X86ISD::SBB";
13708   case X86ISD::SMUL:               return "X86ISD::SMUL";
13709   case X86ISD::UMUL:               return "X86ISD::UMUL";
13710   case X86ISD::INC:                return "X86ISD::INC";
13711   case X86ISD::DEC:                return "X86ISD::DEC";
13712   case X86ISD::OR:                 return "X86ISD::OR";
13713   case X86ISD::XOR:                return "X86ISD::XOR";
13714   case X86ISD::AND:                return "X86ISD::AND";
13715   case X86ISD::BLSI:               return "X86ISD::BLSI";
13716   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13717   case X86ISD::BLSR:               return "X86ISD::BLSR";
13718   case X86ISD::BZHI:               return "X86ISD::BZHI";
13719   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
13720   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13721   case X86ISD::PTEST:              return "X86ISD::PTEST";
13722   case X86ISD::TESTP:              return "X86ISD::TESTP";
13723   case X86ISD::TESTM:              return "X86ISD::TESTM";
13724   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
13725   case X86ISD::KTEST:              return "X86ISD::KTEST";
13726   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13727   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13728   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13729   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13730   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13731   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13732   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13733   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13734   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13735   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13736   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13737   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13738   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13739   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13740   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13741   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13742   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13743   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13744   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
13745   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13746   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13747   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13748   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
13749   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13750   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13751   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13752   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13753   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13754   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13755   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13756   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13757   case X86ISD::SAHF:               return "X86ISD::SAHF";
13758   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13759   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13760   case X86ISD::FMADD:              return "X86ISD::FMADD";
13761   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13762   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13763   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13764   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13765   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13766   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13767   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13768   case X86ISD::XTEST:              return "X86ISD::XTEST";
13769   }
13770 }
13771
13772 // isLegalAddressingMode - Return true if the addressing mode represented
13773 // by AM is legal for this target, for a load/store of the specified type.
13774 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13775                                               Type *Ty) const {
13776   // X86 supports extremely general addressing modes.
13777   CodeModel::Model M = getTargetMachine().getCodeModel();
13778   Reloc::Model R = getTargetMachine().getRelocationModel();
13779
13780   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13781   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13782     return false;
13783
13784   if (AM.BaseGV) {
13785     unsigned GVFlags =
13786       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13787
13788     // If a reference to this global requires an extra load, we can't fold it.
13789     if (isGlobalStubReference(GVFlags))
13790       return false;
13791
13792     // If BaseGV requires a register for the PIC base, we cannot also have a
13793     // BaseReg specified.
13794     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13795       return false;
13796
13797     // If lower 4G is not available, then we must use rip-relative addressing.
13798     if ((M != CodeModel::Small || R != Reloc::Static) &&
13799         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13800       return false;
13801   }
13802
13803   switch (AM.Scale) {
13804   case 0:
13805   case 1:
13806   case 2:
13807   case 4:
13808   case 8:
13809     // These scales always work.
13810     break;
13811   case 3:
13812   case 5:
13813   case 9:
13814     // These scales are formed with basereg+scalereg.  Only accept if there is
13815     // no basereg yet.
13816     if (AM.HasBaseReg)
13817       return false;
13818     break;
13819   default:  // Other stuff never works.
13820     return false;
13821   }
13822
13823   return true;
13824 }
13825
13826 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13827   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13828     return false;
13829   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13830   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13831   return NumBits1 > NumBits2;
13832 }
13833
13834 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13835   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13836     return false;
13837
13838   if (!isTypeLegal(EVT::getEVT(Ty1)))
13839     return false;
13840
13841   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13842
13843   // Assuming the caller doesn't have a zeroext or signext return parameter,
13844   // truncation all the way down to i1 is valid.
13845   return true;
13846 }
13847
13848 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13849   return isInt<32>(Imm);
13850 }
13851
13852 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13853   // Can also use sub to handle negated immediates.
13854   return isInt<32>(Imm);
13855 }
13856
13857 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13858   if (!VT1.isInteger() || !VT2.isInteger())
13859     return false;
13860   unsigned NumBits1 = VT1.getSizeInBits();
13861   unsigned NumBits2 = VT2.getSizeInBits();
13862   return NumBits1 > NumBits2;
13863 }
13864
13865 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13866   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13867   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13868 }
13869
13870 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13871   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13872   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13873 }
13874
13875 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13876   EVT VT1 = Val.getValueType();
13877   if (isZExtFree(VT1, VT2))
13878     return true;
13879
13880   if (Val.getOpcode() != ISD::LOAD)
13881     return false;
13882
13883   if (!VT1.isSimple() || !VT1.isInteger() ||
13884       !VT2.isSimple() || !VT2.isInteger())
13885     return false;
13886
13887   switch (VT1.getSimpleVT().SimpleTy) {
13888   default: break;
13889   case MVT::i8:
13890   case MVT::i16:
13891   case MVT::i32:
13892     // X86 has 8, 16, and 32-bit zero-extending loads.
13893     return true;
13894   }
13895
13896   return false;
13897 }
13898
13899 bool
13900 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13901   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13902     return false;
13903
13904   VT = VT.getScalarType();
13905
13906   if (!VT.isSimple())
13907     return false;
13908
13909   switch (VT.getSimpleVT().SimpleTy) {
13910   case MVT::f32:
13911   case MVT::f64:
13912     return true;
13913   default:
13914     break;
13915   }
13916
13917   return false;
13918 }
13919
13920 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13921   // i16 instructions are longer (0x66 prefix) and potentially slower.
13922   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13923 }
13924
13925 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13926 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13927 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13928 /// are assumed to be legal.
13929 bool
13930 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13931                                       EVT VT) const {
13932   if (!VT.isSimple())
13933     return false;
13934
13935   MVT SVT = VT.getSimpleVT();
13936
13937   // Very little shuffling can be done for 64-bit vectors right now.
13938   if (VT.getSizeInBits() == 64)
13939     return false;
13940
13941   // FIXME: pshufb, blends, shifts.
13942   return (SVT.getVectorNumElements() == 2 ||
13943           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13944           isMOVLMask(M, SVT) ||
13945           isSHUFPMask(M, SVT) ||
13946           isPSHUFDMask(M, SVT) ||
13947           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
13948           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
13949           isPALIGNRMask(M, SVT, Subtarget) ||
13950           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
13951           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
13952           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
13953           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
13954 }
13955
13956 bool
13957 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13958                                           EVT VT) const {
13959   if (!VT.isSimple())
13960     return false;
13961
13962   MVT SVT = VT.getSimpleVT();
13963   unsigned NumElts = SVT.getVectorNumElements();
13964   // FIXME: This collection of masks seems suspect.
13965   if (NumElts == 2)
13966     return true;
13967   if (NumElts == 4 && SVT.is128BitVector()) {
13968     return (isMOVLMask(Mask, SVT)  ||
13969             isCommutedMOVLMask(Mask, SVT, true) ||
13970             isSHUFPMask(Mask, SVT) ||
13971             isSHUFPMask(Mask, SVT, /* Commuted */ true));
13972   }
13973   return false;
13974 }
13975
13976 //===----------------------------------------------------------------------===//
13977 //                           X86 Scheduler Hooks
13978 //===----------------------------------------------------------------------===//
13979
13980 /// Utility function to emit xbegin specifying the start of an RTM region.
13981 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13982                                      const TargetInstrInfo *TII) {
13983   DebugLoc DL = MI->getDebugLoc();
13984
13985   const BasicBlock *BB = MBB->getBasicBlock();
13986   MachineFunction::iterator I = MBB;
13987   ++I;
13988
13989   // For the v = xbegin(), we generate
13990   //
13991   // thisMBB:
13992   //  xbegin sinkMBB
13993   //
13994   // mainMBB:
13995   //  eax = -1
13996   //
13997   // sinkMBB:
13998   //  v = eax
13999
14000   MachineBasicBlock *thisMBB = MBB;
14001   MachineFunction *MF = MBB->getParent();
14002   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14003   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14004   MF->insert(I, mainMBB);
14005   MF->insert(I, sinkMBB);
14006
14007   // Transfer the remainder of BB and its successor edges to sinkMBB.
14008   sinkMBB->splice(sinkMBB->begin(), MBB,
14009                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14010   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14011
14012   // thisMBB:
14013   //  xbegin sinkMBB
14014   //  # fallthrough to mainMBB
14015   //  # abortion to sinkMBB
14016   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14017   thisMBB->addSuccessor(mainMBB);
14018   thisMBB->addSuccessor(sinkMBB);
14019
14020   // mainMBB:
14021   //  EAX = -1
14022   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14023   mainMBB->addSuccessor(sinkMBB);
14024
14025   // sinkMBB:
14026   // EAX is live into the sinkMBB
14027   sinkMBB->addLiveIn(X86::EAX);
14028   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14029           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14030     .addReg(X86::EAX);
14031
14032   MI->eraseFromParent();
14033   return sinkMBB;
14034 }
14035
14036 // Get CMPXCHG opcode for the specified data type.
14037 static unsigned getCmpXChgOpcode(EVT VT) {
14038   switch (VT.getSimpleVT().SimpleTy) {
14039   case MVT::i8:  return X86::LCMPXCHG8;
14040   case MVT::i16: return X86::LCMPXCHG16;
14041   case MVT::i32: return X86::LCMPXCHG32;
14042   case MVT::i64: return X86::LCMPXCHG64;
14043   default:
14044     break;
14045   }
14046   llvm_unreachable("Invalid operand size!");
14047 }
14048
14049 // Get LOAD opcode for the specified data type.
14050 static unsigned getLoadOpcode(EVT VT) {
14051   switch (VT.getSimpleVT().SimpleTy) {
14052   case MVT::i8:  return X86::MOV8rm;
14053   case MVT::i16: return X86::MOV16rm;
14054   case MVT::i32: return X86::MOV32rm;
14055   case MVT::i64: return X86::MOV64rm;
14056   default:
14057     break;
14058   }
14059   llvm_unreachable("Invalid operand size!");
14060 }
14061
14062 // Get opcode of the non-atomic one from the specified atomic instruction.
14063 static unsigned getNonAtomicOpcode(unsigned Opc) {
14064   switch (Opc) {
14065   case X86::ATOMAND8:  return X86::AND8rr;
14066   case X86::ATOMAND16: return X86::AND16rr;
14067   case X86::ATOMAND32: return X86::AND32rr;
14068   case X86::ATOMAND64: return X86::AND64rr;
14069   case X86::ATOMOR8:   return X86::OR8rr;
14070   case X86::ATOMOR16:  return X86::OR16rr;
14071   case X86::ATOMOR32:  return X86::OR32rr;
14072   case X86::ATOMOR64:  return X86::OR64rr;
14073   case X86::ATOMXOR8:  return X86::XOR8rr;
14074   case X86::ATOMXOR16: return X86::XOR16rr;
14075   case X86::ATOMXOR32: return X86::XOR32rr;
14076   case X86::ATOMXOR64: return X86::XOR64rr;
14077   }
14078   llvm_unreachable("Unhandled atomic-load-op opcode!");
14079 }
14080
14081 // Get opcode of the non-atomic one from the specified atomic instruction with
14082 // extra opcode.
14083 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14084                                                unsigned &ExtraOpc) {
14085   switch (Opc) {
14086   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14087   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14088   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14089   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14090   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14091   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14092   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14093   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14094   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14095   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14096   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14097   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14098   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14099   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14100   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14101   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14102   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14103   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14104   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14105   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14106   }
14107   llvm_unreachable("Unhandled atomic-load-op opcode!");
14108 }
14109
14110 // Get opcode of the non-atomic one from the specified atomic instruction for
14111 // 64-bit data type on 32-bit target.
14112 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14113   switch (Opc) {
14114   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14115   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14116   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14117   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14118   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14119   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14120   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14121   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14122   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14123   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14124   }
14125   llvm_unreachable("Unhandled atomic-load-op opcode!");
14126 }
14127
14128 // Get opcode of the non-atomic one from the specified atomic instruction for
14129 // 64-bit data type on 32-bit target with extra opcode.
14130 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14131                                                    unsigned &HiOpc,
14132                                                    unsigned &ExtraOpc) {
14133   switch (Opc) {
14134   case X86::ATOMNAND6432:
14135     ExtraOpc = X86::NOT32r;
14136     HiOpc = X86::AND32rr;
14137     return X86::AND32rr;
14138   }
14139   llvm_unreachable("Unhandled atomic-load-op opcode!");
14140 }
14141
14142 // Get pseudo CMOV opcode from the specified data type.
14143 static unsigned getPseudoCMOVOpc(EVT VT) {
14144   switch (VT.getSimpleVT().SimpleTy) {
14145   case MVT::i8:  return X86::CMOV_GR8;
14146   case MVT::i16: return X86::CMOV_GR16;
14147   case MVT::i32: return X86::CMOV_GR32;
14148   default:
14149     break;
14150   }
14151   llvm_unreachable("Unknown CMOV opcode!");
14152 }
14153
14154 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14155 // They will be translated into a spin-loop or compare-exchange loop from
14156 //
14157 //    ...
14158 //    dst = atomic-fetch-op MI.addr, MI.val
14159 //    ...
14160 //
14161 // to
14162 //
14163 //    ...
14164 //    t1 = LOAD MI.addr
14165 // loop:
14166 //    t4 = phi(t1, t3 / loop)
14167 //    t2 = OP MI.val, t4
14168 //    EAX = t4
14169 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14170 //    t3 = EAX
14171 //    JNE loop
14172 // sink:
14173 //    dst = t3
14174 //    ...
14175 MachineBasicBlock *
14176 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14177                                        MachineBasicBlock *MBB) const {
14178   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14179   DebugLoc DL = MI->getDebugLoc();
14180
14181   MachineFunction *MF = MBB->getParent();
14182   MachineRegisterInfo &MRI = MF->getRegInfo();
14183
14184   const BasicBlock *BB = MBB->getBasicBlock();
14185   MachineFunction::iterator I = MBB;
14186   ++I;
14187
14188   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14189          "Unexpected number of operands");
14190
14191   assert(MI->hasOneMemOperand() &&
14192          "Expected atomic-load-op to have one memoperand");
14193
14194   // Memory Reference
14195   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14196   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14197
14198   unsigned DstReg, SrcReg;
14199   unsigned MemOpndSlot;
14200
14201   unsigned CurOp = 0;
14202
14203   DstReg = MI->getOperand(CurOp++).getReg();
14204   MemOpndSlot = CurOp;
14205   CurOp += X86::AddrNumOperands;
14206   SrcReg = MI->getOperand(CurOp++).getReg();
14207
14208   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14209   MVT::SimpleValueType VT = *RC->vt_begin();
14210   unsigned t1 = MRI.createVirtualRegister(RC);
14211   unsigned t2 = MRI.createVirtualRegister(RC);
14212   unsigned t3 = MRI.createVirtualRegister(RC);
14213   unsigned t4 = MRI.createVirtualRegister(RC);
14214   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14215
14216   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14217   unsigned LOADOpc = getLoadOpcode(VT);
14218
14219   // For the atomic load-arith operator, we generate
14220   //
14221   //  thisMBB:
14222   //    t1 = LOAD [MI.addr]
14223   //  mainMBB:
14224   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14225   //    t1 = OP MI.val, EAX
14226   //    EAX = t4
14227   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14228   //    t3 = EAX
14229   //    JNE mainMBB
14230   //  sinkMBB:
14231   //    dst = t3
14232
14233   MachineBasicBlock *thisMBB = MBB;
14234   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14235   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14236   MF->insert(I, mainMBB);
14237   MF->insert(I, sinkMBB);
14238
14239   MachineInstrBuilder MIB;
14240
14241   // Transfer the remainder of BB and its successor edges to sinkMBB.
14242   sinkMBB->splice(sinkMBB->begin(), MBB,
14243                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14244   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14245
14246   // thisMBB:
14247   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14248   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14249     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14250     if (NewMO.isReg())
14251       NewMO.setIsKill(false);
14252     MIB.addOperand(NewMO);
14253   }
14254   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14255     unsigned flags = (*MMOI)->getFlags();
14256     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14257     MachineMemOperand *MMO =
14258       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14259                                (*MMOI)->getSize(),
14260                                (*MMOI)->getBaseAlignment(),
14261                                (*MMOI)->getTBAAInfo(),
14262                                (*MMOI)->getRanges());
14263     MIB.addMemOperand(MMO);
14264   }
14265
14266   thisMBB->addSuccessor(mainMBB);
14267
14268   // mainMBB:
14269   MachineBasicBlock *origMainMBB = mainMBB;
14270
14271   // Add a PHI.
14272   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14273                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14274
14275   unsigned Opc = MI->getOpcode();
14276   switch (Opc) {
14277   default:
14278     llvm_unreachable("Unhandled atomic-load-op opcode!");
14279   case X86::ATOMAND8:
14280   case X86::ATOMAND16:
14281   case X86::ATOMAND32:
14282   case X86::ATOMAND64:
14283   case X86::ATOMOR8:
14284   case X86::ATOMOR16:
14285   case X86::ATOMOR32:
14286   case X86::ATOMOR64:
14287   case X86::ATOMXOR8:
14288   case X86::ATOMXOR16:
14289   case X86::ATOMXOR32:
14290   case X86::ATOMXOR64: {
14291     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14292     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14293       .addReg(t4);
14294     break;
14295   }
14296   case X86::ATOMNAND8:
14297   case X86::ATOMNAND16:
14298   case X86::ATOMNAND32:
14299   case X86::ATOMNAND64: {
14300     unsigned Tmp = MRI.createVirtualRegister(RC);
14301     unsigned NOTOpc;
14302     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14303     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14304       .addReg(t4);
14305     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14306     break;
14307   }
14308   case X86::ATOMMAX8:
14309   case X86::ATOMMAX16:
14310   case X86::ATOMMAX32:
14311   case X86::ATOMMAX64:
14312   case X86::ATOMMIN8:
14313   case X86::ATOMMIN16:
14314   case X86::ATOMMIN32:
14315   case X86::ATOMMIN64:
14316   case X86::ATOMUMAX8:
14317   case X86::ATOMUMAX16:
14318   case X86::ATOMUMAX32:
14319   case X86::ATOMUMAX64:
14320   case X86::ATOMUMIN8:
14321   case X86::ATOMUMIN16:
14322   case X86::ATOMUMIN32:
14323   case X86::ATOMUMIN64: {
14324     unsigned CMPOpc;
14325     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14326
14327     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14328       .addReg(SrcReg)
14329       .addReg(t4);
14330
14331     if (Subtarget->hasCMov()) {
14332       if (VT != MVT::i8) {
14333         // Native support
14334         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14335           .addReg(SrcReg)
14336           .addReg(t4);
14337       } else {
14338         // Promote i8 to i32 to use CMOV32
14339         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14340         const TargetRegisterClass *RC32 =
14341           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14342         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14343         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14344         unsigned Tmp = MRI.createVirtualRegister(RC32);
14345
14346         unsigned Undef = MRI.createVirtualRegister(RC32);
14347         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14348
14349         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14350           .addReg(Undef)
14351           .addReg(SrcReg)
14352           .addImm(X86::sub_8bit);
14353         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14354           .addReg(Undef)
14355           .addReg(t4)
14356           .addImm(X86::sub_8bit);
14357
14358         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14359           .addReg(SrcReg32)
14360           .addReg(AccReg32);
14361
14362         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14363           .addReg(Tmp, 0, X86::sub_8bit);
14364       }
14365     } else {
14366       // Use pseudo select and lower them.
14367       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14368              "Invalid atomic-load-op transformation!");
14369       unsigned SelOpc = getPseudoCMOVOpc(VT);
14370       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14371       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14372       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14373               .addReg(SrcReg).addReg(t4)
14374               .addImm(CC);
14375       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14376       // Replace the original PHI node as mainMBB is changed after CMOV
14377       // lowering.
14378       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14379         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14380       Phi->eraseFromParent();
14381     }
14382     break;
14383   }
14384   }
14385
14386   // Copy PhyReg back from virtual register.
14387   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14388     .addReg(t4);
14389
14390   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14391   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14392     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14393     if (NewMO.isReg())
14394       NewMO.setIsKill(false);
14395     MIB.addOperand(NewMO);
14396   }
14397   MIB.addReg(t2);
14398   MIB.setMemRefs(MMOBegin, MMOEnd);
14399
14400   // Copy PhyReg back to virtual register.
14401   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14402     .addReg(PhyReg);
14403
14404   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14405
14406   mainMBB->addSuccessor(origMainMBB);
14407   mainMBB->addSuccessor(sinkMBB);
14408
14409   // sinkMBB:
14410   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14411           TII->get(TargetOpcode::COPY), DstReg)
14412     .addReg(t3);
14413
14414   MI->eraseFromParent();
14415   return sinkMBB;
14416 }
14417
14418 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14419 // instructions. They will be translated into a spin-loop or compare-exchange
14420 // loop from
14421 //
14422 //    ...
14423 //    dst = atomic-fetch-op MI.addr, MI.val
14424 //    ...
14425 //
14426 // to
14427 //
14428 //    ...
14429 //    t1L = LOAD [MI.addr + 0]
14430 //    t1H = LOAD [MI.addr + 4]
14431 // loop:
14432 //    t4L = phi(t1L, t3L / loop)
14433 //    t4H = phi(t1H, t3H / loop)
14434 //    t2L = OP MI.val.lo, t4L
14435 //    t2H = OP MI.val.hi, t4H
14436 //    EAX = t4L
14437 //    EDX = t4H
14438 //    EBX = t2L
14439 //    ECX = t2H
14440 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14441 //    t3L = EAX
14442 //    t3H = EDX
14443 //    JNE loop
14444 // sink:
14445 //    dstL = t3L
14446 //    dstH = t3H
14447 //    ...
14448 MachineBasicBlock *
14449 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14450                                            MachineBasicBlock *MBB) const {
14451   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14452   DebugLoc DL = MI->getDebugLoc();
14453
14454   MachineFunction *MF = MBB->getParent();
14455   MachineRegisterInfo &MRI = MF->getRegInfo();
14456
14457   const BasicBlock *BB = MBB->getBasicBlock();
14458   MachineFunction::iterator I = MBB;
14459   ++I;
14460
14461   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14462          "Unexpected number of operands");
14463
14464   assert(MI->hasOneMemOperand() &&
14465          "Expected atomic-load-op32 to have one memoperand");
14466
14467   // Memory Reference
14468   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14469   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14470
14471   unsigned DstLoReg, DstHiReg;
14472   unsigned SrcLoReg, SrcHiReg;
14473   unsigned MemOpndSlot;
14474
14475   unsigned CurOp = 0;
14476
14477   DstLoReg = MI->getOperand(CurOp++).getReg();
14478   DstHiReg = MI->getOperand(CurOp++).getReg();
14479   MemOpndSlot = CurOp;
14480   CurOp += X86::AddrNumOperands;
14481   SrcLoReg = MI->getOperand(CurOp++).getReg();
14482   SrcHiReg = MI->getOperand(CurOp++).getReg();
14483
14484   const TargetRegisterClass *RC = &X86::GR32RegClass;
14485   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14486
14487   unsigned t1L = MRI.createVirtualRegister(RC);
14488   unsigned t1H = MRI.createVirtualRegister(RC);
14489   unsigned t2L = MRI.createVirtualRegister(RC);
14490   unsigned t2H = MRI.createVirtualRegister(RC);
14491   unsigned t3L = MRI.createVirtualRegister(RC);
14492   unsigned t3H = MRI.createVirtualRegister(RC);
14493   unsigned t4L = MRI.createVirtualRegister(RC);
14494   unsigned t4H = MRI.createVirtualRegister(RC);
14495
14496   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14497   unsigned LOADOpc = X86::MOV32rm;
14498
14499   // For the atomic load-arith operator, we generate
14500   //
14501   //  thisMBB:
14502   //    t1L = LOAD [MI.addr + 0]
14503   //    t1H = LOAD [MI.addr + 4]
14504   //  mainMBB:
14505   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14506   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14507   //    t2L = OP MI.val.lo, t4L
14508   //    t2H = OP MI.val.hi, t4H
14509   //    EBX = t2L
14510   //    ECX = t2H
14511   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14512   //    t3L = EAX
14513   //    t3H = EDX
14514   //    JNE loop
14515   //  sinkMBB:
14516   //    dstL = t3L
14517   //    dstH = t3H
14518
14519   MachineBasicBlock *thisMBB = MBB;
14520   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14521   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14522   MF->insert(I, mainMBB);
14523   MF->insert(I, sinkMBB);
14524
14525   MachineInstrBuilder MIB;
14526
14527   // Transfer the remainder of BB and its successor edges to sinkMBB.
14528   sinkMBB->splice(sinkMBB->begin(), MBB,
14529                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14530   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14531
14532   // thisMBB:
14533   // Lo
14534   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14535   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14536     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14537     if (NewMO.isReg())
14538       NewMO.setIsKill(false);
14539     MIB.addOperand(NewMO);
14540   }
14541   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14542     unsigned flags = (*MMOI)->getFlags();
14543     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14544     MachineMemOperand *MMO =
14545       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14546                                (*MMOI)->getSize(),
14547                                (*MMOI)->getBaseAlignment(),
14548                                (*MMOI)->getTBAAInfo(),
14549                                (*MMOI)->getRanges());
14550     MIB.addMemOperand(MMO);
14551   };
14552   MachineInstr *LowMI = MIB;
14553
14554   // Hi
14555   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14556   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14557     if (i == X86::AddrDisp) {
14558       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14559     } else {
14560       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14561       if (NewMO.isReg())
14562         NewMO.setIsKill(false);
14563       MIB.addOperand(NewMO);
14564     }
14565   }
14566   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14567
14568   thisMBB->addSuccessor(mainMBB);
14569
14570   // mainMBB:
14571   MachineBasicBlock *origMainMBB = mainMBB;
14572
14573   // Add PHIs.
14574   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14575                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14576   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14577                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14578
14579   unsigned Opc = MI->getOpcode();
14580   switch (Opc) {
14581   default:
14582     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14583   case X86::ATOMAND6432:
14584   case X86::ATOMOR6432:
14585   case X86::ATOMXOR6432:
14586   case X86::ATOMADD6432:
14587   case X86::ATOMSUB6432: {
14588     unsigned HiOpc;
14589     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14590     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14591       .addReg(SrcLoReg);
14592     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14593       .addReg(SrcHiReg);
14594     break;
14595   }
14596   case X86::ATOMNAND6432: {
14597     unsigned HiOpc, NOTOpc;
14598     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14599     unsigned TmpL = MRI.createVirtualRegister(RC);
14600     unsigned TmpH = MRI.createVirtualRegister(RC);
14601     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14602       .addReg(t4L);
14603     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14604       .addReg(t4H);
14605     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14606     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14607     break;
14608   }
14609   case X86::ATOMMAX6432:
14610   case X86::ATOMMIN6432:
14611   case X86::ATOMUMAX6432:
14612   case X86::ATOMUMIN6432: {
14613     unsigned HiOpc;
14614     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14615     unsigned cL = MRI.createVirtualRegister(RC8);
14616     unsigned cH = MRI.createVirtualRegister(RC8);
14617     unsigned cL32 = MRI.createVirtualRegister(RC);
14618     unsigned cH32 = MRI.createVirtualRegister(RC);
14619     unsigned cc = MRI.createVirtualRegister(RC);
14620     // cl := cmp src_lo, lo
14621     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14622       .addReg(SrcLoReg).addReg(t4L);
14623     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14624     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14625     // ch := cmp src_hi, hi
14626     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14627       .addReg(SrcHiReg).addReg(t4H);
14628     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14629     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14630     // cc := if (src_hi == hi) ? cl : ch;
14631     if (Subtarget->hasCMov()) {
14632       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14633         .addReg(cH32).addReg(cL32);
14634     } else {
14635       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14636               .addReg(cH32).addReg(cL32)
14637               .addImm(X86::COND_E);
14638       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14639     }
14640     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14641     if (Subtarget->hasCMov()) {
14642       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14643         .addReg(SrcLoReg).addReg(t4L);
14644       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14645         .addReg(SrcHiReg).addReg(t4H);
14646     } else {
14647       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14648               .addReg(SrcLoReg).addReg(t4L)
14649               .addImm(X86::COND_NE);
14650       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14651       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14652       // 2nd CMOV lowering.
14653       mainMBB->addLiveIn(X86::EFLAGS);
14654       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14655               .addReg(SrcHiReg).addReg(t4H)
14656               .addImm(X86::COND_NE);
14657       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14658       // Replace the original PHI node as mainMBB is changed after CMOV
14659       // lowering.
14660       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14661         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14662       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14663         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14664       PhiL->eraseFromParent();
14665       PhiH->eraseFromParent();
14666     }
14667     break;
14668   }
14669   case X86::ATOMSWAP6432: {
14670     unsigned HiOpc;
14671     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14672     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14673     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14674     break;
14675   }
14676   }
14677
14678   // Copy EDX:EAX back from HiReg:LoReg
14679   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14680   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14681   // Copy ECX:EBX from t1H:t1L
14682   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14683   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14684
14685   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14686   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14687     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14688     if (NewMO.isReg())
14689       NewMO.setIsKill(false);
14690     MIB.addOperand(NewMO);
14691   }
14692   MIB.setMemRefs(MMOBegin, MMOEnd);
14693
14694   // Copy EDX:EAX back to t3H:t3L
14695   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14696   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14697
14698   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14699
14700   mainMBB->addSuccessor(origMainMBB);
14701   mainMBB->addSuccessor(sinkMBB);
14702
14703   // sinkMBB:
14704   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14705           TII->get(TargetOpcode::COPY), DstLoReg)
14706     .addReg(t3L);
14707   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14708           TII->get(TargetOpcode::COPY), DstHiReg)
14709     .addReg(t3H);
14710
14711   MI->eraseFromParent();
14712   return sinkMBB;
14713 }
14714
14715 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14716 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14717 // in the .td file.
14718 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14719                                        const TargetInstrInfo *TII) {
14720   unsigned Opc;
14721   switch (MI->getOpcode()) {
14722   default: llvm_unreachable("illegal opcode!");
14723   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14724   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14725   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14726   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14727   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14728   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14729   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14730   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14731   }
14732
14733   DebugLoc dl = MI->getDebugLoc();
14734   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14735
14736   unsigned NumArgs = MI->getNumOperands();
14737   for (unsigned i = 1; i < NumArgs; ++i) {
14738     MachineOperand &Op = MI->getOperand(i);
14739     if (!(Op.isReg() && Op.isImplicit()))
14740       MIB.addOperand(Op);
14741   }
14742   if (MI->hasOneMemOperand())
14743     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14744
14745   BuildMI(*BB, MI, dl,
14746     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14747     .addReg(X86::XMM0);
14748
14749   MI->eraseFromParent();
14750   return BB;
14751 }
14752
14753 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14754 // defs in an instruction pattern
14755 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14756                                        const TargetInstrInfo *TII) {
14757   unsigned Opc;
14758   switch (MI->getOpcode()) {
14759   default: llvm_unreachable("illegal opcode!");
14760   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14761   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14762   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14763   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14764   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14765   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14766   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14767   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14768   }
14769
14770   DebugLoc dl = MI->getDebugLoc();
14771   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14772
14773   unsigned NumArgs = MI->getNumOperands(); // remove the results
14774   for (unsigned i = 1; i < NumArgs; ++i) {
14775     MachineOperand &Op = MI->getOperand(i);
14776     if (!(Op.isReg() && Op.isImplicit()))
14777       MIB.addOperand(Op);
14778   }
14779   if (MI->hasOneMemOperand())
14780     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14781
14782   BuildMI(*BB, MI, dl,
14783     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14784     .addReg(X86::ECX);
14785
14786   MI->eraseFromParent();
14787   return BB;
14788 }
14789
14790 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14791                                        const TargetInstrInfo *TII,
14792                                        const X86Subtarget* Subtarget) {
14793   DebugLoc dl = MI->getDebugLoc();
14794
14795   // Address into RAX/EAX, other two args into ECX, EDX.
14796   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14797   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14798   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14799   for (int i = 0; i < X86::AddrNumOperands; ++i)
14800     MIB.addOperand(MI->getOperand(i));
14801
14802   unsigned ValOps = X86::AddrNumOperands;
14803   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14804     .addReg(MI->getOperand(ValOps).getReg());
14805   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14806     .addReg(MI->getOperand(ValOps+1).getReg());
14807
14808   // The instruction doesn't actually take any operands though.
14809   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14810
14811   MI->eraseFromParent(); // The pseudo is gone now.
14812   return BB;
14813 }
14814
14815 MachineBasicBlock *
14816 X86TargetLowering::EmitVAARG64WithCustomInserter(
14817                    MachineInstr *MI,
14818                    MachineBasicBlock *MBB) const {
14819   // Emit va_arg instruction on X86-64.
14820
14821   // Operands to this pseudo-instruction:
14822   // 0  ) Output        : destination address (reg)
14823   // 1-5) Input         : va_list address (addr, i64mem)
14824   // 6  ) ArgSize       : Size (in bytes) of vararg type
14825   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14826   // 8  ) Align         : Alignment of type
14827   // 9  ) EFLAGS (implicit-def)
14828
14829   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14830   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14831
14832   unsigned DestReg = MI->getOperand(0).getReg();
14833   MachineOperand &Base = MI->getOperand(1);
14834   MachineOperand &Scale = MI->getOperand(2);
14835   MachineOperand &Index = MI->getOperand(3);
14836   MachineOperand &Disp = MI->getOperand(4);
14837   MachineOperand &Segment = MI->getOperand(5);
14838   unsigned ArgSize = MI->getOperand(6).getImm();
14839   unsigned ArgMode = MI->getOperand(7).getImm();
14840   unsigned Align = MI->getOperand(8).getImm();
14841
14842   // Memory Reference
14843   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14844   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14845   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14846
14847   // Machine Information
14848   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14849   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14850   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14851   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14852   DebugLoc DL = MI->getDebugLoc();
14853
14854   // struct va_list {
14855   //   i32   gp_offset
14856   //   i32   fp_offset
14857   //   i64   overflow_area (address)
14858   //   i64   reg_save_area (address)
14859   // }
14860   // sizeof(va_list) = 24
14861   // alignment(va_list) = 8
14862
14863   unsigned TotalNumIntRegs = 6;
14864   unsigned TotalNumXMMRegs = 8;
14865   bool UseGPOffset = (ArgMode == 1);
14866   bool UseFPOffset = (ArgMode == 2);
14867   unsigned MaxOffset = TotalNumIntRegs * 8 +
14868                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14869
14870   /* Align ArgSize to a multiple of 8 */
14871   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14872   bool NeedsAlign = (Align > 8);
14873
14874   MachineBasicBlock *thisMBB = MBB;
14875   MachineBasicBlock *overflowMBB;
14876   MachineBasicBlock *offsetMBB;
14877   MachineBasicBlock *endMBB;
14878
14879   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14880   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14881   unsigned OffsetReg = 0;
14882
14883   if (!UseGPOffset && !UseFPOffset) {
14884     // If we only pull from the overflow region, we don't create a branch.
14885     // We don't need to alter control flow.
14886     OffsetDestReg = 0; // unused
14887     OverflowDestReg = DestReg;
14888
14889     offsetMBB = NULL;
14890     overflowMBB = thisMBB;
14891     endMBB = thisMBB;
14892   } else {
14893     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14894     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14895     // If not, pull from overflow_area. (branch to overflowMBB)
14896     //
14897     //       thisMBB
14898     //         |     .
14899     //         |        .
14900     //     offsetMBB   overflowMBB
14901     //         |        .
14902     //         |     .
14903     //        endMBB
14904
14905     // Registers for the PHI in endMBB
14906     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14907     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14908
14909     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14910     MachineFunction *MF = MBB->getParent();
14911     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14912     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14913     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14914
14915     MachineFunction::iterator MBBIter = MBB;
14916     ++MBBIter;
14917
14918     // Insert the new basic blocks
14919     MF->insert(MBBIter, offsetMBB);
14920     MF->insert(MBBIter, overflowMBB);
14921     MF->insert(MBBIter, endMBB);
14922
14923     // Transfer the remainder of MBB and its successor edges to endMBB.
14924     endMBB->splice(endMBB->begin(), thisMBB,
14925                     llvm::next(MachineBasicBlock::iterator(MI)),
14926                     thisMBB->end());
14927     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14928
14929     // Make offsetMBB and overflowMBB successors of thisMBB
14930     thisMBB->addSuccessor(offsetMBB);
14931     thisMBB->addSuccessor(overflowMBB);
14932
14933     // endMBB is a successor of both offsetMBB and overflowMBB
14934     offsetMBB->addSuccessor(endMBB);
14935     overflowMBB->addSuccessor(endMBB);
14936
14937     // Load the offset value into a register
14938     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14939     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14940       .addOperand(Base)
14941       .addOperand(Scale)
14942       .addOperand(Index)
14943       .addDisp(Disp, UseFPOffset ? 4 : 0)
14944       .addOperand(Segment)
14945       .setMemRefs(MMOBegin, MMOEnd);
14946
14947     // Check if there is enough room left to pull this argument.
14948     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14949       .addReg(OffsetReg)
14950       .addImm(MaxOffset + 8 - ArgSizeA8);
14951
14952     // Branch to "overflowMBB" if offset >= max
14953     // Fall through to "offsetMBB" otherwise
14954     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14955       .addMBB(overflowMBB);
14956   }
14957
14958   // In offsetMBB, emit code to use the reg_save_area.
14959   if (offsetMBB) {
14960     assert(OffsetReg != 0);
14961
14962     // Read the reg_save_area address.
14963     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14964     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14965       .addOperand(Base)
14966       .addOperand(Scale)
14967       .addOperand(Index)
14968       .addDisp(Disp, 16)
14969       .addOperand(Segment)
14970       .setMemRefs(MMOBegin, MMOEnd);
14971
14972     // Zero-extend the offset
14973     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14974       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14975         .addImm(0)
14976         .addReg(OffsetReg)
14977         .addImm(X86::sub_32bit);
14978
14979     // Add the offset to the reg_save_area to get the final address.
14980     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14981       .addReg(OffsetReg64)
14982       .addReg(RegSaveReg);
14983
14984     // Compute the offset for the next argument
14985     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14986     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14987       .addReg(OffsetReg)
14988       .addImm(UseFPOffset ? 16 : 8);
14989
14990     // Store it back into the va_list.
14991     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14992       .addOperand(Base)
14993       .addOperand(Scale)
14994       .addOperand(Index)
14995       .addDisp(Disp, UseFPOffset ? 4 : 0)
14996       .addOperand(Segment)
14997       .addReg(NextOffsetReg)
14998       .setMemRefs(MMOBegin, MMOEnd);
14999
15000     // Jump to endMBB
15001     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15002       .addMBB(endMBB);
15003   }
15004
15005   //
15006   // Emit code to use overflow area
15007   //
15008
15009   // Load the overflow_area address into a register.
15010   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15011   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15012     .addOperand(Base)
15013     .addOperand(Scale)
15014     .addOperand(Index)
15015     .addDisp(Disp, 8)
15016     .addOperand(Segment)
15017     .setMemRefs(MMOBegin, MMOEnd);
15018
15019   // If we need to align it, do so. Otherwise, just copy the address
15020   // to OverflowDestReg.
15021   if (NeedsAlign) {
15022     // Align the overflow address
15023     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15024     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15025
15026     // aligned_addr = (addr + (align-1)) & ~(align-1)
15027     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15028       .addReg(OverflowAddrReg)
15029       .addImm(Align-1);
15030
15031     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15032       .addReg(TmpReg)
15033       .addImm(~(uint64_t)(Align-1));
15034   } else {
15035     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15036       .addReg(OverflowAddrReg);
15037   }
15038
15039   // Compute the next overflow address after this argument.
15040   // (the overflow address should be kept 8-byte aligned)
15041   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15042   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15043     .addReg(OverflowDestReg)
15044     .addImm(ArgSizeA8);
15045
15046   // Store the new overflow address.
15047   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15048     .addOperand(Base)
15049     .addOperand(Scale)
15050     .addOperand(Index)
15051     .addDisp(Disp, 8)
15052     .addOperand(Segment)
15053     .addReg(NextAddrReg)
15054     .setMemRefs(MMOBegin, MMOEnd);
15055
15056   // If we branched, emit the PHI to the front of endMBB.
15057   if (offsetMBB) {
15058     BuildMI(*endMBB, endMBB->begin(), DL,
15059             TII->get(X86::PHI), DestReg)
15060       .addReg(OffsetDestReg).addMBB(offsetMBB)
15061       .addReg(OverflowDestReg).addMBB(overflowMBB);
15062   }
15063
15064   // Erase the pseudo instruction
15065   MI->eraseFromParent();
15066
15067   return endMBB;
15068 }
15069
15070 MachineBasicBlock *
15071 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15072                                                  MachineInstr *MI,
15073                                                  MachineBasicBlock *MBB) const {
15074   // Emit code to save XMM registers to the stack. The ABI says that the
15075   // number of registers to save is given in %al, so it's theoretically
15076   // possible to do an indirect jump trick to avoid saving all of them,
15077   // however this code takes a simpler approach and just executes all
15078   // of the stores if %al is non-zero. It's less code, and it's probably
15079   // easier on the hardware branch predictor, and stores aren't all that
15080   // expensive anyway.
15081
15082   // Create the new basic blocks. One block contains all the XMM stores,
15083   // and one block is the final destination regardless of whether any
15084   // stores were performed.
15085   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15086   MachineFunction *F = MBB->getParent();
15087   MachineFunction::iterator MBBIter = MBB;
15088   ++MBBIter;
15089   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15090   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15091   F->insert(MBBIter, XMMSaveMBB);
15092   F->insert(MBBIter, EndMBB);
15093
15094   // Transfer the remainder of MBB and its successor edges to EndMBB.
15095   EndMBB->splice(EndMBB->begin(), MBB,
15096                  llvm::next(MachineBasicBlock::iterator(MI)),
15097                  MBB->end());
15098   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15099
15100   // The original block will now fall through to the XMM save block.
15101   MBB->addSuccessor(XMMSaveMBB);
15102   // The XMMSaveMBB will fall through to the end block.
15103   XMMSaveMBB->addSuccessor(EndMBB);
15104
15105   // Now add the instructions.
15106   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15107   DebugLoc DL = MI->getDebugLoc();
15108
15109   unsigned CountReg = MI->getOperand(0).getReg();
15110   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15111   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15112
15113   if (!Subtarget->isTargetWin64()) {
15114     // If %al is 0, branch around the XMM save block.
15115     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15116     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15117     MBB->addSuccessor(EndMBB);
15118   }
15119
15120   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15121   // In the XMM save block, save all the XMM argument registers.
15122   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
15123     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15124     MachineMemOperand *MMO =
15125       F->getMachineMemOperand(
15126           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15127         MachineMemOperand::MOStore,
15128         /*Size=*/16, /*Align=*/16);
15129     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15130       .addFrameIndex(RegSaveFrameIndex)
15131       .addImm(/*Scale=*/1)
15132       .addReg(/*IndexReg=*/0)
15133       .addImm(/*Disp=*/Offset)
15134       .addReg(/*Segment=*/0)
15135       .addReg(MI->getOperand(i).getReg())
15136       .addMemOperand(MMO);
15137   }
15138
15139   MI->eraseFromParent();   // The pseudo instruction is gone now.
15140
15141   return EndMBB;
15142 }
15143
15144 // The EFLAGS operand of SelectItr might be missing a kill marker
15145 // because there were multiple uses of EFLAGS, and ISel didn't know
15146 // which to mark. Figure out whether SelectItr should have had a
15147 // kill marker, and set it if it should. Returns the correct kill
15148 // marker value.
15149 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15150                                      MachineBasicBlock* BB,
15151                                      const TargetRegisterInfo* TRI) {
15152   // Scan forward through BB for a use/def of EFLAGS.
15153   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15154   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15155     const MachineInstr& mi = *miI;
15156     if (mi.readsRegister(X86::EFLAGS))
15157       return false;
15158     if (mi.definesRegister(X86::EFLAGS))
15159       break; // Should have kill-flag - update below.
15160   }
15161
15162   // If we hit the end of the block, check whether EFLAGS is live into a
15163   // successor.
15164   if (miI == BB->end()) {
15165     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15166                                           sEnd = BB->succ_end();
15167          sItr != sEnd; ++sItr) {
15168       MachineBasicBlock* succ = *sItr;
15169       if (succ->isLiveIn(X86::EFLAGS))
15170         return false;
15171     }
15172   }
15173
15174   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15175   // out. SelectMI should have a kill flag on EFLAGS.
15176   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15177   return true;
15178 }
15179
15180 MachineBasicBlock *
15181 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15182                                      MachineBasicBlock *BB) const {
15183   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15184   DebugLoc DL = MI->getDebugLoc();
15185
15186   // To "insert" a SELECT_CC instruction, we actually have to insert the
15187   // diamond control-flow pattern.  The incoming instruction knows the
15188   // destination vreg to set, the condition code register to branch on, the
15189   // true/false values to select between, and a branch opcode to use.
15190   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15191   MachineFunction::iterator It = BB;
15192   ++It;
15193
15194   //  thisMBB:
15195   //  ...
15196   //   TrueVal = ...
15197   //   cmpTY ccX, r1, r2
15198   //   bCC copy1MBB
15199   //   fallthrough --> copy0MBB
15200   MachineBasicBlock *thisMBB = BB;
15201   MachineFunction *F = BB->getParent();
15202   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15203   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15204   F->insert(It, copy0MBB);
15205   F->insert(It, sinkMBB);
15206
15207   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15208   // live into the sink and copy blocks.
15209   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15210   if (!MI->killsRegister(X86::EFLAGS) &&
15211       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15212     copy0MBB->addLiveIn(X86::EFLAGS);
15213     sinkMBB->addLiveIn(X86::EFLAGS);
15214   }
15215
15216   // Transfer the remainder of BB and its successor edges to sinkMBB.
15217   sinkMBB->splice(sinkMBB->begin(), BB,
15218                   llvm::next(MachineBasicBlock::iterator(MI)),
15219                   BB->end());
15220   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15221
15222   // Add the true and fallthrough blocks as its successors.
15223   BB->addSuccessor(copy0MBB);
15224   BB->addSuccessor(sinkMBB);
15225
15226   // Create the conditional branch instruction.
15227   unsigned Opc =
15228     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15229   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15230
15231   //  copy0MBB:
15232   //   %FalseValue = ...
15233   //   # fallthrough to sinkMBB
15234   copy0MBB->addSuccessor(sinkMBB);
15235
15236   //  sinkMBB:
15237   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15238   //  ...
15239   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15240           TII->get(X86::PHI), MI->getOperand(0).getReg())
15241     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15242     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15243
15244   MI->eraseFromParent();   // The pseudo instruction is gone now.
15245   return sinkMBB;
15246 }
15247
15248 MachineBasicBlock *
15249 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15250                                         bool Is64Bit) const {
15251   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15252   DebugLoc DL = MI->getDebugLoc();
15253   MachineFunction *MF = BB->getParent();
15254   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15255
15256   assert(getTargetMachine().Options.EnableSegmentedStacks);
15257
15258   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15259   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15260
15261   // BB:
15262   //  ... [Till the alloca]
15263   // If stacklet is not large enough, jump to mallocMBB
15264   //
15265   // bumpMBB:
15266   //  Allocate by subtracting from RSP
15267   //  Jump to continueMBB
15268   //
15269   // mallocMBB:
15270   //  Allocate by call to runtime
15271   //
15272   // continueMBB:
15273   //  ...
15274   //  [rest of original BB]
15275   //
15276
15277   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15278   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15279   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15280
15281   MachineRegisterInfo &MRI = MF->getRegInfo();
15282   const TargetRegisterClass *AddrRegClass =
15283     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15284
15285   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15286     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15287     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15288     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15289     sizeVReg = MI->getOperand(1).getReg(),
15290     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15291
15292   MachineFunction::iterator MBBIter = BB;
15293   ++MBBIter;
15294
15295   MF->insert(MBBIter, bumpMBB);
15296   MF->insert(MBBIter, mallocMBB);
15297   MF->insert(MBBIter, continueMBB);
15298
15299   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15300                       (MachineBasicBlock::iterator(MI)), BB->end());
15301   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15302
15303   // Add code to the main basic block to check if the stack limit has been hit,
15304   // and if so, jump to mallocMBB otherwise to bumpMBB.
15305   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15306   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15307     .addReg(tmpSPVReg).addReg(sizeVReg);
15308   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15309     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15310     .addReg(SPLimitVReg);
15311   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15312
15313   // bumpMBB simply decreases the stack pointer, since we know the current
15314   // stacklet has enough space.
15315   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15316     .addReg(SPLimitVReg);
15317   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15318     .addReg(SPLimitVReg);
15319   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15320
15321   // Calls into a routine in libgcc to allocate more space from the heap.
15322   const uint32_t *RegMask =
15323     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15324   if (Is64Bit) {
15325     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15326       .addReg(sizeVReg);
15327     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15328       .addExternalSymbol("__morestack_allocate_stack_space")
15329       .addRegMask(RegMask)
15330       .addReg(X86::RDI, RegState::Implicit)
15331       .addReg(X86::RAX, RegState::ImplicitDefine);
15332   } else {
15333     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15334       .addImm(12);
15335     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15336     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15337       .addExternalSymbol("__morestack_allocate_stack_space")
15338       .addRegMask(RegMask)
15339       .addReg(X86::EAX, RegState::ImplicitDefine);
15340   }
15341
15342   if (!Is64Bit)
15343     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15344       .addImm(16);
15345
15346   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15347     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15348   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15349
15350   // Set up the CFG correctly.
15351   BB->addSuccessor(bumpMBB);
15352   BB->addSuccessor(mallocMBB);
15353   mallocMBB->addSuccessor(continueMBB);
15354   bumpMBB->addSuccessor(continueMBB);
15355
15356   // Take care of the PHI nodes.
15357   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15358           MI->getOperand(0).getReg())
15359     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15360     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15361
15362   // Delete the original pseudo instruction.
15363   MI->eraseFromParent();
15364
15365   // And we're done.
15366   return continueMBB;
15367 }
15368
15369 MachineBasicBlock *
15370 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15371                                           MachineBasicBlock *BB) const {
15372   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15373   DebugLoc DL = MI->getDebugLoc();
15374
15375   assert(!Subtarget->isTargetEnvMacho());
15376
15377   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15378   // non-trivial part is impdef of ESP.
15379
15380   if (Subtarget->isTargetWin64()) {
15381     if (Subtarget->isTargetCygMing()) {
15382       // ___chkstk(Mingw64):
15383       // Clobbers R10, R11, RAX and EFLAGS.
15384       // Updates RSP.
15385       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15386         .addExternalSymbol("___chkstk")
15387         .addReg(X86::RAX, RegState::Implicit)
15388         .addReg(X86::RSP, RegState::Implicit)
15389         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15390         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15391         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15392     } else {
15393       // __chkstk(MSVCRT): does not update stack pointer.
15394       // Clobbers R10, R11 and EFLAGS.
15395       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15396         .addExternalSymbol("__chkstk")
15397         .addReg(X86::RAX, RegState::Implicit)
15398         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15399       // RAX has the offset to be subtracted from RSP.
15400       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15401         .addReg(X86::RSP)
15402         .addReg(X86::RAX);
15403     }
15404   } else {
15405     const char *StackProbeSymbol =
15406       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15407
15408     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15409       .addExternalSymbol(StackProbeSymbol)
15410       .addReg(X86::EAX, RegState::Implicit)
15411       .addReg(X86::ESP, RegState::Implicit)
15412       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15413       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15414       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15415   }
15416
15417   MI->eraseFromParent();   // The pseudo instruction is gone now.
15418   return BB;
15419 }
15420
15421 MachineBasicBlock *
15422 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15423                                       MachineBasicBlock *BB) const {
15424   // This is pretty easy.  We're taking the value that we received from
15425   // our load from the relocation, sticking it in either RDI (x86-64)
15426   // or EAX and doing an indirect call.  The return value will then
15427   // be in the normal return register.
15428   const X86InstrInfo *TII
15429     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15430   DebugLoc DL = MI->getDebugLoc();
15431   MachineFunction *F = BB->getParent();
15432
15433   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15434   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15435
15436   // Get a register mask for the lowered call.
15437   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15438   // proper register mask.
15439   const uint32_t *RegMask =
15440     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15441   if (Subtarget->is64Bit()) {
15442     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15443                                       TII->get(X86::MOV64rm), X86::RDI)
15444     .addReg(X86::RIP)
15445     .addImm(0).addReg(0)
15446     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15447                       MI->getOperand(3).getTargetFlags())
15448     .addReg(0);
15449     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15450     addDirectMem(MIB, X86::RDI);
15451     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15452   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15453     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15454                                       TII->get(X86::MOV32rm), X86::EAX)
15455     .addReg(0)
15456     .addImm(0).addReg(0)
15457     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15458                       MI->getOperand(3).getTargetFlags())
15459     .addReg(0);
15460     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15461     addDirectMem(MIB, X86::EAX);
15462     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15463   } else {
15464     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15465                                       TII->get(X86::MOV32rm), X86::EAX)
15466     .addReg(TII->getGlobalBaseReg(F))
15467     .addImm(0).addReg(0)
15468     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15469                       MI->getOperand(3).getTargetFlags())
15470     .addReg(0);
15471     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15472     addDirectMem(MIB, X86::EAX);
15473     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15474   }
15475
15476   MI->eraseFromParent(); // The pseudo instruction is gone now.
15477   return BB;
15478 }
15479
15480 MachineBasicBlock *
15481 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15482                                     MachineBasicBlock *MBB) const {
15483   DebugLoc DL = MI->getDebugLoc();
15484   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15485
15486   MachineFunction *MF = MBB->getParent();
15487   MachineRegisterInfo &MRI = MF->getRegInfo();
15488
15489   const BasicBlock *BB = MBB->getBasicBlock();
15490   MachineFunction::iterator I = MBB;
15491   ++I;
15492
15493   // Memory Reference
15494   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15495   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15496
15497   unsigned DstReg;
15498   unsigned MemOpndSlot = 0;
15499
15500   unsigned CurOp = 0;
15501
15502   DstReg = MI->getOperand(CurOp++).getReg();
15503   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15504   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15505   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15506   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15507
15508   MemOpndSlot = CurOp;
15509
15510   MVT PVT = getPointerTy();
15511   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15512          "Invalid Pointer Size!");
15513
15514   // For v = setjmp(buf), we generate
15515   //
15516   // thisMBB:
15517   //  buf[LabelOffset] = restoreMBB
15518   //  SjLjSetup restoreMBB
15519   //
15520   // mainMBB:
15521   //  v_main = 0
15522   //
15523   // sinkMBB:
15524   //  v = phi(main, restore)
15525   //
15526   // restoreMBB:
15527   //  v_restore = 1
15528
15529   MachineBasicBlock *thisMBB = MBB;
15530   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15531   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15532   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15533   MF->insert(I, mainMBB);
15534   MF->insert(I, sinkMBB);
15535   MF->push_back(restoreMBB);
15536
15537   MachineInstrBuilder MIB;
15538
15539   // Transfer the remainder of BB and its successor edges to sinkMBB.
15540   sinkMBB->splice(sinkMBB->begin(), MBB,
15541                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15542   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15543
15544   // thisMBB:
15545   unsigned PtrStoreOpc = 0;
15546   unsigned LabelReg = 0;
15547   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15548   Reloc::Model RM = getTargetMachine().getRelocationModel();
15549   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15550                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15551
15552   // Prepare IP either in reg or imm.
15553   if (!UseImmLabel) {
15554     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15555     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15556     LabelReg = MRI.createVirtualRegister(PtrRC);
15557     if (Subtarget->is64Bit()) {
15558       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15559               .addReg(X86::RIP)
15560               .addImm(0)
15561               .addReg(0)
15562               .addMBB(restoreMBB)
15563               .addReg(0);
15564     } else {
15565       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15566       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15567               .addReg(XII->getGlobalBaseReg(MF))
15568               .addImm(0)
15569               .addReg(0)
15570               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15571               .addReg(0);
15572     }
15573   } else
15574     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15575   // Store IP
15576   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15577   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15578     if (i == X86::AddrDisp)
15579       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15580     else
15581       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15582   }
15583   if (!UseImmLabel)
15584     MIB.addReg(LabelReg);
15585   else
15586     MIB.addMBB(restoreMBB);
15587   MIB.setMemRefs(MMOBegin, MMOEnd);
15588   // Setup
15589   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15590           .addMBB(restoreMBB);
15591
15592   const X86RegisterInfo *RegInfo =
15593     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15594   MIB.addRegMask(RegInfo->getNoPreservedMask());
15595   thisMBB->addSuccessor(mainMBB);
15596   thisMBB->addSuccessor(restoreMBB);
15597
15598   // mainMBB:
15599   //  EAX = 0
15600   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15601   mainMBB->addSuccessor(sinkMBB);
15602
15603   // sinkMBB:
15604   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15605           TII->get(X86::PHI), DstReg)
15606     .addReg(mainDstReg).addMBB(mainMBB)
15607     .addReg(restoreDstReg).addMBB(restoreMBB);
15608
15609   // restoreMBB:
15610   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15611   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15612   restoreMBB->addSuccessor(sinkMBB);
15613
15614   MI->eraseFromParent();
15615   return sinkMBB;
15616 }
15617
15618 MachineBasicBlock *
15619 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15620                                      MachineBasicBlock *MBB) const {
15621   DebugLoc DL = MI->getDebugLoc();
15622   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15623
15624   MachineFunction *MF = MBB->getParent();
15625   MachineRegisterInfo &MRI = MF->getRegInfo();
15626
15627   // Memory Reference
15628   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15629   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15630
15631   MVT PVT = getPointerTy();
15632   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15633          "Invalid Pointer Size!");
15634
15635   const TargetRegisterClass *RC =
15636     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15637   unsigned Tmp = MRI.createVirtualRegister(RC);
15638   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15639   const X86RegisterInfo *RegInfo =
15640     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15641   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15642   unsigned SP = RegInfo->getStackRegister();
15643
15644   MachineInstrBuilder MIB;
15645
15646   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15647   const int64_t SPOffset = 2 * PVT.getStoreSize();
15648
15649   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15650   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15651
15652   // Reload FP
15653   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15654   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15655     MIB.addOperand(MI->getOperand(i));
15656   MIB.setMemRefs(MMOBegin, MMOEnd);
15657   // Reload IP
15658   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15659   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15660     if (i == X86::AddrDisp)
15661       MIB.addDisp(MI->getOperand(i), LabelOffset);
15662     else
15663       MIB.addOperand(MI->getOperand(i));
15664   }
15665   MIB.setMemRefs(MMOBegin, MMOEnd);
15666   // Reload SP
15667   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15668   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15669     if (i == X86::AddrDisp)
15670       MIB.addDisp(MI->getOperand(i), SPOffset);
15671     else
15672       MIB.addOperand(MI->getOperand(i));
15673   }
15674   MIB.setMemRefs(MMOBegin, MMOEnd);
15675   // Jump
15676   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15677
15678   MI->eraseFromParent();
15679   return MBB;
15680 }
15681
15682 MachineBasicBlock *
15683 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15684                                                MachineBasicBlock *BB) const {
15685   switch (MI->getOpcode()) {
15686   default: llvm_unreachable("Unexpected instr type to insert");
15687   case X86::TAILJMPd64:
15688   case X86::TAILJMPr64:
15689   case X86::TAILJMPm64:
15690     llvm_unreachable("TAILJMP64 would not be touched here.");
15691   case X86::TCRETURNdi64:
15692   case X86::TCRETURNri64:
15693   case X86::TCRETURNmi64:
15694     return BB;
15695   case X86::WIN_ALLOCA:
15696     return EmitLoweredWinAlloca(MI, BB);
15697   case X86::SEG_ALLOCA_32:
15698     return EmitLoweredSegAlloca(MI, BB, false);
15699   case X86::SEG_ALLOCA_64:
15700     return EmitLoweredSegAlloca(MI, BB, true);
15701   case X86::TLSCall_32:
15702   case X86::TLSCall_64:
15703     return EmitLoweredTLSCall(MI, BB);
15704   case X86::CMOV_GR8:
15705   case X86::CMOV_FR32:
15706   case X86::CMOV_FR64:
15707   case X86::CMOV_V4F32:
15708   case X86::CMOV_V2F64:
15709   case X86::CMOV_V2I64:
15710   case X86::CMOV_V8F32:
15711   case X86::CMOV_V4F64:
15712   case X86::CMOV_V4I64:
15713   case X86::CMOV_GR16:
15714   case X86::CMOV_GR32:
15715   case X86::CMOV_RFP32:
15716   case X86::CMOV_RFP64:
15717   case X86::CMOV_RFP80:
15718     return EmitLoweredSelect(MI, BB);
15719
15720   case X86::FP32_TO_INT16_IN_MEM:
15721   case X86::FP32_TO_INT32_IN_MEM:
15722   case X86::FP32_TO_INT64_IN_MEM:
15723   case X86::FP64_TO_INT16_IN_MEM:
15724   case X86::FP64_TO_INT32_IN_MEM:
15725   case X86::FP64_TO_INT64_IN_MEM:
15726   case X86::FP80_TO_INT16_IN_MEM:
15727   case X86::FP80_TO_INT32_IN_MEM:
15728   case X86::FP80_TO_INT64_IN_MEM: {
15729     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15730     DebugLoc DL = MI->getDebugLoc();
15731
15732     // Change the floating point control register to use "round towards zero"
15733     // mode when truncating to an integer value.
15734     MachineFunction *F = BB->getParent();
15735     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15736     addFrameReference(BuildMI(*BB, MI, DL,
15737                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15738
15739     // Load the old value of the high byte of the control word...
15740     unsigned OldCW =
15741       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15742     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15743                       CWFrameIdx);
15744
15745     // Set the high part to be round to zero...
15746     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15747       .addImm(0xC7F);
15748
15749     // Reload the modified control word now...
15750     addFrameReference(BuildMI(*BB, MI, DL,
15751                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15752
15753     // Restore the memory image of control word to original value
15754     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15755       .addReg(OldCW);
15756
15757     // Get the X86 opcode to use.
15758     unsigned Opc;
15759     switch (MI->getOpcode()) {
15760     default: llvm_unreachable("illegal opcode!");
15761     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15762     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15763     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15764     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15765     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15766     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15767     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15768     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15769     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15770     }
15771
15772     X86AddressMode AM;
15773     MachineOperand &Op = MI->getOperand(0);
15774     if (Op.isReg()) {
15775       AM.BaseType = X86AddressMode::RegBase;
15776       AM.Base.Reg = Op.getReg();
15777     } else {
15778       AM.BaseType = X86AddressMode::FrameIndexBase;
15779       AM.Base.FrameIndex = Op.getIndex();
15780     }
15781     Op = MI->getOperand(1);
15782     if (Op.isImm())
15783       AM.Scale = Op.getImm();
15784     Op = MI->getOperand(2);
15785     if (Op.isImm())
15786       AM.IndexReg = Op.getImm();
15787     Op = MI->getOperand(3);
15788     if (Op.isGlobal()) {
15789       AM.GV = Op.getGlobal();
15790     } else {
15791       AM.Disp = Op.getImm();
15792     }
15793     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15794                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15795
15796     // Reload the original control word now.
15797     addFrameReference(BuildMI(*BB, MI, DL,
15798                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15799
15800     MI->eraseFromParent();   // The pseudo instruction is gone now.
15801     return BB;
15802   }
15803     // String/text processing lowering.
15804   case X86::PCMPISTRM128REG:
15805   case X86::VPCMPISTRM128REG:
15806   case X86::PCMPISTRM128MEM:
15807   case X86::VPCMPISTRM128MEM:
15808   case X86::PCMPESTRM128REG:
15809   case X86::VPCMPESTRM128REG:
15810   case X86::PCMPESTRM128MEM:
15811   case X86::VPCMPESTRM128MEM:
15812     assert(Subtarget->hasSSE42() &&
15813            "Target must have SSE4.2 or AVX features enabled");
15814     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15815
15816   // String/text processing lowering.
15817   case X86::PCMPISTRIREG:
15818   case X86::VPCMPISTRIREG:
15819   case X86::PCMPISTRIMEM:
15820   case X86::VPCMPISTRIMEM:
15821   case X86::PCMPESTRIREG:
15822   case X86::VPCMPESTRIREG:
15823   case X86::PCMPESTRIMEM:
15824   case X86::VPCMPESTRIMEM:
15825     assert(Subtarget->hasSSE42() &&
15826            "Target must have SSE4.2 or AVX features enabled");
15827     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15828
15829   // Thread synchronization.
15830   case X86::MONITOR:
15831     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15832
15833   // xbegin
15834   case X86::XBEGIN:
15835     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15836
15837   // Atomic Lowering.
15838   case X86::ATOMAND8:
15839   case X86::ATOMAND16:
15840   case X86::ATOMAND32:
15841   case X86::ATOMAND64:
15842     // Fall through
15843   case X86::ATOMOR8:
15844   case X86::ATOMOR16:
15845   case X86::ATOMOR32:
15846   case X86::ATOMOR64:
15847     // Fall through
15848   case X86::ATOMXOR16:
15849   case X86::ATOMXOR8:
15850   case X86::ATOMXOR32:
15851   case X86::ATOMXOR64:
15852     // Fall through
15853   case X86::ATOMNAND8:
15854   case X86::ATOMNAND16:
15855   case X86::ATOMNAND32:
15856   case X86::ATOMNAND64:
15857     // Fall through
15858   case X86::ATOMMAX8:
15859   case X86::ATOMMAX16:
15860   case X86::ATOMMAX32:
15861   case X86::ATOMMAX64:
15862     // Fall through
15863   case X86::ATOMMIN8:
15864   case X86::ATOMMIN16:
15865   case X86::ATOMMIN32:
15866   case X86::ATOMMIN64:
15867     // Fall through
15868   case X86::ATOMUMAX8:
15869   case X86::ATOMUMAX16:
15870   case X86::ATOMUMAX32:
15871   case X86::ATOMUMAX64:
15872     // Fall through
15873   case X86::ATOMUMIN8:
15874   case X86::ATOMUMIN16:
15875   case X86::ATOMUMIN32:
15876   case X86::ATOMUMIN64:
15877     return EmitAtomicLoadArith(MI, BB);
15878
15879   // This group does 64-bit operations on a 32-bit host.
15880   case X86::ATOMAND6432:
15881   case X86::ATOMOR6432:
15882   case X86::ATOMXOR6432:
15883   case X86::ATOMNAND6432:
15884   case X86::ATOMADD6432:
15885   case X86::ATOMSUB6432:
15886   case X86::ATOMMAX6432:
15887   case X86::ATOMMIN6432:
15888   case X86::ATOMUMAX6432:
15889   case X86::ATOMUMIN6432:
15890   case X86::ATOMSWAP6432:
15891     return EmitAtomicLoadArith6432(MI, BB);
15892
15893   case X86::VASTART_SAVE_XMM_REGS:
15894     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15895
15896   case X86::VAARG_64:
15897     return EmitVAARG64WithCustomInserter(MI, BB);
15898
15899   case X86::EH_SjLj_SetJmp32:
15900   case X86::EH_SjLj_SetJmp64:
15901     return emitEHSjLjSetJmp(MI, BB);
15902
15903   case X86::EH_SjLj_LongJmp32:
15904   case X86::EH_SjLj_LongJmp64:
15905     return emitEHSjLjLongJmp(MI, BB);
15906   }
15907 }
15908
15909 //===----------------------------------------------------------------------===//
15910 //                           X86 Optimization Hooks
15911 //===----------------------------------------------------------------------===//
15912
15913 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15914                                                        APInt &KnownZero,
15915                                                        APInt &KnownOne,
15916                                                        const SelectionDAG &DAG,
15917                                                        unsigned Depth) const {
15918   unsigned BitWidth = KnownZero.getBitWidth();
15919   unsigned Opc = Op.getOpcode();
15920   assert((Opc >= ISD::BUILTIN_OP_END ||
15921           Opc == ISD::INTRINSIC_WO_CHAIN ||
15922           Opc == ISD::INTRINSIC_W_CHAIN ||
15923           Opc == ISD::INTRINSIC_VOID) &&
15924          "Should use MaskedValueIsZero if you don't know whether Op"
15925          " is a target node!");
15926
15927   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15928   switch (Opc) {
15929   default: break;
15930   case X86ISD::ADD:
15931   case X86ISD::SUB:
15932   case X86ISD::ADC:
15933   case X86ISD::SBB:
15934   case X86ISD::SMUL:
15935   case X86ISD::UMUL:
15936   case X86ISD::INC:
15937   case X86ISD::DEC:
15938   case X86ISD::OR:
15939   case X86ISD::XOR:
15940   case X86ISD::AND:
15941     // These nodes' second result is a boolean.
15942     if (Op.getResNo() == 0)
15943       break;
15944     // Fallthrough
15945   case X86ISD::SETCC:
15946     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15947     break;
15948   case ISD::INTRINSIC_WO_CHAIN: {
15949     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15950     unsigned NumLoBits = 0;
15951     switch (IntId) {
15952     default: break;
15953     case Intrinsic::x86_sse_movmsk_ps:
15954     case Intrinsic::x86_avx_movmsk_ps_256:
15955     case Intrinsic::x86_sse2_movmsk_pd:
15956     case Intrinsic::x86_avx_movmsk_pd_256:
15957     case Intrinsic::x86_mmx_pmovmskb:
15958     case Intrinsic::x86_sse2_pmovmskb_128:
15959     case Intrinsic::x86_avx2_pmovmskb: {
15960       // High bits of movmskp{s|d}, pmovmskb are known zero.
15961       switch (IntId) {
15962         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15963         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15964         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15965         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15966         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15967         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15968         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15969         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15970       }
15971       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15972       break;
15973     }
15974     }
15975     break;
15976   }
15977   }
15978 }
15979
15980 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15981                                                          unsigned Depth) const {
15982   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15983   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15984     return Op.getValueType().getScalarType().getSizeInBits();
15985
15986   // Fallback case.
15987   return 1;
15988 }
15989
15990 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15991 /// node is a GlobalAddress + offset.
15992 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15993                                        const GlobalValue* &GA,
15994                                        int64_t &Offset) const {
15995   if (N->getOpcode() == X86ISD::Wrapper) {
15996     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15997       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15998       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15999       return true;
16000     }
16001   }
16002   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16003 }
16004
16005 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16006 /// same as extracting the high 128-bit part of 256-bit vector and then
16007 /// inserting the result into the low part of a new 256-bit vector
16008 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16009   EVT VT = SVOp->getValueType(0);
16010   unsigned NumElems = VT.getVectorNumElements();
16011
16012   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16013   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16014     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16015         SVOp->getMaskElt(j) >= 0)
16016       return false;
16017
16018   return true;
16019 }
16020
16021 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16022 /// same as extracting the low 128-bit part of 256-bit vector and then
16023 /// inserting the result into the high part of a new 256-bit vector
16024 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16025   EVT VT = SVOp->getValueType(0);
16026   unsigned NumElems = VT.getVectorNumElements();
16027
16028   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16029   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16030     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16031         SVOp->getMaskElt(j) >= 0)
16032       return false;
16033
16034   return true;
16035 }
16036
16037 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16038 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16039                                         TargetLowering::DAGCombinerInfo &DCI,
16040                                         const X86Subtarget* Subtarget) {
16041   SDLoc dl(N);
16042   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16043   SDValue V1 = SVOp->getOperand(0);
16044   SDValue V2 = SVOp->getOperand(1);
16045   EVT VT = SVOp->getValueType(0);
16046   unsigned NumElems = VT.getVectorNumElements();
16047
16048   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16049       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16050     //
16051     //                   0,0,0,...
16052     //                      |
16053     //    V      UNDEF    BUILD_VECTOR    UNDEF
16054     //     \      /           \           /
16055     //  CONCAT_VECTOR         CONCAT_VECTOR
16056     //         \                  /
16057     //          \                /
16058     //          RESULT: V + zero extended
16059     //
16060     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16061         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16062         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16063       return SDValue();
16064
16065     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16066       return SDValue();
16067
16068     // To match the shuffle mask, the first half of the mask should
16069     // be exactly the first vector, and all the rest a splat with the
16070     // first element of the second one.
16071     for (unsigned i = 0; i != NumElems/2; ++i)
16072       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16073           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16074         return SDValue();
16075
16076     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16077     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16078       if (Ld->hasNUsesOfValue(1, 0)) {
16079         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16080         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16081         SDValue ResNode =
16082           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16083                                   array_lengthof(Ops),
16084                                   Ld->getMemoryVT(),
16085                                   Ld->getPointerInfo(),
16086                                   Ld->getAlignment(),
16087                                   false/*isVolatile*/, true/*ReadMem*/,
16088                                   false/*WriteMem*/);
16089
16090         // Make sure the newly-created LOAD is in the same position as Ld in
16091         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16092         // and update uses of Ld's output chain to use the TokenFactor.
16093         if (Ld->hasAnyUseOfValue(1)) {
16094           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16095                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16096           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16097           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16098                                  SDValue(ResNode.getNode(), 1));
16099         }
16100
16101         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16102       }
16103     }
16104
16105     // Emit a zeroed vector and insert the desired subvector on its
16106     // first half.
16107     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16108     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16109     return DCI.CombineTo(N, InsV);
16110   }
16111
16112   //===--------------------------------------------------------------------===//
16113   // Combine some shuffles into subvector extracts and inserts:
16114   //
16115
16116   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16117   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16118     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16119     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16120     return DCI.CombineTo(N, InsV);
16121   }
16122
16123   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16124   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16125     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16126     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16127     return DCI.CombineTo(N, InsV);
16128   }
16129
16130   return SDValue();
16131 }
16132
16133 /// PerformShuffleCombine - Performs several different shuffle combines.
16134 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16135                                      TargetLowering::DAGCombinerInfo &DCI,
16136                                      const X86Subtarget *Subtarget) {
16137   SDLoc dl(N);
16138   EVT VT = N->getValueType(0);
16139
16140   // Don't create instructions with illegal types after legalize types has run.
16141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16142   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16143     return SDValue();
16144
16145   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16146   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16147       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16148     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16149
16150   // Only handle 128 wide vector from here on.
16151   if (!VT.is128BitVector())
16152     return SDValue();
16153
16154   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16155   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16156   // consecutive, non-overlapping, and in the right order.
16157   SmallVector<SDValue, 16> Elts;
16158   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16159     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16160
16161   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
16162 }
16163
16164 /// PerformTruncateCombine - Converts truncate operation to
16165 /// a sequence of vector shuffle operations.
16166 /// It is possible when we truncate 256-bit vector to 128-bit vector
16167 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16168                                       TargetLowering::DAGCombinerInfo &DCI,
16169                                       const X86Subtarget *Subtarget)  {
16170   return SDValue();
16171 }
16172
16173 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16174 /// specific shuffle of a load can be folded into a single element load.
16175 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16176 /// shuffles have been customed lowered so we need to handle those here.
16177 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16178                                          TargetLowering::DAGCombinerInfo &DCI) {
16179   if (DCI.isBeforeLegalizeOps())
16180     return SDValue();
16181
16182   SDValue InVec = N->getOperand(0);
16183   SDValue EltNo = N->getOperand(1);
16184
16185   if (!isa<ConstantSDNode>(EltNo))
16186     return SDValue();
16187
16188   EVT VT = InVec.getValueType();
16189
16190   bool HasShuffleIntoBitcast = false;
16191   if (InVec.getOpcode() == ISD::BITCAST) {
16192     // Don't duplicate a load with other uses.
16193     if (!InVec.hasOneUse())
16194       return SDValue();
16195     EVT BCVT = InVec.getOperand(0).getValueType();
16196     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16197       return SDValue();
16198     InVec = InVec.getOperand(0);
16199     HasShuffleIntoBitcast = true;
16200   }
16201
16202   if (!isTargetShuffle(InVec.getOpcode()))
16203     return SDValue();
16204
16205   // Don't duplicate a load with other uses.
16206   if (!InVec.hasOneUse())
16207     return SDValue();
16208
16209   SmallVector<int, 16> ShuffleMask;
16210   bool UnaryShuffle;
16211   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16212                             UnaryShuffle))
16213     return SDValue();
16214
16215   // Select the input vector, guarding against out of range extract vector.
16216   unsigned NumElems = VT.getVectorNumElements();
16217   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16218   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16219   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16220                                          : InVec.getOperand(1);
16221
16222   // If inputs to shuffle are the same for both ops, then allow 2 uses
16223   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16224
16225   if (LdNode.getOpcode() == ISD::BITCAST) {
16226     // Don't duplicate a load with other uses.
16227     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16228       return SDValue();
16229
16230     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16231     LdNode = LdNode.getOperand(0);
16232   }
16233
16234   if (!ISD::isNormalLoad(LdNode.getNode()))
16235     return SDValue();
16236
16237   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16238
16239   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16240     return SDValue();
16241
16242   if (HasShuffleIntoBitcast) {
16243     // If there's a bitcast before the shuffle, check if the load type and
16244     // alignment is valid.
16245     unsigned Align = LN0->getAlignment();
16246     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16247     unsigned NewAlign = TLI.getDataLayout()->
16248       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16249
16250     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16251       return SDValue();
16252   }
16253
16254   // All checks match so transform back to vector_shuffle so that DAG combiner
16255   // can finish the job
16256   SDLoc dl(N);
16257
16258   // Create shuffle node taking into account the case that its a unary shuffle
16259   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16260   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16261                                  InVec.getOperand(0), Shuffle,
16262                                  &ShuffleMask[0]);
16263   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16264   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16265                      EltNo);
16266 }
16267
16268 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16269 /// generation and convert it from being a bunch of shuffles and extracts
16270 /// to a simple store and scalar loads to extract the elements.
16271 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16272                                          TargetLowering::DAGCombinerInfo &DCI) {
16273   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16274   if (NewOp.getNode())
16275     return NewOp;
16276
16277   SDValue InputVector = N->getOperand(0);
16278   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16279   // from mmx to v2i32 has a single usage.
16280   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16281       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16282       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16283     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16284                        N->getValueType(0),
16285                        InputVector.getNode()->getOperand(0));
16286
16287   // Only operate on vectors of 4 elements, where the alternative shuffling
16288   // gets to be more expensive.
16289   if (InputVector.getValueType() != MVT::v4i32)
16290     return SDValue();
16291
16292   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16293   // single use which is a sign-extend or zero-extend, and all elements are
16294   // used.
16295   SmallVector<SDNode *, 4> Uses;
16296   unsigned ExtractedElements = 0;
16297   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16298        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16299     if (UI.getUse().getResNo() != InputVector.getResNo())
16300       return SDValue();
16301
16302     SDNode *Extract = *UI;
16303     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16304       return SDValue();
16305
16306     if (Extract->getValueType(0) != MVT::i32)
16307       return SDValue();
16308     if (!Extract->hasOneUse())
16309       return SDValue();
16310     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16311         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16312       return SDValue();
16313     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16314       return SDValue();
16315
16316     // Record which element was extracted.
16317     ExtractedElements |=
16318       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16319
16320     Uses.push_back(Extract);
16321   }
16322
16323   // If not all the elements were used, this may not be worthwhile.
16324   if (ExtractedElements != 15)
16325     return SDValue();
16326
16327   // Ok, we've now decided to do the transformation.
16328   SDLoc dl(InputVector);
16329
16330   // Store the value to a temporary stack slot.
16331   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16332   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16333                             MachinePointerInfo(), false, false, 0);
16334
16335   // Replace each use (extract) with a load of the appropriate element.
16336   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16337        UE = Uses.end(); UI != UE; ++UI) {
16338     SDNode *Extract = *UI;
16339
16340     // cOMpute the element's address.
16341     SDValue Idx = Extract->getOperand(1);
16342     unsigned EltSize =
16343         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16344     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16345     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16346     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16347
16348     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16349                                      StackPtr, OffsetVal);
16350
16351     // Load the scalar.
16352     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16353                                      ScalarAddr, MachinePointerInfo(),
16354                                      false, false, false, 0);
16355
16356     // Replace the exact with the load.
16357     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16358   }
16359
16360   // The replacement was made in place; don't return anything.
16361   return SDValue();
16362 }
16363
16364 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16365 static std::pair<unsigned, bool>
16366 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16367                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16368   if (!VT.isVector())
16369     return std::make_pair(0, false);
16370
16371   bool NeedSplit = false;
16372   switch (VT.getSimpleVT().SimpleTy) {
16373   default: return std::make_pair(0, false);
16374   case MVT::v32i8:
16375   case MVT::v16i16:
16376   case MVT::v8i32:
16377     if (!Subtarget->hasAVX2())
16378       NeedSplit = true;
16379     if (!Subtarget->hasAVX())
16380       return std::make_pair(0, false);
16381     break;
16382   case MVT::v16i8:
16383   case MVT::v8i16:
16384   case MVT::v4i32:
16385     if (!Subtarget->hasSSE2())
16386       return std::make_pair(0, false);
16387   }
16388
16389   // SSE2 has only a small subset of the operations.
16390   bool hasUnsigned = Subtarget->hasSSE41() ||
16391                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16392   bool hasSigned = Subtarget->hasSSE41() ||
16393                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16394
16395   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16396
16397   unsigned Opc = 0;
16398   // Check for x CC y ? x : y.
16399   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16400       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16401     switch (CC) {
16402     default: break;
16403     case ISD::SETULT:
16404     case ISD::SETULE:
16405       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16406     case ISD::SETUGT:
16407     case ISD::SETUGE:
16408       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16409     case ISD::SETLT:
16410     case ISD::SETLE:
16411       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16412     case ISD::SETGT:
16413     case ISD::SETGE:
16414       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16415     }
16416   // Check for x CC y ? y : x -- a min/max with reversed arms.
16417   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16418              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16419     switch (CC) {
16420     default: break;
16421     case ISD::SETULT:
16422     case ISD::SETULE:
16423       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16424     case ISD::SETUGT:
16425     case ISD::SETUGE:
16426       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16427     case ISD::SETLT:
16428     case ISD::SETLE:
16429       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16430     case ISD::SETGT:
16431     case ISD::SETGE:
16432       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16433     }
16434   }
16435
16436   return std::make_pair(Opc, NeedSplit);
16437 }
16438
16439 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16440 /// nodes.
16441 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16442                                     TargetLowering::DAGCombinerInfo &DCI,
16443                                     const X86Subtarget *Subtarget) {
16444   SDLoc DL(N);
16445   SDValue Cond = N->getOperand(0);
16446   // Get the LHS/RHS of the select.
16447   SDValue LHS = N->getOperand(1);
16448   SDValue RHS = N->getOperand(2);
16449   EVT VT = LHS.getValueType();
16450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16451
16452   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16453   // instructions match the semantics of the common C idiom x<y?x:y but not
16454   // x<=y?x:y, because of how they handle negative zero (which can be
16455   // ignored in unsafe-math mode).
16456   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16457       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16458       (Subtarget->hasSSE2() ||
16459        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16460     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16461
16462     unsigned Opcode = 0;
16463     // Check for x CC y ? x : y.
16464     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16465         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16466       switch (CC) {
16467       default: break;
16468       case ISD::SETULT:
16469         // Converting this to a min would handle NaNs incorrectly, and swapping
16470         // the operands would cause it to handle comparisons between positive
16471         // and negative zero incorrectly.
16472         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16473           if (!DAG.getTarget().Options.UnsafeFPMath &&
16474               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16475             break;
16476           std::swap(LHS, RHS);
16477         }
16478         Opcode = X86ISD::FMIN;
16479         break;
16480       case ISD::SETOLE:
16481         // Converting this to a min would handle comparisons between positive
16482         // and negative zero incorrectly.
16483         if (!DAG.getTarget().Options.UnsafeFPMath &&
16484             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16485           break;
16486         Opcode = X86ISD::FMIN;
16487         break;
16488       case ISD::SETULE:
16489         // Converting this to a min would handle both negative zeros and NaNs
16490         // incorrectly, but we can swap the operands to fix both.
16491         std::swap(LHS, RHS);
16492       case ISD::SETOLT:
16493       case ISD::SETLT:
16494       case ISD::SETLE:
16495         Opcode = X86ISD::FMIN;
16496         break;
16497
16498       case ISD::SETOGE:
16499         // Converting this to a max would handle comparisons between positive
16500         // and negative zero incorrectly.
16501         if (!DAG.getTarget().Options.UnsafeFPMath &&
16502             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16503           break;
16504         Opcode = X86ISD::FMAX;
16505         break;
16506       case ISD::SETUGT:
16507         // Converting this to a max would handle NaNs incorrectly, and swapping
16508         // the operands would cause it to handle comparisons between positive
16509         // and negative zero incorrectly.
16510         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16511           if (!DAG.getTarget().Options.UnsafeFPMath &&
16512               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16513             break;
16514           std::swap(LHS, RHS);
16515         }
16516         Opcode = X86ISD::FMAX;
16517         break;
16518       case ISD::SETUGE:
16519         // Converting this to a max would handle both negative zeros and NaNs
16520         // incorrectly, but we can swap the operands to fix both.
16521         std::swap(LHS, RHS);
16522       case ISD::SETOGT:
16523       case ISD::SETGT:
16524       case ISD::SETGE:
16525         Opcode = X86ISD::FMAX;
16526         break;
16527       }
16528     // Check for x CC y ? y : x -- a min/max with reversed arms.
16529     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16530                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16531       switch (CC) {
16532       default: break;
16533       case ISD::SETOGE:
16534         // Converting this to a min would handle comparisons between positive
16535         // and negative zero incorrectly, and swapping the operands would
16536         // cause it to handle NaNs incorrectly.
16537         if (!DAG.getTarget().Options.UnsafeFPMath &&
16538             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16539           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16540             break;
16541           std::swap(LHS, RHS);
16542         }
16543         Opcode = X86ISD::FMIN;
16544         break;
16545       case ISD::SETUGT:
16546         // Converting this to a min would handle NaNs incorrectly.
16547         if (!DAG.getTarget().Options.UnsafeFPMath &&
16548             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16549           break;
16550         Opcode = X86ISD::FMIN;
16551         break;
16552       case ISD::SETUGE:
16553         // Converting this to a min would handle both negative zeros and NaNs
16554         // incorrectly, but we can swap the operands to fix both.
16555         std::swap(LHS, RHS);
16556       case ISD::SETOGT:
16557       case ISD::SETGT:
16558       case ISD::SETGE:
16559         Opcode = X86ISD::FMIN;
16560         break;
16561
16562       case ISD::SETULT:
16563         // Converting this to a max would handle NaNs incorrectly.
16564         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16565           break;
16566         Opcode = X86ISD::FMAX;
16567         break;
16568       case ISD::SETOLE:
16569         // Converting this to a max would handle comparisons between positive
16570         // and negative zero incorrectly, and swapping the operands would
16571         // cause it to handle NaNs incorrectly.
16572         if (!DAG.getTarget().Options.UnsafeFPMath &&
16573             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16574           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16575             break;
16576           std::swap(LHS, RHS);
16577         }
16578         Opcode = X86ISD::FMAX;
16579         break;
16580       case ISD::SETULE:
16581         // Converting this to a max would handle both negative zeros and NaNs
16582         // incorrectly, but we can swap the operands to fix both.
16583         std::swap(LHS, RHS);
16584       case ISD::SETOLT:
16585       case ISD::SETLT:
16586       case ISD::SETLE:
16587         Opcode = X86ISD::FMAX;
16588         break;
16589       }
16590     }
16591
16592     if (Opcode)
16593       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16594   }
16595
16596   if (Subtarget->hasAVX512() && VT.isVector() &&
16597       Cond.getValueType().getVectorElementType() == MVT::i1) {
16598     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16599     // lowering on AVX-512. In this case we convert it to
16600     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16601     // The same situation for all 128 and 256-bit vectors of i8 and i16
16602     EVT OpVT = LHS.getValueType();
16603     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16604         (OpVT.getVectorElementType() == MVT::i8 ||
16605          OpVT.getVectorElementType() == MVT::i16)) {
16606       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16607       DCI.AddToWorklist(Cond.getNode());
16608       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16609     }
16610   }
16611   // If this is a select between two integer constants, try to do some
16612   // optimizations.
16613   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16614     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16615       // Don't do this for crazy integer types.
16616       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16617         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16618         // so that TrueC (the true value) is larger than FalseC.
16619         bool NeedsCondInvert = false;
16620
16621         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16622             // Efficiently invertible.
16623             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16624              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16625               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16626           NeedsCondInvert = true;
16627           std::swap(TrueC, FalseC);
16628         }
16629
16630         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16631         if (FalseC->getAPIntValue() == 0 &&
16632             TrueC->getAPIntValue().isPowerOf2()) {
16633           if (NeedsCondInvert) // Invert the condition if needed.
16634             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16635                                DAG.getConstant(1, Cond.getValueType()));
16636
16637           // Zero extend the condition if needed.
16638           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16639
16640           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16641           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16642                              DAG.getConstant(ShAmt, MVT::i8));
16643         }
16644
16645         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16646         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16647           if (NeedsCondInvert) // Invert the condition if needed.
16648             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16649                                DAG.getConstant(1, Cond.getValueType()));
16650
16651           // Zero extend the condition if needed.
16652           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16653                              FalseC->getValueType(0), Cond);
16654           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16655                              SDValue(FalseC, 0));
16656         }
16657
16658         // Optimize cases that will turn into an LEA instruction.  This requires
16659         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16660         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16661           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16662           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16663
16664           bool isFastMultiplier = false;
16665           if (Diff < 10) {
16666             switch ((unsigned char)Diff) {
16667               default: break;
16668               case 1:  // result = add base, cond
16669               case 2:  // result = lea base(    , cond*2)
16670               case 3:  // result = lea base(cond, cond*2)
16671               case 4:  // result = lea base(    , cond*4)
16672               case 5:  // result = lea base(cond, cond*4)
16673               case 8:  // result = lea base(    , cond*8)
16674               case 9:  // result = lea base(cond, cond*8)
16675                 isFastMultiplier = true;
16676                 break;
16677             }
16678           }
16679
16680           if (isFastMultiplier) {
16681             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16682             if (NeedsCondInvert) // Invert the condition if needed.
16683               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16684                                  DAG.getConstant(1, Cond.getValueType()));
16685
16686             // Zero extend the condition if needed.
16687             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16688                                Cond);
16689             // Scale the condition by the difference.
16690             if (Diff != 1)
16691               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16692                                  DAG.getConstant(Diff, Cond.getValueType()));
16693
16694             // Add the base if non-zero.
16695             if (FalseC->getAPIntValue() != 0)
16696               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16697                                  SDValue(FalseC, 0));
16698             return Cond;
16699           }
16700         }
16701       }
16702   }
16703
16704   // Canonicalize max and min:
16705   // (x > y) ? x : y -> (x >= y) ? x : y
16706   // (x < y) ? x : y -> (x <= y) ? x : y
16707   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16708   // the need for an extra compare
16709   // against zero. e.g.
16710   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16711   // subl   %esi, %edi
16712   // testl  %edi, %edi
16713   // movl   $0, %eax
16714   // cmovgl %edi, %eax
16715   // =>
16716   // xorl   %eax, %eax
16717   // subl   %esi, $edi
16718   // cmovsl %eax, %edi
16719   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16720       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16721       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16722     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16723     switch (CC) {
16724     default: break;
16725     case ISD::SETLT:
16726     case ISD::SETGT: {
16727       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16728       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16729                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16730       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16731     }
16732     }
16733   }
16734
16735   // Early exit check
16736   if (!TLI.isTypeLegal(VT))
16737     return SDValue();
16738
16739   // Match VSELECTs into subs with unsigned saturation.
16740   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16741       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16742       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16743        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16744     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16745
16746     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16747     // left side invert the predicate to simplify logic below.
16748     SDValue Other;
16749     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16750       Other = RHS;
16751       CC = ISD::getSetCCInverse(CC, true);
16752     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16753       Other = LHS;
16754     }
16755
16756     if (Other.getNode() && Other->getNumOperands() == 2 &&
16757         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16758       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16759       SDValue CondRHS = Cond->getOperand(1);
16760
16761       // Look for a general sub with unsigned saturation first.
16762       // x >= y ? x-y : 0 --> subus x, y
16763       // x >  y ? x-y : 0 --> subus x, y
16764       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16765           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16766         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16767
16768       // If the RHS is a constant we have to reverse the const canonicalization.
16769       // x > C-1 ? x+-C : 0 --> subus x, C
16770       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16771           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16772         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16773         if (CondRHS.getConstantOperandVal(0) == -A-1)
16774           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16775                              DAG.getConstant(-A, VT));
16776       }
16777
16778       // Another special case: If C was a sign bit, the sub has been
16779       // canonicalized into a xor.
16780       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16781       //        it's safe to decanonicalize the xor?
16782       // x s< 0 ? x^C : 0 --> subus x, C
16783       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16784           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16785           isSplatVector(OpRHS.getNode())) {
16786         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16787         if (A.isSignBit())
16788           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16789       }
16790     }
16791   }
16792
16793   // Try to match a min/max vector operation.
16794   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
16795     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
16796     unsigned Opc = ret.first;
16797     bool NeedSplit = ret.second;
16798
16799     if (Opc && NeedSplit) {
16800       unsigned NumElems = VT.getVectorNumElements();
16801       // Extract the LHS vectors
16802       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
16803       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
16804
16805       // Extract the RHS vectors
16806       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
16807       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
16808
16809       // Create min/max for each subvector
16810       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
16811       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
16812
16813       // Merge the result
16814       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
16815     } else if (Opc)
16816       return DAG.getNode(Opc, DL, VT, LHS, RHS);
16817   }
16818
16819   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16820   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16821       // Check if SETCC has already been promoted
16822       TLI.getSetCCResultType(*DAG.getContext(), VT) == Cond.getValueType()) {
16823
16824     assert(Cond.getValueType().isVector() &&
16825            "vector select expects a vector selector!");
16826
16827     EVT IntVT = Cond.getValueType();
16828     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16829     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16830
16831     if (!TValIsAllOnes && !FValIsAllZeros) {
16832       // Try invert the condition if true value is not all 1s and false value
16833       // is not all 0s.
16834       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16835       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16836
16837       if (TValIsAllZeros || FValIsAllOnes) {
16838         SDValue CC = Cond.getOperand(2);
16839         ISD::CondCode NewCC =
16840           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16841                                Cond.getOperand(0).getValueType().isInteger());
16842         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16843         std::swap(LHS, RHS);
16844         TValIsAllOnes = FValIsAllOnes;
16845         FValIsAllZeros = TValIsAllZeros;
16846       }
16847     }
16848
16849     if (TValIsAllOnes || FValIsAllZeros) {
16850       SDValue Ret;
16851
16852       if (TValIsAllOnes && FValIsAllZeros)
16853         Ret = Cond;
16854       else if (TValIsAllOnes)
16855         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16856                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16857       else if (FValIsAllZeros)
16858         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16859                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16860
16861       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16862     }
16863   }
16864
16865   // If we know that this node is legal then we know that it is going to be
16866   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16867   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16868   // to simplify previous instructions.
16869   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16870       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16871     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16872
16873     // Don't optimize vector selects that map to mask-registers.
16874     if (BitWidth == 1)
16875       return SDValue();
16876
16877     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16878     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16879
16880     APInt KnownZero, KnownOne;
16881     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16882                                           DCI.isBeforeLegalizeOps());
16883     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16884         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16885       DCI.CommitTargetLoweringOpt(TLO);
16886   }
16887
16888   return SDValue();
16889 }
16890
16891 // Check whether a boolean test is testing a boolean value generated by
16892 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16893 // code.
16894 //
16895 // Simplify the following patterns:
16896 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16897 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16898 // to (Op EFLAGS Cond)
16899 //
16900 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16901 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16902 // to (Op EFLAGS !Cond)
16903 //
16904 // where Op could be BRCOND or CMOV.
16905 //
16906 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16907   // Quit if not CMP and SUB with its value result used.
16908   if (Cmp.getOpcode() != X86ISD::CMP &&
16909       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16910       return SDValue();
16911
16912   // Quit if not used as a boolean value.
16913   if (CC != X86::COND_E && CC != X86::COND_NE)
16914     return SDValue();
16915
16916   // Check CMP operands. One of them should be 0 or 1 and the other should be
16917   // an SetCC or extended from it.
16918   SDValue Op1 = Cmp.getOperand(0);
16919   SDValue Op2 = Cmp.getOperand(1);
16920
16921   SDValue SetCC;
16922   const ConstantSDNode* C = 0;
16923   bool needOppositeCond = (CC == X86::COND_E);
16924   bool checkAgainstTrue = false; // Is it a comparison against 1?
16925
16926   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16927     SetCC = Op2;
16928   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16929     SetCC = Op1;
16930   else // Quit if all operands are not constants.
16931     return SDValue();
16932
16933   if (C->getZExtValue() == 1) {
16934     needOppositeCond = !needOppositeCond;
16935     checkAgainstTrue = true;
16936   } else if (C->getZExtValue() != 0)
16937     // Quit if the constant is neither 0 or 1.
16938     return SDValue();
16939
16940   bool truncatedToBoolWithAnd = false;
16941   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16942   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16943          SetCC.getOpcode() == ISD::TRUNCATE ||
16944          SetCC.getOpcode() == ISD::AND) {
16945     if (SetCC.getOpcode() == ISD::AND) {
16946       int OpIdx = -1;
16947       ConstantSDNode *CS;
16948       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16949           CS->getZExtValue() == 1)
16950         OpIdx = 1;
16951       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16952           CS->getZExtValue() == 1)
16953         OpIdx = 0;
16954       if (OpIdx == -1)
16955         break;
16956       SetCC = SetCC.getOperand(OpIdx);
16957       truncatedToBoolWithAnd = true;
16958     } else
16959       SetCC = SetCC.getOperand(0);
16960   }
16961
16962   switch (SetCC.getOpcode()) {
16963   case X86ISD::SETCC_CARRY:
16964     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16965     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16966     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16967     // truncated to i1 using 'and'.
16968     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16969       break;
16970     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16971            "Invalid use of SETCC_CARRY!");
16972     // FALL THROUGH
16973   case X86ISD::SETCC:
16974     // Set the condition code or opposite one if necessary.
16975     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16976     if (needOppositeCond)
16977       CC = X86::GetOppositeBranchCondition(CC);
16978     return SetCC.getOperand(1);
16979   case X86ISD::CMOV: {
16980     // Check whether false/true value has canonical one, i.e. 0 or 1.
16981     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16982     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16983     // Quit if true value is not a constant.
16984     if (!TVal)
16985       return SDValue();
16986     // Quit if false value is not a constant.
16987     if (!FVal) {
16988       SDValue Op = SetCC.getOperand(0);
16989       // Skip 'zext' or 'trunc' node.
16990       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16991           Op.getOpcode() == ISD::TRUNCATE)
16992         Op = Op.getOperand(0);
16993       // A special case for rdrand/rdseed, where 0 is set if false cond is
16994       // found.
16995       if ((Op.getOpcode() != X86ISD::RDRAND &&
16996            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16997         return SDValue();
16998     }
16999     // Quit if false value is not the constant 0 or 1.
17000     bool FValIsFalse = true;
17001     if (FVal && FVal->getZExtValue() != 0) {
17002       if (FVal->getZExtValue() != 1)
17003         return SDValue();
17004       // If FVal is 1, opposite cond is needed.
17005       needOppositeCond = !needOppositeCond;
17006       FValIsFalse = false;
17007     }
17008     // Quit if TVal is not the constant opposite of FVal.
17009     if (FValIsFalse && TVal->getZExtValue() != 1)
17010       return SDValue();
17011     if (!FValIsFalse && TVal->getZExtValue() != 0)
17012       return SDValue();
17013     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17014     if (needOppositeCond)
17015       CC = X86::GetOppositeBranchCondition(CC);
17016     return SetCC.getOperand(3);
17017   }
17018   }
17019
17020   return SDValue();
17021 }
17022
17023 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17024 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17025                                   TargetLowering::DAGCombinerInfo &DCI,
17026                                   const X86Subtarget *Subtarget) {
17027   SDLoc DL(N);
17028
17029   // If the flag operand isn't dead, don't touch this CMOV.
17030   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17031     return SDValue();
17032
17033   SDValue FalseOp = N->getOperand(0);
17034   SDValue TrueOp = N->getOperand(1);
17035   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17036   SDValue Cond = N->getOperand(3);
17037
17038   if (CC == X86::COND_E || CC == X86::COND_NE) {
17039     switch (Cond.getOpcode()) {
17040     default: break;
17041     case X86ISD::BSR:
17042     case X86ISD::BSF:
17043       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17044       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17045         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17046     }
17047   }
17048
17049   SDValue Flags;
17050
17051   Flags = checkBoolTestSetCCCombine(Cond, CC);
17052   if (Flags.getNode() &&
17053       // Extra check as FCMOV only supports a subset of X86 cond.
17054       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17055     SDValue Ops[] = { FalseOp, TrueOp,
17056                       DAG.getConstant(CC, MVT::i8), Flags };
17057     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17058                        Ops, array_lengthof(Ops));
17059   }
17060
17061   // If this is a select between two integer constants, try to do some
17062   // optimizations.  Note that the operands are ordered the opposite of SELECT
17063   // operands.
17064   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17065     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17066       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17067       // larger than FalseC (the false value).
17068       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17069         CC = X86::GetOppositeBranchCondition(CC);
17070         std::swap(TrueC, FalseC);
17071         std::swap(TrueOp, FalseOp);
17072       }
17073
17074       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17075       // This is efficient for any integer data type (including i8/i16) and
17076       // shift amount.
17077       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17078         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17079                            DAG.getConstant(CC, MVT::i8), Cond);
17080
17081         // Zero extend the condition if needed.
17082         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17083
17084         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17085         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17086                            DAG.getConstant(ShAmt, MVT::i8));
17087         if (N->getNumValues() == 2)  // Dead flag value?
17088           return DCI.CombineTo(N, Cond, SDValue());
17089         return Cond;
17090       }
17091
17092       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17093       // for any integer data type, including i8/i16.
17094       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17095         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17096                            DAG.getConstant(CC, MVT::i8), Cond);
17097
17098         // Zero extend the condition if needed.
17099         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17100                            FalseC->getValueType(0), Cond);
17101         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17102                            SDValue(FalseC, 0));
17103
17104         if (N->getNumValues() == 2)  // Dead flag value?
17105           return DCI.CombineTo(N, Cond, SDValue());
17106         return Cond;
17107       }
17108
17109       // Optimize cases that will turn into an LEA instruction.  This requires
17110       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17111       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17112         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17113         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17114
17115         bool isFastMultiplier = false;
17116         if (Diff < 10) {
17117           switch ((unsigned char)Diff) {
17118           default: break;
17119           case 1:  // result = add base, cond
17120           case 2:  // result = lea base(    , cond*2)
17121           case 3:  // result = lea base(cond, cond*2)
17122           case 4:  // result = lea base(    , cond*4)
17123           case 5:  // result = lea base(cond, cond*4)
17124           case 8:  // result = lea base(    , cond*8)
17125           case 9:  // result = lea base(cond, cond*8)
17126             isFastMultiplier = true;
17127             break;
17128           }
17129         }
17130
17131         if (isFastMultiplier) {
17132           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17133           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17134                              DAG.getConstant(CC, MVT::i8), Cond);
17135           // Zero extend the condition if needed.
17136           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17137                              Cond);
17138           // Scale the condition by the difference.
17139           if (Diff != 1)
17140             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17141                                DAG.getConstant(Diff, Cond.getValueType()));
17142
17143           // Add the base if non-zero.
17144           if (FalseC->getAPIntValue() != 0)
17145             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17146                                SDValue(FalseC, 0));
17147           if (N->getNumValues() == 2)  // Dead flag value?
17148             return DCI.CombineTo(N, Cond, SDValue());
17149           return Cond;
17150         }
17151       }
17152     }
17153   }
17154
17155   // Handle these cases:
17156   //   (select (x != c), e, c) -> select (x != c), e, x),
17157   //   (select (x == c), c, e) -> select (x == c), x, e)
17158   // where the c is an integer constant, and the "select" is the combination
17159   // of CMOV and CMP.
17160   //
17161   // The rationale for this change is that the conditional-move from a constant
17162   // needs two instructions, however, conditional-move from a register needs
17163   // only one instruction.
17164   //
17165   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17166   //  some instruction-combining opportunities. This opt needs to be
17167   //  postponed as late as possible.
17168   //
17169   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17170     // the DCI.xxxx conditions are provided to postpone the optimization as
17171     // late as possible.
17172
17173     ConstantSDNode *CmpAgainst = 0;
17174     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17175         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17176         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17177
17178       if (CC == X86::COND_NE &&
17179           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17180         CC = X86::GetOppositeBranchCondition(CC);
17181         std::swap(TrueOp, FalseOp);
17182       }
17183
17184       if (CC == X86::COND_E &&
17185           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17186         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17187                           DAG.getConstant(CC, MVT::i8), Cond };
17188         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17189                            array_lengthof(Ops));
17190       }
17191     }
17192   }
17193
17194   return SDValue();
17195 }
17196
17197 /// PerformMulCombine - Optimize a single multiply with constant into two
17198 /// in order to implement it with two cheaper instructions, e.g.
17199 /// LEA + SHL, LEA + LEA.
17200 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17201                                  TargetLowering::DAGCombinerInfo &DCI) {
17202   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17203     return SDValue();
17204
17205   EVT VT = N->getValueType(0);
17206   if (VT != MVT::i64)
17207     return SDValue();
17208
17209   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17210   if (!C)
17211     return SDValue();
17212   uint64_t MulAmt = C->getZExtValue();
17213   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17214     return SDValue();
17215
17216   uint64_t MulAmt1 = 0;
17217   uint64_t MulAmt2 = 0;
17218   if ((MulAmt % 9) == 0) {
17219     MulAmt1 = 9;
17220     MulAmt2 = MulAmt / 9;
17221   } else if ((MulAmt % 5) == 0) {
17222     MulAmt1 = 5;
17223     MulAmt2 = MulAmt / 5;
17224   } else if ((MulAmt % 3) == 0) {
17225     MulAmt1 = 3;
17226     MulAmt2 = MulAmt / 3;
17227   }
17228   if (MulAmt2 &&
17229       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17230     SDLoc DL(N);
17231
17232     if (isPowerOf2_64(MulAmt2) &&
17233         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17234       // If second multiplifer is pow2, issue it first. We want the multiply by
17235       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17236       // is an add.
17237       std::swap(MulAmt1, MulAmt2);
17238
17239     SDValue NewMul;
17240     if (isPowerOf2_64(MulAmt1))
17241       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17242                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17243     else
17244       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17245                            DAG.getConstant(MulAmt1, VT));
17246
17247     if (isPowerOf2_64(MulAmt2))
17248       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17249                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17250     else
17251       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17252                            DAG.getConstant(MulAmt2, VT));
17253
17254     // Do not add new nodes to DAG combiner worklist.
17255     DCI.CombineTo(N, NewMul, false);
17256   }
17257   return SDValue();
17258 }
17259
17260 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17261   SDValue N0 = N->getOperand(0);
17262   SDValue N1 = N->getOperand(1);
17263   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17264   EVT VT = N0.getValueType();
17265
17266   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17267   // since the result of setcc_c is all zero's or all ones.
17268   if (VT.isInteger() && !VT.isVector() &&
17269       N1C && N0.getOpcode() == ISD::AND &&
17270       N0.getOperand(1).getOpcode() == ISD::Constant) {
17271     SDValue N00 = N0.getOperand(0);
17272     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17273         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17274           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17275          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17276       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17277       APInt ShAmt = N1C->getAPIntValue();
17278       Mask = Mask.shl(ShAmt);
17279       if (Mask != 0)
17280         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17281                            N00, DAG.getConstant(Mask, VT));
17282     }
17283   }
17284
17285   // Hardware support for vector shifts is sparse which makes us scalarize the
17286   // vector operations in many cases. Also, on sandybridge ADD is faster than
17287   // shl.
17288   // (shl V, 1) -> add V,V
17289   if (isSplatVector(N1.getNode())) {
17290     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17291     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17292     // We shift all of the values by one. In many cases we do not have
17293     // hardware support for this operation. This is better expressed as an ADD
17294     // of two values.
17295     if (N1C && (1 == N1C->getZExtValue())) {
17296       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17297     }
17298   }
17299
17300   return SDValue();
17301 }
17302
17303 /// \brief Returns a vector of 0s if the node in input is a vector logical
17304 /// shift by a constant amount which is known to be bigger than or equal 
17305 /// to the vector element size in bits.
17306 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17307                                       const X86Subtarget *Subtarget) {
17308   EVT VT = N->getValueType(0);
17309
17310   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17311       (!Subtarget->hasInt256() ||
17312        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17313     return SDValue();
17314
17315   SDValue Amt = N->getOperand(1);
17316   SDLoc DL(N);
17317   if (isSplatVector(Amt.getNode())) {
17318     SDValue SclrAmt = Amt->getOperand(0);
17319     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17320       APInt ShiftAmt = C->getAPIntValue();
17321       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17322
17323       // SSE2/AVX2 logical shifts always return a vector of 0s
17324       // if the shift amount is bigger than or equal to 
17325       // the element size. The constant shift amount will be
17326       // encoded as a 8-bit immediate.
17327       if (ShiftAmt.trunc(8).uge(MaxAmount))
17328         return getZeroVector(VT, Subtarget, DAG, DL);
17329     }
17330   }
17331
17332   return SDValue();
17333 }
17334
17335 /// PerformShiftCombine - Combine shifts.
17336 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17337                                    TargetLowering::DAGCombinerInfo &DCI,
17338                                    const X86Subtarget *Subtarget) {
17339   if (N->getOpcode() == ISD::SHL) {
17340     SDValue V = PerformSHLCombine(N, DAG);
17341     if (V.getNode()) return V;
17342   }
17343
17344   if (N->getOpcode() != ISD::SRA) {
17345     // Try to fold this logical shift into a zero vector.
17346     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17347     if (V.getNode()) return V;
17348   }
17349
17350   return SDValue();
17351 }
17352
17353 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17354 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17355 // and friends.  Likewise for OR -> CMPNEQSS.
17356 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17357                             TargetLowering::DAGCombinerInfo &DCI,
17358                             const X86Subtarget *Subtarget) {
17359   unsigned opcode;
17360
17361   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17362   // we're requiring SSE2 for both.
17363   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17364     SDValue N0 = N->getOperand(0);
17365     SDValue N1 = N->getOperand(1);
17366     SDValue CMP0 = N0->getOperand(1);
17367     SDValue CMP1 = N1->getOperand(1);
17368     SDLoc DL(N);
17369
17370     // The SETCCs should both refer to the same CMP.
17371     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17372       return SDValue();
17373
17374     SDValue CMP00 = CMP0->getOperand(0);
17375     SDValue CMP01 = CMP0->getOperand(1);
17376     EVT     VT    = CMP00.getValueType();
17377
17378     if (VT == MVT::f32 || VT == MVT::f64) {
17379       bool ExpectingFlags = false;
17380       // Check for any users that want flags:
17381       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17382            !ExpectingFlags && UI != UE; ++UI)
17383         switch (UI->getOpcode()) {
17384         default:
17385         case ISD::BR_CC:
17386         case ISD::BRCOND:
17387         case ISD::SELECT:
17388           ExpectingFlags = true;
17389           break;
17390         case ISD::CopyToReg:
17391         case ISD::SIGN_EXTEND:
17392         case ISD::ZERO_EXTEND:
17393         case ISD::ANY_EXTEND:
17394           break;
17395         }
17396
17397       if (!ExpectingFlags) {
17398         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17399         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17400
17401         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17402           X86::CondCode tmp = cc0;
17403           cc0 = cc1;
17404           cc1 = tmp;
17405         }
17406
17407         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17408             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17409           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17410           X86ISD::NodeType NTOperator = is64BitFP ?
17411             X86ISD::FSETCCsd : X86ISD::FSETCCss;
17412           // FIXME: need symbolic constants for these magic numbers.
17413           // See X86ATTInstPrinter.cpp:printSSECC().
17414           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17415           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
17416                                               DAG.getConstant(x86cc, MVT::i8));
17417           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
17418                                               OnesOrZeroesF);
17419           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
17420                                       DAG.getConstant(1, MVT::i32));
17421           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17422           return OneBitOfTruth;
17423         }
17424       }
17425     }
17426   }
17427   return SDValue();
17428 }
17429
17430 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17431 /// so it can be folded inside ANDNP.
17432 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17433   EVT VT = N->getValueType(0);
17434
17435   // Match direct AllOnes for 128 and 256-bit vectors
17436   if (ISD::isBuildVectorAllOnes(N))
17437     return true;
17438
17439   // Look through a bit convert.
17440   if (N->getOpcode() == ISD::BITCAST)
17441     N = N->getOperand(0).getNode();
17442
17443   // Sometimes the operand may come from a insert_subvector building a 256-bit
17444   // allones vector
17445   if (VT.is256BitVector() &&
17446       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17447     SDValue V1 = N->getOperand(0);
17448     SDValue V2 = N->getOperand(1);
17449
17450     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17451         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17452         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17453         ISD::isBuildVectorAllOnes(V2.getNode()))
17454       return true;
17455   }
17456
17457   return false;
17458 }
17459
17460 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17461 // register. In most cases we actually compare or select YMM-sized registers
17462 // and mixing the two types creates horrible code. This method optimizes
17463 // some of the transition sequences.
17464 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17465                                  TargetLowering::DAGCombinerInfo &DCI,
17466                                  const X86Subtarget *Subtarget) {
17467   EVT VT = N->getValueType(0);
17468   if (!VT.is256BitVector())
17469     return SDValue();
17470
17471   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17472           N->getOpcode() == ISD::ZERO_EXTEND ||
17473           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17474
17475   SDValue Narrow = N->getOperand(0);
17476   EVT NarrowVT = Narrow->getValueType(0);
17477   if (!NarrowVT.is128BitVector())
17478     return SDValue();
17479
17480   if (Narrow->getOpcode() != ISD::XOR &&
17481       Narrow->getOpcode() != ISD::AND &&
17482       Narrow->getOpcode() != ISD::OR)
17483     return SDValue();
17484
17485   SDValue N0  = Narrow->getOperand(0);
17486   SDValue N1  = Narrow->getOperand(1);
17487   SDLoc DL(Narrow);
17488
17489   // The Left side has to be a trunc.
17490   if (N0.getOpcode() != ISD::TRUNCATE)
17491     return SDValue();
17492
17493   // The type of the truncated inputs.
17494   EVT WideVT = N0->getOperand(0)->getValueType(0);
17495   if (WideVT != VT)
17496     return SDValue();
17497
17498   // The right side has to be a 'trunc' or a constant vector.
17499   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17500   bool RHSConst = (isSplatVector(N1.getNode()) &&
17501                    isa<ConstantSDNode>(N1->getOperand(0)));
17502   if (!RHSTrunc && !RHSConst)
17503     return SDValue();
17504
17505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17506
17507   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17508     return SDValue();
17509
17510   // Set N0 and N1 to hold the inputs to the new wide operation.
17511   N0 = N0->getOperand(0);
17512   if (RHSConst) {
17513     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17514                      N1->getOperand(0));
17515     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17516     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17517   } else if (RHSTrunc) {
17518     N1 = N1->getOperand(0);
17519   }
17520
17521   // Generate the wide operation.
17522   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17523   unsigned Opcode = N->getOpcode();
17524   switch (Opcode) {
17525   case ISD::ANY_EXTEND:
17526     return Op;
17527   case ISD::ZERO_EXTEND: {
17528     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17529     APInt Mask = APInt::getAllOnesValue(InBits);
17530     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17531     return DAG.getNode(ISD::AND, DL, VT,
17532                        Op, DAG.getConstant(Mask, VT));
17533   }
17534   case ISD::SIGN_EXTEND:
17535     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17536                        Op, DAG.getValueType(NarrowVT));
17537   default:
17538     llvm_unreachable("Unexpected opcode");
17539   }
17540 }
17541
17542 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17543                                  TargetLowering::DAGCombinerInfo &DCI,
17544                                  const X86Subtarget *Subtarget) {
17545   EVT VT = N->getValueType(0);
17546   if (DCI.isBeforeLegalizeOps())
17547     return SDValue();
17548
17549   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17550   if (R.getNode())
17551     return R;
17552
17553   // Create BLSI, BLSR, and BZHI instructions
17554   // BLSI is X & (-X)
17555   // BLSR is X & (X-1)
17556   // BZHI is X & ((1 << Y) - 1)
17557   // BEXTR is ((X >> imm) & (2**size-1))
17558   if (VT == MVT::i32 || VT == MVT::i64) {
17559     SDValue N0 = N->getOperand(0);
17560     SDValue N1 = N->getOperand(1);
17561     SDLoc DL(N);
17562
17563     if (Subtarget->hasBMI()) {
17564       // Check LHS for neg
17565       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17566           isZero(N0.getOperand(0)))
17567         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17568
17569       // Check RHS for neg
17570       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17571           isZero(N1.getOperand(0)))
17572         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17573
17574       // Check LHS for X-1
17575       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17576           isAllOnes(N0.getOperand(1)))
17577         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17578
17579       // Check RHS for X-1
17580       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17581           isAllOnes(N1.getOperand(1)))
17582         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17583
17584       // Check for BEXTR
17585       if (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL) {
17586         ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17587         ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17588         if (MaskNode && ShiftNode) {
17589           uint64_t Mask = MaskNode->getZExtValue();
17590           uint64_t Shift = ShiftNode->getZExtValue();
17591           if (isMask_64(Mask)) {
17592             uint64_t MaskSize = CountPopulation_64(Mask);
17593             if (Shift + MaskSize <= VT.getSizeInBits())
17594               return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17595                                  DAG.getConstant(Shift | (MaskSize << 8), VT));
17596           }
17597         }
17598       }
17599     }
17600
17601     if (Subtarget->hasBMI2()) {
17602       // Check for (and (add (shl 1, Y), -1), X)
17603       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17604         SDValue N00 = N0.getOperand(0);
17605         if (N00.getOpcode() == ISD::SHL) {
17606           SDValue N001 = N00.getOperand(1);
17607           assert(N001.getValueType() == MVT::i8 && "unexpected type");
17608           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17609           if (C && C->getZExtValue() == 1)
17610             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17611         }
17612       }
17613
17614       // Check for (and X, (add (shl 1, Y), -1))
17615       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17616         SDValue N10 = N1.getOperand(0);
17617         if (N10.getOpcode() == ISD::SHL) {
17618           SDValue N101 = N10.getOperand(1);
17619           assert(N101.getValueType() == MVT::i8 && "unexpected type");
17620           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17621           if (C && C->getZExtValue() == 1)
17622             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17623         }
17624       }
17625     }
17626
17627     return SDValue();
17628   }
17629
17630   // Want to form ANDNP nodes:
17631   // 1) In the hopes of then easily combining them with OR and AND nodes
17632   //    to form PBLEND/PSIGN.
17633   // 2) To match ANDN packed intrinsics
17634   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17635     return SDValue();
17636
17637   SDValue N0 = N->getOperand(0);
17638   SDValue N1 = N->getOperand(1);
17639   SDLoc DL(N);
17640
17641   // Check LHS for vnot
17642   if (N0.getOpcode() == ISD::XOR &&
17643       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17644       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17645     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17646
17647   // Check RHS for vnot
17648   if (N1.getOpcode() == ISD::XOR &&
17649       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17650       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17651     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17652
17653   return SDValue();
17654 }
17655
17656 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17657                                 TargetLowering::DAGCombinerInfo &DCI,
17658                                 const X86Subtarget *Subtarget) {
17659   EVT VT = N->getValueType(0);
17660   if (DCI.isBeforeLegalizeOps())
17661     return SDValue();
17662
17663   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17664   if (R.getNode())
17665     return R;
17666
17667   SDValue N0 = N->getOperand(0);
17668   SDValue N1 = N->getOperand(1);
17669
17670   // look for psign/blend
17671   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17672     if (!Subtarget->hasSSSE3() ||
17673         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17674       return SDValue();
17675
17676     // Canonicalize pandn to RHS
17677     if (N0.getOpcode() == X86ISD::ANDNP)
17678       std::swap(N0, N1);
17679     // or (and (m, y), (pandn m, x))
17680     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17681       SDValue Mask = N1.getOperand(0);
17682       SDValue X    = N1.getOperand(1);
17683       SDValue Y;
17684       if (N0.getOperand(0) == Mask)
17685         Y = N0.getOperand(1);
17686       if (N0.getOperand(1) == Mask)
17687         Y = N0.getOperand(0);
17688
17689       // Check to see if the mask appeared in both the AND and ANDNP and
17690       if (!Y.getNode())
17691         return SDValue();
17692
17693       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17694       // Look through mask bitcast.
17695       if (Mask.getOpcode() == ISD::BITCAST)
17696         Mask = Mask.getOperand(0);
17697       if (X.getOpcode() == ISD::BITCAST)
17698         X = X.getOperand(0);
17699       if (Y.getOpcode() == ISD::BITCAST)
17700         Y = Y.getOperand(0);
17701
17702       EVT MaskVT = Mask.getValueType();
17703
17704       // Validate that the Mask operand is a vector sra node.
17705       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17706       // there is no psrai.b
17707       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17708       unsigned SraAmt = ~0;
17709       if (Mask.getOpcode() == ISD::SRA) {
17710         SDValue Amt = Mask.getOperand(1);
17711         if (isSplatVector(Amt.getNode())) {
17712           SDValue SclrAmt = Amt->getOperand(0);
17713           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17714             SraAmt = C->getZExtValue();
17715         }
17716       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17717         SDValue SraC = Mask.getOperand(1);
17718         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17719       }
17720       if ((SraAmt + 1) != EltBits)
17721         return SDValue();
17722
17723       SDLoc DL(N);
17724
17725       // Now we know we at least have a plendvb with the mask val.  See if
17726       // we can form a psignb/w/d.
17727       // psign = x.type == y.type == mask.type && y = sub(0, x);
17728       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17729           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17730           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17731         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17732                "Unsupported VT for PSIGN");
17733         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17734         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17735       }
17736       // PBLENDVB only available on SSE 4.1
17737       if (!Subtarget->hasSSE41())
17738         return SDValue();
17739
17740       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17741
17742       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17743       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17744       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17745       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17746       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17747     }
17748   }
17749
17750   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17751     return SDValue();
17752
17753   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17754   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17755     std::swap(N0, N1);
17756   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17757     return SDValue();
17758   if (!N0.hasOneUse() || !N1.hasOneUse())
17759     return SDValue();
17760
17761   SDValue ShAmt0 = N0.getOperand(1);
17762   if (ShAmt0.getValueType() != MVT::i8)
17763     return SDValue();
17764   SDValue ShAmt1 = N1.getOperand(1);
17765   if (ShAmt1.getValueType() != MVT::i8)
17766     return SDValue();
17767   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17768     ShAmt0 = ShAmt0.getOperand(0);
17769   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17770     ShAmt1 = ShAmt1.getOperand(0);
17771
17772   SDLoc DL(N);
17773   unsigned Opc = X86ISD::SHLD;
17774   SDValue Op0 = N0.getOperand(0);
17775   SDValue Op1 = N1.getOperand(0);
17776   if (ShAmt0.getOpcode() == ISD::SUB) {
17777     Opc = X86ISD::SHRD;
17778     std::swap(Op0, Op1);
17779     std::swap(ShAmt0, ShAmt1);
17780   }
17781
17782   unsigned Bits = VT.getSizeInBits();
17783   if (ShAmt1.getOpcode() == ISD::SUB) {
17784     SDValue Sum = ShAmt1.getOperand(0);
17785     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17786       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17787       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17788         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17789       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17790         return DAG.getNode(Opc, DL, VT,
17791                            Op0, Op1,
17792                            DAG.getNode(ISD::TRUNCATE, DL,
17793                                        MVT::i8, ShAmt0));
17794     }
17795   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17796     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17797     if (ShAmt0C &&
17798         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17799       return DAG.getNode(Opc, DL, VT,
17800                          N0.getOperand(0), N1.getOperand(0),
17801                          DAG.getNode(ISD::TRUNCATE, DL,
17802                                        MVT::i8, ShAmt0));
17803   }
17804
17805   return SDValue();
17806 }
17807
17808 // Generate NEG and CMOV for integer abs.
17809 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17810   EVT VT = N->getValueType(0);
17811
17812   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17813   // 8-bit integer abs to NEG and CMOV.
17814   if (VT.isInteger() && VT.getSizeInBits() == 8)
17815     return SDValue();
17816
17817   SDValue N0 = N->getOperand(0);
17818   SDValue N1 = N->getOperand(1);
17819   SDLoc DL(N);
17820
17821   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17822   // and change it to SUB and CMOV.
17823   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17824       N0.getOpcode() == ISD::ADD &&
17825       N0.getOperand(1) == N1 &&
17826       N1.getOpcode() == ISD::SRA &&
17827       N1.getOperand(0) == N0.getOperand(0))
17828     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17829       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17830         // Generate SUB & CMOV.
17831         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17832                                   DAG.getConstant(0, VT), N0.getOperand(0));
17833
17834         SDValue Ops[] = { N0.getOperand(0), Neg,
17835                           DAG.getConstant(X86::COND_GE, MVT::i8),
17836                           SDValue(Neg.getNode(), 1) };
17837         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17838                            Ops, array_lengthof(Ops));
17839       }
17840   return SDValue();
17841 }
17842
17843 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17844 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17845                                  TargetLowering::DAGCombinerInfo &DCI,
17846                                  const X86Subtarget *Subtarget) {
17847   EVT VT = N->getValueType(0);
17848   if (DCI.isBeforeLegalizeOps())
17849     return SDValue();
17850
17851   if (Subtarget->hasCMov()) {
17852     SDValue RV = performIntegerAbsCombine(N, DAG);
17853     if (RV.getNode())
17854       return RV;
17855   }
17856
17857   // Try forming BMI if it is available.
17858   if (!Subtarget->hasBMI())
17859     return SDValue();
17860
17861   if (VT != MVT::i32 && VT != MVT::i64)
17862     return SDValue();
17863
17864   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17865
17866   // Create BLSMSK instructions by finding X ^ (X-1)
17867   SDValue N0 = N->getOperand(0);
17868   SDValue N1 = N->getOperand(1);
17869   SDLoc DL(N);
17870
17871   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17872       isAllOnes(N0.getOperand(1)))
17873     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17874
17875   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17876       isAllOnes(N1.getOperand(1)))
17877     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17878
17879   return SDValue();
17880 }
17881
17882 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17883 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17884                                   TargetLowering::DAGCombinerInfo &DCI,
17885                                   const X86Subtarget *Subtarget) {
17886   LoadSDNode *Ld = cast<LoadSDNode>(N);
17887   EVT RegVT = Ld->getValueType(0);
17888   EVT MemVT = Ld->getMemoryVT();
17889   SDLoc dl(Ld);
17890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17891   unsigned RegSz = RegVT.getSizeInBits();
17892
17893   // On Sandybridge unaligned 256bit loads are inefficient.
17894   ISD::LoadExtType Ext = Ld->getExtensionType();
17895   unsigned Alignment = Ld->getAlignment();
17896   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17897   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17898       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17899     unsigned NumElems = RegVT.getVectorNumElements();
17900     if (NumElems < 2)
17901       return SDValue();
17902
17903     SDValue Ptr = Ld->getBasePtr();
17904     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17905
17906     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17907                                   NumElems/2);
17908     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17909                                 Ld->getPointerInfo(), Ld->isVolatile(),
17910                                 Ld->isNonTemporal(), Ld->isInvariant(),
17911                                 Alignment);
17912     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17913     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17914                                 Ld->getPointerInfo(), Ld->isVolatile(),
17915                                 Ld->isNonTemporal(), Ld->isInvariant(),
17916                                 std::min(16U, Alignment));
17917     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17918                              Load1.getValue(1),
17919                              Load2.getValue(1));
17920
17921     SDValue NewVec = DAG.getUNDEF(RegVT);
17922     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17923     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17924     return DCI.CombineTo(N, NewVec, TF, true);
17925   }
17926
17927   // If this is a vector EXT Load then attempt to optimize it using a
17928   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17929   // expansion is still better than scalar code.
17930   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17931   // emit a shuffle and a arithmetic shift.
17932   // TODO: It is possible to support ZExt by zeroing the undef values
17933   // during the shuffle phase or after the shuffle.
17934   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17935       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17936     assert(MemVT != RegVT && "Cannot extend to the same type");
17937     assert(MemVT.isVector() && "Must load a vector from memory");
17938
17939     unsigned NumElems = RegVT.getVectorNumElements();
17940     unsigned MemSz = MemVT.getSizeInBits();
17941     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17942
17943     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17944       return SDValue();
17945
17946     // All sizes must be a power of two.
17947     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17948       return SDValue();
17949
17950     // Attempt to load the original value using scalar loads.
17951     // Find the largest scalar type that divides the total loaded size.
17952     MVT SclrLoadTy = MVT::i8;
17953     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17954          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17955       MVT Tp = (MVT::SimpleValueType)tp;
17956       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17957         SclrLoadTy = Tp;
17958       }
17959     }
17960
17961     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17962     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17963         (64 <= MemSz))
17964       SclrLoadTy = MVT::f64;
17965
17966     // Calculate the number of scalar loads that we need to perform
17967     // in order to load our vector from memory.
17968     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17969     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17970       return SDValue();
17971
17972     unsigned loadRegZize = RegSz;
17973     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17974       loadRegZize /= 2;
17975
17976     // Represent our vector as a sequence of elements which are the
17977     // largest scalar that we can load.
17978     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17979       loadRegZize/SclrLoadTy.getSizeInBits());
17980
17981     // Represent the data using the same element type that is stored in
17982     // memory. In practice, we ''widen'' MemVT.
17983     EVT WideVecVT =
17984           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17985                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17986
17987     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17988       "Invalid vector type");
17989
17990     // We can't shuffle using an illegal type.
17991     if (!TLI.isTypeLegal(WideVecVT))
17992       return SDValue();
17993
17994     SmallVector<SDValue, 8> Chains;
17995     SDValue Ptr = Ld->getBasePtr();
17996     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17997                                         TLI.getPointerTy());
17998     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17999
18000     for (unsigned i = 0; i < NumLoads; ++i) {
18001       // Perform a single load.
18002       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18003                                        Ptr, Ld->getPointerInfo(),
18004                                        Ld->isVolatile(), Ld->isNonTemporal(),
18005                                        Ld->isInvariant(), Ld->getAlignment());
18006       Chains.push_back(ScalarLoad.getValue(1));
18007       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18008       // another round of DAGCombining.
18009       if (i == 0)
18010         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18011       else
18012         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18013                           ScalarLoad, DAG.getIntPtrConstant(i));
18014
18015       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18016     }
18017
18018     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18019                                Chains.size());
18020
18021     // Bitcast the loaded value to a vector of the original element type, in
18022     // the size of the target vector type.
18023     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18024     unsigned SizeRatio = RegSz/MemSz;
18025
18026     if (Ext == ISD::SEXTLOAD) {
18027       // If we have SSE4.1 we can directly emit a VSEXT node.
18028       if (Subtarget->hasSSE41()) {
18029         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18030         return DCI.CombineTo(N, Sext, TF, true);
18031       }
18032
18033       // Otherwise we'll shuffle the small elements in the high bits of the
18034       // larger type and perform an arithmetic shift. If the shift is not legal
18035       // it's better to scalarize.
18036       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18037         return SDValue();
18038
18039       // Redistribute the loaded elements into the different locations.
18040       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18041       for (unsigned i = 0; i != NumElems; ++i)
18042         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18043
18044       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18045                                            DAG.getUNDEF(WideVecVT),
18046                                            &ShuffleVec[0]);
18047
18048       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18049
18050       // Build the arithmetic shift.
18051       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18052                      MemVT.getVectorElementType().getSizeInBits();
18053       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18054                           DAG.getConstant(Amt, RegVT));
18055
18056       return DCI.CombineTo(N, Shuff, TF, true);
18057     }
18058
18059     // Redistribute the loaded elements into the different locations.
18060     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18061     for (unsigned i = 0; i != NumElems; ++i)
18062       ShuffleVec[i*SizeRatio] = i;
18063
18064     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18065                                          DAG.getUNDEF(WideVecVT),
18066                                          &ShuffleVec[0]);
18067
18068     // Bitcast to the requested type.
18069     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18070     // Replace the original load with the new sequence
18071     // and return the new chain.
18072     return DCI.CombineTo(N, Shuff, TF, true);
18073   }
18074
18075   return SDValue();
18076 }
18077
18078 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18079 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18080                                    const X86Subtarget *Subtarget) {
18081   StoreSDNode *St = cast<StoreSDNode>(N);
18082   EVT VT = St->getValue().getValueType();
18083   EVT StVT = St->getMemoryVT();
18084   SDLoc dl(St);
18085   SDValue StoredVal = St->getOperand(1);
18086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18087
18088   // If we are saving a concatenation of two XMM registers, perform two stores.
18089   // On Sandy Bridge, 256-bit memory operations are executed by two
18090   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18091   // memory  operation.
18092   unsigned Alignment = St->getAlignment();
18093   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18094   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18095       StVT == VT && !IsAligned) {
18096     unsigned NumElems = VT.getVectorNumElements();
18097     if (NumElems < 2)
18098       return SDValue();
18099
18100     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18101     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18102
18103     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18104     SDValue Ptr0 = St->getBasePtr();
18105     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18106
18107     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18108                                 St->getPointerInfo(), St->isVolatile(),
18109                                 St->isNonTemporal(), Alignment);
18110     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18111                                 St->getPointerInfo(), St->isVolatile(),
18112                                 St->isNonTemporal(),
18113                                 std::min(16U, Alignment));
18114     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18115   }
18116
18117   // Optimize trunc store (of multiple scalars) to shuffle and store.
18118   // First, pack all of the elements in one place. Next, store to memory
18119   // in fewer chunks.
18120   if (St->isTruncatingStore() && VT.isVector()) {
18121     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18122     unsigned NumElems = VT.getVectorNumElements();
18123     assert(StVT != VT && "Cannot truncate to the same type");
18124     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18125     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18126
18127     // From, To sizes and ElemCount must be pow of two
18128     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18129     // We are going to use the original vector elt for storing.
18130     // Accumulated smaller vector elements must be a multiple of the store size.
18131     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18132
18133     unsigned SizeRatio  = FromSz / ToSz;
18134
18135     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18136
18137     // Create a type on which we perform the shuffle
18138     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18139             StVT.getScalarType(), NumElems*SizeRatio);
18140
18141     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18142
18143     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18144     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18145     for (unsigned i = 0; i != NumElems; ++i)
18146       ShuffleVec[i] = i * SizeRatio;
18147
18148     // Can't shuffle using an illegal type.
18149     if (!TLI.isTypeLegal(WideVecVT))
18150       return SDValue();
18151
18152     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18153                                          DAG.getUNDEF(WideVecVT),
18154                                          &ShuffleVec[0]);
18155     // At this point all of the data is stored at the bottom of the
18156     // register. We now need to save it to mem.
18157
18158     // Find the largest store unit
18159     MVT StoreType = MVT::i8;
18160     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18161          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18162       MVT Tp = (MVT::SimpleValueType)tp;
18163       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18164         StoreType = Tp;
18165     }
18166
18167     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18168     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18169         (64 <= NumElems * ToSz))
18170       StoreType = MVT::f64;
18171
18172     // Bitcast the original vector into a vector of store-size units
18173     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18174             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18175     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18176     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18177     SmallVector<SDValue, 8> Chains;
18178     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18179                                         TLI.getPointerTy());
18180     SDValue Ptr = St->getBasePtr();
18181
18182     // Perform one or more big stores into memory.
18183     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18184       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18185                                    StoreType, ShuffWide,
18186                                    DAG.getIntPtrConstant(i));
18187       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18188                                 St->getPointerInfo(), St->isVolatile(),
18189                                 St->isNonTemporal(), St->getAlignment());
18190       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18191       Chains.push_back(Ch);
18192     }
18193
18194     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18195                                Chains.size());
18196   }
18197
18198   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18199   // the FP state in cases where an emms may be missing.
18200   // A preferable solution to the general problem is to figure out the right
18201   // places to insert EMMS.  This qualifies as a quick hack.
18202
18203   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18204   if (VT.getSizeInBits() != 64)
18205     return SDValue();
18206
18207   const Function *F = DAG.getMachineFunction().getFunction();
18208   bool NoImplicitFloatOps = F->getAttributes().
18209     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18210   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18211                      && Subtarget->hasSSE2();
18212   if ((VT.isVector() ||
18213        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18214       isa<LoadSDNode>(St->getValue()) &&
18215       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18216       St->getChain().hasOneUse() && !St->isVolatile()) {
18217     SDNode* LdVal = St->getValue().getNode();
18218     LoadSDNode *Ld = 0;
18219     int TokenFactorIndex = -1;
18220     SmallVector<SDValue, 8> Ops;
18221     SDNode* ChainVal = St->getChain().getNode();
18222     // Must be a store of a load.  We currently handle two cases:  the load
18223     // is a direct child, and it's under an intervening TokenFactor.  It is
18224     // possible to dig deeper under nested TokenFactors.
18225     if (ChainVal == LdVal)
18226       Ld = cast<LoadSDNode>(St->getChain());
18227     else if (St->getValue().hasOneUse() &&
18228              ChainVal->getOpcode() == ISD::TokenFactor) {
18229       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18230         if (ChainVal->getOperand(i).getNode() == LdVal) {
18231           TokenFactorIndex = i;
18232           Ld = cast<LoadSDNode>(St->getValue());
18233         } else
18234           Ops.push_back(ChainVal->getOperand(i));
18235       }
18236     }
18237
18238     if (!Ld || !ISD::isNormalLoad(Ld))
18239       return SDValue();
18240
18241     // If this is not the MMX case, i.e. we are just turning i64 load/store
18242     // into f64 load/store, avoid the transformation if there are multiple
18243     // uses of the loaded value.
18244     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18245       return SDValue();
18246
18247     SDLoc LdDL(Ld);
18248     SDLoc StDL(N);
18249     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18250     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18251     // pair instead.
18252     if (Subtarget->is64Bit() || F64IsLegal) {
18253       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18254       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18255                                   Ld->getPointerInfo(), Ld->isVolatile(),
18256                                   Ld->isNonTemporal(), Ld->isInvariant(),
18257                                   Ld->getAlignment());
18258       SDValue NewChain = NewLd.getValue(1);
18259       if (TokenFactorIndex != -1) {
18260         Ops.push_back(NewChain);
18261         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18262                                Ops.size());
18263       }
18264       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18265                           St->getPointerInfo(),
18266                           St->isVolatile(), St->isNonTemporal(),
18267                           St->getAlignment());
18268     }
18269
18270     // Otherwise, lower to two pairs of 32-bit loads / stores.
18271     SDValue LoAddr = Ld->getBasePtr();
18272     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18273                                  DAG.getConstant(4, MVT::i32));
18274
18275     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18276                                Ld->getPointerInfo(),
18277                                Ld->isVolatile(), Ld->isNonTemporal(),
18278                                Ld->isInvariant(), Ld->getAlignment());
18279     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18280                                Ld->getPointerInfo().getWithOffset(4),
18281                                Ld->isVolatile(), Ld->isNonTemporal(),
18282                                Ld->isInvariant(),
18283                                MinAlign(Ld->getAlignment(), 4));
18284
18285     SDValue NewChain = LoLd.getValue(1);
18286     if (TokenFactorIndex != -1) {
18287       Ops.push_back(LoLd);
18288       Ops.push_back(HiLd);
18289       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18290                              Ops.size());
18291     }
18292
18293     LoAddr = St->getBasePtr();
18294     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18295                          DAG.getConstant(4, MVT::i32));
18296
18297     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18298                                 St->getPointerInfo(),
18299                                 St->isVolatile(), St->isNonTemporal(),
18300                                 St->getAlignment());
18301     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18302                                 St->getPointerInfo().getWithOffset(4),
18303                                 St->isVolatile(),
18304                                 St->isNonTemporal(),
18305                                 MinAlign(St->getAlignment(), 4));
18306     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18307   }
18308   return SDValue();
18309 }
18310
18311 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18312 /// and return the operands for the horizontal operation in LHS and RHS.  A
18313 /// horizontal operation performs the binary operation on successive elements
18314 /// of its first operand, then on successive elements of its second operand,
18315 /// returning the resulting values in a vector.  For example, if
18316 ///   A = < float a0, float a1, float a2, float a3 >
18317 /// and
18318 ///   B = < float b0, float b1, float b2, float b3 >
18319 /// then the result of doing a horizontal operation on A and B is
18320 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18321 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18322 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18323 /// set to A, RHS to B, and the routine returns 'true'.
18324 /// Note that the binary operation should have the property that if one of the
18325 /// operands is UNDEF then the result is UNDEF.
18326 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18327   // Look for the following pattern: if
18328   //   A = < float a0, float a1, float a2, float a3 >
18329   //   B = < float b0, float b1, float b2, float b3 >
18330   // and
18331   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18332   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18333   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18334   // which is A horizontal-op B.
18335
18336   // At least one of the operands should be a vector shuffle.
18337   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18338       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18339     return false;
18340
18341   MVT VT = LHS.getSimpleValueType();
18342
18343   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18344          "Unsupported vector type for horizontal add/sub");
18345
18346   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18347   // operate independently on 128-bit lanes.
18348   unsigned NumElts = VT.getVectorNumElements();
18349   unsigned NumLanes = VT.getSizeInBits()/128;
18350   unsigned NumLaneElts = NumElts / NumLanes;
18351   assert((NumLaneElts % 2 == 0) &&
18352          "Vector type should have an even number of elements in each lane");
18353   unsigned HalfLaneElts = NumLaneElts/2;
18354
18355   // View LHS in the form
18356   //   LHS = VECTOR_SHUFFLE A, B, LMask
18357   // If LHS is not a shuffle then pretend it is the shuffle
18358   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18359   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18360   // type VT.
18361   SDValue A, B;
18362   SmallVector<int, 16> LMask(NumElts);
18363   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18364     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18365       A = LHS.getOperand(0);
18366     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18367       B = LHS.getOperand(1);
18368     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18369     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18370   } else {
18371     if (LHS.getOpcode() != ISD::UNDEF)
18372       A = LHS;
18373     for (unsigned i = 0; i != NumElts; ++i)
18374       LMask[i] = i;
18375   }
18376
18377   // Likewise, view RHS in the form
18378   //   RHS = VECTOR_SHUFFLE C, D, RMask
18379   SDValue C, D;
18380   SmallVector<int, 16> RMask(NumElts);
18381   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18382     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18383       C = RHS.getOperand(0);
18384     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18385       D = RHS.getOperand(1);
18386     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18387     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18388   } else {
18389     if (RHS.getOpcode() != ISD::UNDEF)
18390       C = RHS;
18391     for (unsigned i = 0; i != NumElts; ++i)
18392       RMask[i] = i;
18393   }
18394
18395   // Check that the shuffles are both shuffling the same vectors.
18396   if (!(A == C && B == D) && !(A == D && B == C))
18397     return false;
18398
18399   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18400   if (!A.getNode() && !B.getNode())
18401     return false;
18402
18403   // If A and B occur in reverse order in RHS, then "swap" them (which means
18404   // rewriting the mask).
18405   if (A != C)
18406     CommuteVectorShuffleMask(RMask, NumElts);
18407
18408   // At this point LHS and RHS are equivalent to
18409   //   LHS = VECTOR_SHUFFLE A, B, LMask
18410   //   RHS = VECTOR_SHUFFLE A, B, RMask
18411   // Check that the masks correspond to performing a horizontal operation.
18412   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18413     for (unsigned i = 0; i != NumLaneElts; ++i) {
18414       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18415
18416       // Ignore any UNDEF components.
18417       if (LIdx < 0 || RIdx < 0 ||
18418           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18419           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18420         continue;
18421
18422       // Check that successive elements are being operated on.  If not, this is
18423       // not a horizontal operation.
18424       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18425       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18426       if (!(LIdx == Index && RIdx == Index + 1) &&
18427           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18428         return false;
18429     }
18430   }
18431
18432   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18433   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18434   return true;
18435 }
18436
18437 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18438 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18439                                   const X86Subtarget *Subtarget) {
18440   EVT VT = N->getValueType(0);
18441   SDValue LHS = N->getOperand(0);
18442   SDValue RHS = N->getOperand(1);
18443
18444   // Try to synthesize horizontal adds from adds of shuffles.
18445   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18446        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18447       isHorizontalBinOp(LHS, RHS, true))
18448     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18449   return SDValue();
18450 }
18451
18452 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18453 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18454                                   const X86Subtarget *Subtarget) {
18455   EVT VT = N->getValueType(0);
18456   SDValue LHS = N->getOperand(0);
18457   SDValue RHS = N->getOperand(1);
18458
18459   // Try to synthesize horizontal subs from subs of shuffles.
18460   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18461        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18462       isHorizontalBinOp(LHS, RHS, false))
18463     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18464   return SDValue();
18465 }
18466
18467 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18468 /// X86ISD::FXOR nodes.
18469 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18470   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18471   // F[X]OR(0.0, x) -> x
18472   // F[X]OR(x, 0.0) -> x
18473   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18474     if (C->getValueAPF().isPosZero())
18475       return N->getOperand(1);
18476   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18477     if (C->getValueAPF().isPosZero())
18478       return N->getOperand(0);
18479   return SDValue();
18480 }
18481
18482 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18483 /// X86ISD::FMAX nodes.
18484 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18485   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18486
18487   // Only perform optimizations if UnsafeMath is used.
18488   if (!DAG.getTarget().Options.UnsafeFPMath)
18489     return SDValue();
18490
18491   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18492   // into FMINC and FMAXC, which are Commutative operations.
18493   unsigned NewOp = 0;
18494   switch (N->getOpcode()) {
18495     default: llvm_unreachable("unknown opcode");
18496     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18497     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18498   }
18499
18500   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18501                      N->getOperand(0), N->getOperand(1));
18502 }
18503
18504 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18505 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18506   // FAND(0.0, x) -> 0.0
18507   // FAND(x, 0.0) -> 0.0
18508   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18509     if (C->getValueAPF().isPosZero())
18510       return N->getOperand(0);
18511   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18512     if (C->getValueAPF().isPosZero())
18513       return N->getOperand(1);
18514   return SDValue();
18515 }
18516
18517 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18518 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18519   // FANDN(x, 0.0) -> 0.0
18520   // FANDN(0.0, x) -> x
18521   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18522     if (C->getValueAPF().isPosZero())
18523       return N->getOperand(1);
18524   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18525     if (C->getValueAPF().isPosZero())
18526       return N->getOperand(1);
18527   return SDValue();
18528 }
18529
18530 static SDValue PerformBTCombine(SDNode *N,
18531                                 SelectionDAG &DAG,
18532                                 TargetLowering::DAGCombinerInfo &DCI) {
18533   // BT ignores high bits in the bit index operand.
18534   SDValue Op1 = N->getOperand(1);
18535   if (Op1.hasOneUse()) {
18536     unsigned BitWidth = Op1.getValueSizeInBits();
18537     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18538     APInt KnownZero, KnownOne;
18539     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18540                                           !DCI.isBeforeLegalizeOps());
18541     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18542     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18543         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18544       DCI.CommitTargetLoweringOpt(TLO);
18545   }
18546   return SDValue();
18547 }
18548
18549 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18550   SDValue Op = N->getOperand(0);
18551   if (Op.getOpcode() == ISD::BITCAST)
18552     Op = Op.getOperand(0);
18553   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18554   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18555       VT.getVectorElementType().getSizeInBits() ==
18556       OpVT.getVectorElementType().getSizeInBits()) {
18557     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18558   }
18559   return SDValue();
18560 }
18561
18562 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18563                                                const X86Subtarget *Subtarget) {
18564   EVT VT = N->getValueType(0);
18565   if (!VT.isVector())
18566     return SDValue();
18567
18568   SDValue N0 = N->getOperand(0);
18569   SDValue N1 = N->getOperand(1);
18570   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18571   SDLoc dl(N);
18572
18573   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18574   // both SSE and AVX2 since there is no sign-extended shift right
18575   // operation on a vector with 64-bit elements.
18576   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18577   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18578   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18579       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18580     SDValue N00 = N0.getOperand(0);
18581
18582     // EXTLOAD has a better solution on AVX2,
18583     // it may be replaced with X86ISD::VSEXT node.
18584     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18585       if (!ISD::isNormalLoad(N00.getNode()))
18586         return SDValue();
18587
18588     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18589         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18590                                   N00, N1);
18591       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18592     }
18593   }
18594   return SDValue();
18595 }
18596
18597 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18598                                   TargetLowering::DAGCombinerInfo &DCI,
18599                                   const X86Subtarget *Subtarget) {
18600   if (!DCI.isBeforeLegalizeOps())
18601     return SDValue();
18602
18603   if (!Subtarget->hasFp256())
18604     return SDValue();
18605
18606   EVT VT = N->getValueType(0);
18607   if (VT.isVector() && VT.getSizeInBits() == 256) {
18608     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18609     if (R.getNode())
18610       return R;
18611   }
18612
18613   return SDValue();
18614 }
18615
18616 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18617                                  const X86Subtarget* Subtarget) {
18618   SDLoc dl(N);
18619   EVT VT = N->getValueType(0);
18620
18621   // Let legalize expand this if it isn't a legal type yet.
18622   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18623     return SDValue();
18624
18625   EVT ScalarVT = VT.getScalarType();
18626   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18627       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18628     return SDValue();
18629
18630   SDValue A = N->getOperand(0);
18631   SDValue B = N->getOperand(1);
18632   SDValue C = N->getOperand(2);
18633
18634   bool NegA = (A.getOpcode() == ISD::FNEG);
18635   bool NegB = (B.getOpcode() == ISD::FNEG);
18636   bool NegC = (C.getOpcode() == ISD::FNEG);
18637
18638   // Negative multiplication when NegA xor NegB
18639   bool NegMul = (NegA != NegB);
18640   if (NegA)
18641     A = A.getOperand(0);
18642   if (NegB)
18643     B = B.getOperand(0);
18644   if (NegC)
18645     C = C.getOperand(0);
18646
18647   unsigned Opcode;
18648   if (!NegMul)
18649     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18650   else
18651     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18652
18653   return DAG.getNode(Opcode, dl, VT, A, B, C);
18654 }
18655
18656 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18657                                   TargetLowering::DAGCombinerInfo &DCI,
18658                                   const X86Subtarget *Subtarget) {
18659   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18660   //           (and (i32 x86isd::setcc_carry), 1)
18661   // This eliminates the zext. This transformation is necessary because
18662   // ISD::SETCC is always legalized to i8.
18663   SDLoc dl(N);
18664   SDValue N0 = N->getOperand(0);
18665   EVT VT = N->getValueType(0);
18666
18667   if (N0.getOpcode() == ISD::AND &&
18668       N0.hasOneUse() &&
18669       N0.getOperand(0).hasOneUse()) {
18670     SDValue N00 = N0.getOperand(0);
18671     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18672       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18673       if (!C || C->getZExtValue() != 1)
18674         return SDValue();
18675       return DAG.getNode(ISD::AND, dl, VT,
18676                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18677                                      N00.getOperand(0), N00.getOperand(1)),
18678                          DAG.getConstant(1, VT));
18679     }
18680   }
18681
18682   if (VT.is256BitVector()) {
18683     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18684     if (R.getNode())
18685       return R;
18686   }
18687
18688   return SDValue();
18689 }
18690
18691 // Optimize x == -y --> x+y == 0
18692 //          x != -y --> x+y != 0
18693 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18694   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18695   SDValue LHS = N->getOperand(0);
18696   SDValue RHS = N->getOperand(1);
18697
18698   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18699     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18700       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18701         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18702                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18703         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18704                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18705       }
18706   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18707     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18708       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18709         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18710                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18711         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18712                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18713       }
18714   return SDValue();
18715 }
18716
18717 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18718 // as "sbb reg,reg", since it can be extended without zext and produces
18719 // an all-ones bit which is more useful than 0/1 in some cases.
18720 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18721   return DAG.getNode(ISD::AND, DL, MVT::i8,
18722                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18723                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18724                      DAG.getConstant(1, MVT::i8));
18725 }
18726
18727 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18728 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18729                                    TargetLowering::DAGCombinerInfo &DCI,
18730                                    const X86Subtarget *Subtarget) {
18731   SDLoc DL(N);
18732   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18733   SDValue EFLAGS = N->getOperand(1);
18734
18735   if (CC == X86::COND_A) {
18736     // Try to convert COND_A into COND_B in an attempt to facilitate
18737     // materializing "setb reg".
18738     //
18739     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18740     // cannot take an immediate as its first operand.
18741     //
18742     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18743         EFLAGS.getValueType().isInteger() &&
18744         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18745       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18746                                    EFLAGS.getNode()->getVTList(),
18747                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18748       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18749       return MaterializeSETB(DL, NewEFLAGS, DAG);
18750     }
18751   }
18752
18753   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18754   // a zext and produces an all-ones bit which is more useful than 0/1 in some
18755   // cases.
18756   if (CC == X86::COND_B)
18757     return MaterializeSETB(DL, EFLAGS, DAG);
18758
18759   SDValue Flags;
18760
18761   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18762   if (Flags.getNode()) {
18763     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18764     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18765   }
18766
18767   return SDValue();
18768 }
18769
18770 // Optimize branch condition evaluation.
18771 //
18772 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18773                                     TargetLowering::DAGCombinerInfo &DCI,
18774                                     const X86Subtarget *Subtarget) {
18775   SDLoc DL(N);
18776   SDValue Chain = N->getOperand(0);
18777   SDValue Dest = N->getOperand(1);
18778   SDValue EFLAGS = N->getOperand(3);
18779   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18780
18781   SDValue Flags;
18782
18783   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18784   if (Flags.getNode()) {
18785     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18786     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18787                        Flags);
18788   }
18789
18790   return SDValue();
18791 }
18792
18793 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18794                                         const X86TargetLowering *XTLI) {
18795   SDValue Op0 = N->getOperand(0);
18796   EVT InVT = Op0->getValueType(0);
18797
18798   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18799   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18800     SDLoc dl(N);
18801     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18802     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18803     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18804   }
18805
18806   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18807   // a 32-bit target where SSE doesn't support i64->FP operations.
18808   if (Op0.getOpcode() == ISD::LOAD) {
18809     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18810     EVT VT = Ld->getValueType(0);
18811     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18812         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18813         !XTLI->getSubtarget()->is64Bit() &&
18814         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18815       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18816                                           Ld->getChain(), Op0, DAG);
18817       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18818       return FILDChain;
18819     }
18820   }
18821   return SDValue();
18822 }
18823
18824 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18825 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18826                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18827   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18828   // the result is either zero or one (depending on the input carry bit).
18829   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18830   if (X86::isZeroNode(N->getOperand(0)) &&
18831       X86::isZeroNode(N->getOperand(1)) &&
18832       // We don't have a good way to replace an EFLAGS use, so only do this when
18833       // dead right now.
18834       SDValue(N, 1).use_empty()) {
18835     SDLoc DL(N);
18836     EVT VT = N->getValueType(0);
18837     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18838     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18839                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18840                                            DAG.getConstant(X86::COND_B,MVT::i8),
18841                                            N->getOperand(2)),
18842                                DAG.getConstant(1, VT));
18843     return DCI.CombineTo(N, Res1, CarryOut);
18844   }
18845
18846   return SDValue();
18847 }
18848
18849 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18850 //      (add Y, (setne X, 0)) -> sbb -1, Y
18851 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18852 //      (sub (setne X, 0), Y) -> adc -1, Y
18853 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18854   SDLoc DL(N);
18855
18856   // Look through ZExts.
18857   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18858   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18859     return SDValue();
18860
18861   SDValue SetCC = Ext.getOperand(0);
18862   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18863     return SDValue();
18864
18865   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18866   if (CC != X86::COND_E && CC != X86::COND_NE)
18867     return SDValue();
18868
18869   SDValue Cmp = SetCC.getOperand(1);
18870   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18871       !X86::isZeroNode(Cmp.getOperand(1)) ||
18872       !Cmp.getOperand(0).getValueType().isInteger())
18873     return SDValue();
18874
18875   SDValue CmpOp0 = Cmp.getOperand(0);
18876   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18877                                DAG.getConstant(1, CmpOp0.getValueType()));
18878
18879   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18880   if (CC == X86::COND_NE)
18881     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18882                        DL, OtherVal.getValueType(), OtherVal,
18883                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18884   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18885                      DL, OtherVal.getValueType(), OtherVal,
18886                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18887 }
18888
18889 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18890 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18891                                  const X86Subtarget *Subtarget) {
18892   EVT VT = N->getValueType(0);
18893   SDValue Op0 = N->getOperand(0);
18894   SDValue Op1 = N->getOperand(1);
18895
18896   // Try to synthesize horizontal adds from adds of shuffles.
18897   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18898        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18899       isHorizontalBinOp(Op0, Op1, true))
18900     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18901
18902   return OptimizeConditionalInDecrement(N, DAG);
18903 }
18904
18905 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18906                                  const X86Subtarget *Subtarget) {
18907   SDValue Op0 = N->getOperand(0);
18908   SDValue Op1 = N->getOperand(1);
18909
18910   // X86 can't encode an immediate LHS of a sub. See if we can push the
18911   // negation into a preceding instruction.
18912   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18913     // If the RHS of the sub is a XOR with one use and a constant, invert the
18914     // immediate. Then add one to the LHS of the sub so we can turn
18915     // X-Y -> X+~Y+1, saving one register.
18916     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18917         isa<ConstantSDNode>(Op1.getOperand(1))) {
18918       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18919       EVT VT = Op0.getValueType();
18920       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18921                                    Op1.getOperand(0),
18922                                    DAG.getConstant(~XorC, VT));
18923       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18924                          DAG.getConstant(C->getAPIntValue()+1, VT));
18925     }
18926   }
18927
18928   // Try to synthesize horizontal adds from adds of shuffles.
18929   EVT VT = N->getValueType(0);
18930   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18931        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18932       isHorizontalBinOp(Op0, Op1, true))
18933     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18934
18935   return OptimizeConditionalInDecrement(N, DAG);
18936 }
18937
18938 /// performVZEXTCombine - Performs build vector combines
18939 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18940                                         TargetLowering::DAGCombinerInfo &DCI,
18941                                         const X86Subtarget *Subtarget) {
18942   // (vzext (bitcast (vzext (x)) -> (vzext x)
18943   SDValue In = N->getOperand(0);
18944   while (In.getOpcode() == ISD::BITCAST)
18945     In = In.getOperand(0);
18946
18947   if (In.getOpcode() != X86ISD::VZEXT)
18948     return SDValue();
18949
18950   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18951                      In.getOperand(0));
18952 }
18953
18954 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18955                                              DAGCombinerInfo &DCI) const {
18956   SelectionDAG &DAG = DCI.DAG;
18957   switch (N->getOpcode()) {
18958   default: break;
18959   case ISD::EXTRACT_VECTOR_ELT:
18960     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18961   case ISD::VSELECT:
18962   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18963   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18964   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18965   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18966   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18967   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18968   case ISD::SHL:
18969   case ISD::SRA:
18970   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18971   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18972   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18973   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18974   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18975   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18976   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18977   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18978   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18979   case X86ISD::FXOR:
18980   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18981   case X86ISD::FMIN:
18982   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18983   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18984   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
18985   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18986   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18987   case ISD::ANY_EXTEND:
18988   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18989   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18990   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18991   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18992   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18993   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18994   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18995   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18996   case X86ISD::SHUFP:       // Handle all target specific shuffles
18997   case X86ISD::PALIGNR:
18998   case X86ISD::UNPCKH:
18999   case X86ISD::UNPCKL:
19000   case X86ISD::MOVHLPS:
19001   case X86ISD::MOVLHPS:
19002   case X86ISD::PSHUFD:
19003   case X86ISD::PSHUFHW:
19004   case X86ISD::PSHUFLW:
19005   case X86ISD::MOVSS:
19006   case X86ISD::MOVSD:
19007   case X86ISD::VPERMILP:
19008   case X86ISD::VPERM2X128:
19009   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19010   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19011   }
19012
19013   return SDValue();
19014 }
19015
19016 /// isTypeDesirableForOp - Return true if the target has native support for
19017 /// the specified value type and it is 'desirable' to use the type for the
19018 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19019 /// instruction encodings are longer and some i16 instructions are slow.
19020 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19021   if (!isTypeLegal(VT))
19022     return false;
19023   if (VT != MVT::i16)
19024     return true;
19025
19026   switch (Opc) {
19027   default:
19028     return true;
19029   case ISD::LOAD:
19030   case ISD::SIGN_EXTEND:
19031   case ISD::ZERO_EXTEND:
19032   case ISD::ANY_EXTEND:
19033   case ISD::SHL:
19034   case ISD::SRL:
19035   case ISD::SUB:
19036   case ISD::ADD:
19037   case ISD::MUL:
19038   case ISD::AND:
19039   case ISD::OR:
19040   case ISD::XOR:
19041     return false;
19042   }
19043 }
19044
19045 /// IsDesirableToPromoteOp - This method query the target whether it is
19046 /// beneficial for dag combiner to promote the specified node. If true, it
19047 /// should return the desired promotion type by reference.
19048 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19049   EVT VT = Op.getValueType();
19050   if (VT != MVT::i16)
19051     return false;
19052
19053   bool Promote = false;
19054   bool Commute = false;
19055   switch (Op.getOpcode()) {
19056   default: break;
19057   case ISD::LOAD: {
19058     LoadSDNode *LD = cast<LoadSDNode>(Op);
19059     // If the non-extending load has a single use and it's not live out, then it
19060     // might be folded.
19061     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19062                                                      Op.hasOneUse()*/) {
19063       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19064              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19065         // The only case where we'd want to promote LOAD (rather then it being
19066         // promoted as an operand is when it's only use is liveout.
19067         if (UI->getOpcode() != ISD::CopyToReg)
19068           return false;
19069       }
19070     }
19071     Promote = true;
19072     break;
19073   }
19074   case ISD::SIGN_EXTEND:
19075   case ISD::ZERO_EXTEND:
19076   case ISD::ANY_EXTEND:
19077     Promote = true;
19078     break;
19079   case ISD::SHL:
19080   case ISD::SRL: {
19081     SDValue N0 = Op.getOperand(0);
19082     // Look out for (store (shl (load), x)).
19083     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19084       return false;
19085     Promote = true;
19086     break;
19087   }
19088   case ISD::ADD:
19089   case ISD::MUL:
19090   case ISD::AND:
19091   case ISD::OR:
19092   case ISD::XOR:
19093     Commute = true;
19094     // fallthrough
19095   case ISD::SUB: {
19096     SDValue N0 = Op.getOperand(0);
19097     SDValue N1 = Op.getOperand(1);
19098     if (!Commute && MayFoldLoad(N1))
19099       return false;
19100     // Avoid disabling potential load folding opportunities.
19101     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19102       return false;
19103     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19104       return false;
19105     Promote = true;
19106   }
19107   }
19108
19109   PVT = MVT::i32;
19110   return Promote;
19111 }
19112
19113 //===----------------------------------------------------------------------===//
19114 //                           X86 Inline Assembly Support
19115 //===----------------------------------------------------------------------===//
19116
19117 namespace {
19118   // Helper to match a string separated by whitespace.
19119   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19120     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19121
19122     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19123       StringRef piece(*args[i]);
19124       if (!s.startswith(piece)) // Check if the piece matches.
19125         return false;
19126
19127       s = s.substr(piece.size());
19128       StringRef::size_type pos = s.find_first_not_of(" \t");
19129       if (pos == 0) // We matched a prefix.
19130         return false;
19131
19132       s = s.substr(pos);
19133     }
19134
19135     return s.empty();
19136   }
19137   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19138 }
19139
19140 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19141   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19142
19143   std::string AsmStr = IA->getAsmString();
19144
19145   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19146   if (!Ty || Ty->getBitWidth() % 16 != 0)
19147     return false;
19148
19149   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19150   SmallVector<StringRef, 4> AsmPieces;
19151   SplitString(AsmStr, AsmPieces, ";\n");
19152
19153   switch (AsmPieces.size()) {
19154   default: return false;
19155   case 1:
19156     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19157     // we will turn this bswap into something that will be lowered to logical
19158     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19159     // lower so don't worry about this.
19160     // bswap $0
19161     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19162         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19163         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19164         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19165         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19166         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19167       // No need to check constraints, nothing other than the equivalent of
19168       // "=r,0" would be valid here.
19169       return IntrinsicLowering::LowerToByteSwap(CI);
19170     }
19171
19172     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19173     if (CI->getType()->isIntegerTy(16) &&
19174         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19175         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19176          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19177       AsmPieces.clear();
19178       const std::string &ConstraintsStr = IA->getConstraintString();
19179       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19180       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19181       if (AsmPieces.size() == 4 &&
19182           AsmPieces[0] == "~{cc}" &&
19183           AsmPieces[1] == "~{dirflag}" &&
19184           AsmPieces[2] == "~{flags}" &&
19185           AsmPieces[3] == "~{fpsr}")
19186       return IntrinsicLowering::LowerToByteSwap(CI);
19187     }
19188     break;
19189   case 3:
19190     if (CI->getType()->isIntegerTy(32) &&
19191         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19192         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19193         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19194         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19195       AsmPieces.clear();
19196       const std::string &ConstraintsStr = IA->getConstraintString();
19197       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19198       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19199       if (AsmPieces.size() == 4 &&
19200           AsmPieces[0] == "~{cc}" &&
19201           AsmPieces[1] == "~{dirflag}" &&
19202           AsmPieces[2] == "~{flags}" &&
19203           AsmPieces[3] == "~{fpsr}")
19204         return IntrinsicLowering::LowerToByteSwap(CI);
19205     }
19206
19207     if (CI->getType()->isIntegerTy(64)) {
19208       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19209       if (Constraints.size() >= 2 &&
19210           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19211           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19212         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19213         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19214             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19215             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19216           return IntrinsicLowering::LowerToByteSwap(CI);
19217       }
19218     }
19219     break;
19220   }
19221   return false;
19222 }
19223
19224 /// getConstraintType - Given a constraint letter, return the type of
19225 /// constraint it is for this target.
19226 X86TargetLowering::ConstraintType
19227 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19228   if (Constraint.size() == 1) {
19229     switch (Constraint[0]) {
19230     case 'R':
19231     case 'q':
19232     case 'Q':
19233     case 'f':
19234     case 't':
19235     case 'u':
19236     case 'y':
19237     case 'x':
19238     case 'Y':
19239     case 'l':
19240       return C_RegisterClass;
19241     case 'a':
19242     case 'b':
19243     case 'c':
19244     case 'd':
19245     case 'S':
19246     case 'D':
19247     case 'A':
19248       return C_Register;
19249     case 'I':
19250     case 'J':
19251     case 'K':
19252     case 'L':
19253     case 'M':
19254     case 'N':
19255     case 'G':
19256     case 'C':
19257     case 'e':
19258     case 'Z':
19259       return C_Other;
19260     default:
19261       break;
19262     }
19263   }
19264   return TargetLowering::getConstraintType(Constraint);
19265 }
19266
19267 /// Examine constraint type and operand type and determine a weight value.
19268 /// This object must already have been set up with the operand type
19269 /// and the current alternative constraint selected.
19270 TargetLowering::ConstraintWeight
19271   X86TargetLowering::getSingleConstraintMatchWeight(
19272     AsmOperandInfo &info, const char *constraint) const {
19273   ConstraintWeight weight = CW_Invalid;
19274   Value *CallOperandVal = info.CallOperandVal;
19275     // If we don't have a value, we can't do a match,
19276     // but allow it at the lowest weight.
19277   if (CallOperandVal == NULL)
19278     return CW_Default;
19279   Type *type = CallOperandVal->getType();
19280   // Look at the constraint type.
19281   switch (*constraint) {
19282   default:
19283     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19284   case 'R':
19285   case 'q':
19286   case 'Q':
19287   case 'a':
19288   case 'b':
19289   case 'c':
19290   case 'd':
19291   case 'S':
19292   case 'D':
19293   case 'A':
19294     if (CallOperandVal->getType()->isIntegerTy())
19295       weight = CW_SpecificReg;
19296     break;
19297   case 'f':
19298   case 't':
19299   case 'u':
19300     if (type->isFloatingPointTy())
19301       weight = CW_SpecificReg;
19302     break;
19303   case 'y':
19304     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19305       weight = CW_SpecificReg;
19306     break;
19307   case 'x':
19308   case 'Y':
19309     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19310         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19311       weight = CW_Register;
19312     break;
19313   case 'I':
19314     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19315       if (C->getZExtValue() <= 31)
19316         weight = CW_Constant;
19317     }
19318     break;
19319   case 'J':
19320     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19321       if (C->getZExtValue() <= 63)
19322         weight = CW_Constant;
19323     }
19324     break;
19325   case 'K':
19326     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19327       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19328         weight = CW_Constant;
19329     }
19330     break;
19331   case 'L':
19332     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19333       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19334         weight = CW_Constant;
19335     }
19336     break;
19337   case 'M':
19338     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19339       if (C->getZExtValue() <= 3)
19340         weight = CW_Constant;
19341     }
19342     break;
19343   case 'N':
19344     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19345       if (C->getZExtValue() <= 0xff)
19346         weight = CW_Constant;
19347     }
19348     break;
19349   case 'G':
19350   case 'C':
19351     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19352       weight = CW_Constant;
19353     }
19354     break;
19355   case 'e':
19356     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19357       if ((C->getSExtValue() >= -0x80000000LL) &&
19358           (C->getSExtValue() <= 0x7fffffffLL))
19359         weight = CW_Constant;
19360     }
19361     break;
19362   case 'Z':
19363     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19364       if (C->getZExtValue() <= 0xffffffff)
19365         weight = CW_Constant;
19366     }
19367     break;
19368   }
19369   return weight;
19370 }
19371
19372 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19373 /// with another that has more specific requirements based on the type of the
19374 /// corresponding operand.
19375 const char *X86TargetLowering::
19376 LowerXConstraint(EVT ConstraintVT) const {
19377   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19378   // 'f' like normal targets.
19379   if (ConstraintVT.isFloatingPoint()) {
19380     if (Subtarget->hasSSE2())
19381       return "Y";
19382     if (Subtarget->hasSSE1())
19383       return "x";
19384   }
19385
19386   return TargetLowering::LowerXConstraint(ConstraintVT);
19387 }
19388
19389 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19390 /// vector.  If it is invalid, don't add anything to Ops.
19391 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19392                                                      std::string &Constraint,
19393                                                      std::vector<SDValue>&Ops,
19394                                                      SelectionDAG &DAG) const {
19395   SDValue Result(0, 0);
19396
19397   // Only support length 1 constraints for now.
19398   if (Constraint.length() > 1) return;
19399
19400   char ConstraintLetter = Constraint[0];
19401   switch (ConstraintLetter) {
19402   default: break;
19403   case 'I':
19404     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19405       if (C->getZExtValue() <= 31) {
19406         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19407         break;
19408       }
19409     }
19410     return;
19411   case 'J':
19412     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19413       if (C->getZExtValue() <= 63) {
19414         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19415         break;
19416       }
19417     }
19418     return;
19419   case 'K':
19420     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19421       if (isInt<8>(C->getSExtValue())) {
19422         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19423         break;
19424       }
19425     }
19426     return;
19427   case 'N':
19428     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19429       if (C->getZExtValue() <= 255) {
19430         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19431         break;
19432       }
19433     }
19434     return;
19435   case 'e': {
19436     // 32-bit signed value
19437     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19438       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19439                                            C->getSExtValue())) {
19440         // Widen to 64 bits here to get it sign extended.
19441         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19442         break;
19443       }
19444     // FIXME gcc accepts some relocatable values here too, but only in certain
19445     // memory models; it's complicated.
19446     }
19447     return;
19448   }
19449   case 'Z': {
19450     // 32-bit unsigned value
19451     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19452       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19453                                            C->getZExtValue())) {
19454         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19455         break;
19456       }
19457     }
19458     // FIXME gcc accepts some relocatable values here too, but only in certain
19459     // memory models; it's complicated.
19460     return;
19461   }
19462   case 'i': {
19463     // Literal immediates are always ok.
19464     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19465       // Widen to 64 bits here to get it sign extended.
19466       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19467       break;
19468     }
19469
19470     // In any sort of PIC mode addresses need to be computed at runtime by
19471     // adding in a register or some sort of table lookup.  These can't
19472     // be used as immediates.
19473     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19474       return;
19475
19476     // If we are in non-pic codegen mode, we allow the address of a global (with
19477     // an optional displacement) to be used with 'i'.
19478     GlobalAddressSDNode *GA = 0;
19479     int64_t Offset = 0;
19480
19481     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19482     while (1) {
19483       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19484         Offset += GA->getOffset();
19485         break;
19486       } else if (Op.getOpcode() == ISD::ADD) {
19487         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19488           Offset += C->getZExtValue();
19489           Op = Op.getOperand(0);
19490           continue;
19491         }
19492       } else if (Op.getOpcode() == ISD::SUB) {
19493         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19494           Offset += -C->getZExtValue();
19495           Op = Op.getOperand(0);
19496           continue;
19497         }
19498       }
19499
19500       // Otherwise, this isn't something we can handle, reject it.
19501       return;
19502     }
19503
19504     const GlobalValue *GV = GA->getGlobal();
19505     // If we require an extra load to get this address, as in PIC mode, we
19506     // can't accept it.
19507     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19508                                                         getTargetMachine())))
19509       return;
19510
19511     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19512                                         GA->getValueType(0), Offset);
19513     break;
19514   }
19515   }
19516
19517   if (Result.getNode()) {
19518     Ops.push_back(Result);
19519     return;
19520   }
19521   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19522 }
19523
19524 std::pair<unsigned, const TargetRegisterClass*>
19525 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19526                                                 MVT VT) const {
19527   // First, see if this is a constraint that directly corresponds to an LLVM
19528   // register class.
19529   if (Constraint.size() == 1) {
19530     // GCC Constraint Letters
19531     switch (Constraint[0]) {
19532     default: break;
19533       // TODO: Slight differences here in allocation order and leaving
19534       // RIP in the class. Do they matter any more here than they do
19535       // in the normal allocation?
19536     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19537       if (Subtarget->is64Bit()) {
19538         if (VT == MVT::i32 || VT == MVT::f32)
19539           return std::make_pair(0U, &X86::GR32RegClass);
19540         if (VT == MVT::i16)
19541           return std::make_pair(0U, &X86::GR16RegClass);
19542         if (VT == MVT::i8 || VT == MVT::i1)
19543           return std::make_pair(0U, &X86::GR8RegClass);
19544         if (VT == MVT::i64 || VT == MVT::f64)
19545           return std::make_pair(0U, &X86::GR64RegClass);
19546         break;
19547       }
19548       // 32-bit fallthrough
19549     case 'Q':   // Q_REGS
19550       if (VT == MVT::i32 || VT == MVT::f32)
19551         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19552       if (VT == MVT::i16)
19553         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19554       if (VT == MVT::i8 || VT == MVT::i1)
19555         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19556       if (VT == MVT::i64)
19557         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19558       break;
19559     case 'r':   // GENERAL_REGS
19560     case 'l':   // INDEX_REGS
19561       if (VT == MVT::i8 || VT == MVT::i1)
19562         return std::make_pair(0U, &X86::GR8RegClass);
19563       if (VT == MVT::i16)
19564         return std::make_pair(0U, &X86::GR16RegClass);
19565       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19566         return std::make_pair(0U, &X86::GR32RegClass);
19567       return std::make_pair(0U, &X86::GR64RegClass);
19568     case 'R':   // LEGACY_REGS
19569       if (VT == MVT::i8 || VT == MVT::i1)
19570         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19571       if (VT == MVT::i16)
19572         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19573       if (VT == MVT::i32 || !Subtarget->is64Bit())
19574         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19575       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19576     case 'f':  // FP Stack registers.
19577       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19578       // value to the correct fpstack register class.
19579       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19580         return std::make_pair(0U, &X86::RFP32RegClass);
19581       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19582         return std::make_pair(0U, &X86::RFP64RegClass);
19583       return std::make_pair(0U, &X86::RFP80RegClass);
19584     case 'y':   // MMX_REGS if MMX allowed.
19585       if (!Subtarget->hasMMX()) break;
19586       return std::make_pair(0U, &X86::VR64RegClass);
19587     case 'Y':   // SSE_REGS if SSE2 allowed
19588       if (!Subtarget->hasSSE2()) break;
19589       // FALL THROUGH.
19590     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19591       if (!Subtarget->hasSSE1()) break;
19592
19593       switch (VT.SimpleTy) {
19594       default: break;
19595       // Scalar SSE types.
19596       case MVT::f32:
19597       case MVT::i32:
19598         return std::make_pair(0U, &X86::FR32RegClass);
19599       case MVT::f64:
19600       case MVT::i64:
19601         return std::make_pair(0U, &X86::FR64RegClass);
19602       // Vector types.
19603       case MVT::v16i8:
19604       case MVT::v8i16:
19605       case MVT::v4i32:
19606       case MVT::v2i64:
19607       case MVT::v4f32:
19608       case MVT::v2f64:
19609         return std::make_pair(0U, &X86::VR128RegClass);
19610       // AVX types.
19611       case MVT::v32i8:
19612       case MVT::v16i16:
19613       case MVT::v8i32:
19614       case MVT::v4i64:
19615       case MVT::v8f32:
19616       case MVT::v4f64:
19617         return std::make_pair(0U, &X86::VR256RegClass);
19618       case MVT::v8f64:
19619       case MVT::v16f32:
19620       case MVT::v16i32:
19621       case MVT::v8i64:
19622         return std::make_pair(0U, &X86::VR512RegClass);
19623       }
19624       break;
19625     }
19626   }
19627
19628   // Use the default implementation in TargetLowering to convert the register
19629   // constraint into a member of a register class.
19630   std::pair<unsigned, const TargetRegisterClass*> Res;
19631   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19632
19633   // Not found as a standard register?
19634   if (Res.second == 0) {
19635     // Map st(0) -> st(7) -> ST0
19636     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19637         tolower(Constraint[1]) == 's' &&
19638         tolower(Constraint[2]) == 't' &&
19639         Constraint[3] == '(' &&
19640         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19641         Constraint[5] == ')' &&
19642         Constraint[6] == '}') {
19643
19644       Res.first = X86::ST0+Constraint[4]-'0';
19645       Res.second = &X86::RFP80RegClass;
19646       return Res;
19647     }
19648
19649     // GCC allows "st(0)" to be called just plain "st".
19650     if (StringRef("{st}").equals_lower(Constraint)) {
19651       Res.first = X86::ST0;
19652       Res.second = &X86::RFP80RegClass;
19653       return Res;
19654     }
19655
19656     // flags -> EFLAGS
19657     if (StringRef("{flags}").equals_lower(Constraint)) {
19658       Res.first = X86::EFLAGS;
19659       Res.second = &X86::CCRRegClass;
19660       return Res;
19661     }
19662
19663     // 'A' means EAX + EDX.
19664     if (Constraint == "A") {
19665       Res.first = X86::EAX;
19666       Res.second = &X86::GR32_ADRegClass;
19667       return Res;
19668     }
19669     return Res;
19670   }
19671
19672   // Otherwise, check to see if this is a register class of the wrong value
19673   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19674   // turn into {ax},{dx}.
19675   if (Res.second->hasType(VT))
19676     return Res;   // Correct type already, nothing to do.
19677
19678   // All of the single-register GCC register classes map their values onto
19679   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19680   // really want an 8-bit or 32-bit register, map to the appropriate register
19681   // class and return the appropriate register.
19682   if (Res.second == &X86::GR16RegClass) {
19683     if (VT == MVT::i8 || VT == MVT::i1) {
19684       unsigned DestReg = 0;
19685       switch (Res.first) {
19686       default: break;
19687       case X86::AX: DestReg = X86::AL; break;
19688       case X86::DX: DestReg = X86::DL; break;
19689       case X86::CX: DestReg = X86::CL; break;
19690       case X86::BX: DestReg = X86::BL; break;
19691       }
19692       if (DestReg) {
19693         Res.first = DestReg;
19694         Res.second = &X86::GR8RegClass;
19695       }
19696     } else if (VT == MVT::i32 || VT == MVT::f32) {
19697       unsigned DestReg = 0;
19698       switch (Res.first) {
19699       default: break;
19700       case X86::AX: DestReg = X86::EAX; break;
19701       case X86::DX: DestReg = X86::EDX; break;
19702       case X86::CX: DestReg = X86::ECX; break;
19703       case X86::BX: DestReg = X86::EBX; break;
19704       case X86::SI: DestReg = X86::ESI; break;
19705       case X86::DI: DestReg = X86::EDI; break;
19706       case X86::BP: DestReg = X86::EBP; break;
19707       case X86::SP: DestReg = X86::ESP; break;
19708       }
19709       if (DestReg) {
19710         Res.first = DestReg;
19711         Res.second = &X86::GR32RegClass;
19712       }
19713     } else if (VT == MVT::i64 || VT == MVT::f64) {
19714       unsigned DestReg = 0;
19715       switch (Res.first) {
19716       default: break;
19717       case X86::AX: DestReg = X86::RAX; break;
19718       case X86::DX: DestReg = X86::RDX; break;
19719       case X86::CX: DestReg = X86::RCX; break;
19720       case X86::BX: DestReg = X86::RBX; break;
19721       case X86::SI: DestReg = X86::RSI; break;
19722       case X86::DI: DestReg = X86::RDI; break;
19723       case X86::BP: DestReg = X86::RBP; break;
19724       case X86::SP: DestReg = X86::RSP; break;
19725       }
19726       if (DestReg) {
19727         Res.first = DestReg;
19728         Res.second = &X86::GR64RegClass;
19729       }
19730     }
19731   } else if (Res.second == &X86::FR32RegClass ||
19732              Res.second == &X86::FR64RegClass ||
19733              Res.second == &X86::VR128RegClass ||
19734              Res.second == &X86::VR256RegClass ||
19735              Res.second == &X86::FR32XRegClass ||
19736              Res.second == &X86::FR64XRegClass ||
19737              Res.second == &X86::VR128XRegClass ||
19738              Res.second == &X86::VR256XRegClass ||
19739              Res.second == &X86::VR512RegClass) {
19740     // Handle references to XMM physical registers that got mapped into the
19741     // wrong class.  This can happen with constraints like {xmm0} where the
19742     // target independent register mapper will just pick the first match it can
19743     // find, ignoring the required type.
19744
19745     if (VT == MVT::f32 || VT == MVT::i32)
19746       Res.second = &X86::FR32RegClass;
19747     else if (VT == MVT::f64 || VT == MVT::i64)
19748       Res.second = &X86::FR64RegClass;
19749     else if (X86::VR128RegClass.hasType(VT))
19750       Res.second = &X86::VR128RegClass;
19751     else if (X86::VR256RegClass.hasType(VT))
19752       Res.second = &X86::VR256RegClass;
19753     else if (X86::VR512RegClass.hasType(VT))
19754       Res.second = &X86::VR512RegClass;
19755   }
19756
19757   return Res;
19758 }