X86: correct tail return address calculation
[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
1394     // Custom lower several nodes.
1395     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397       MVT VT = (MVT::SimpleValueType)i;
1398
1399       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400       // Extract subvector is special because the value type
1401       // (result) is 256/128-bit but the source is 512-bit wide.
1402       if (VT.is128BitVector() || VT.is256BitVector())
1403         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1404
1405       if (VT.getVectorElementType() == MVT::i1)
1406         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1407
1408       // Do not attempt to custom lower other non-512-bit vectors
1409       if (!VT.is512BitVector())
1410         continue;
1411
1412       if (VT != MVT::v8i64) {
1413         setOperationAction(ISD::XOR,   VT, Promote);
1414         AddPromotedToType (ISD::XOR,   VT, MVT::v8i64);
1415         setOperationAction(ISD::OR,    VT, Promote);
1416         AddPromotedToType (ISD::OR,    VT, MVT::v8i64);
1417         setOperationAction(ISD::AND,   VT, Promote);
1418         AddPromotedToType (ISD::AND,   VT, MVT::v8i64);
1419       }
1420       if ( EltSize >= 32) {
1421         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1422         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1423         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1424         setOperationAction(ISD::VSELECT,             VT, Legal);
1425         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1426         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1427         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1428       }
1429     }
1430     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431       MVT VT = (MVT::SimpleValueType)i;
1432
1433       // Do not attempt to promote non-256-bit vectors
1434       if (!VT.is512BitVector())
1435         continue;
1436
1437       setOperationAction(ISD::LOAD,   VT, Promote);
1438       AddPromotedToType (ISD::LOAD,   VT, MVT::v8i64);
1439       setOperationAction(ISD::SELECT, VT, Promote);
1440       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1441     }
1442   }// has  AVX-512
1443
1444   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445   // of this type with custom code.
1446   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1449                        Custom);
1450   }
1451
1452   // We want to custom lower some of our intrinsics.
1453   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1455
1456   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457   // handle type legalization for these operations here.
1458   //
1459   // FIXME: We really should do custom legalization for addition and
1460   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1461   // than generic legalization for 64-bit multiplication-with-overflow, though.
1462   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463     // Add/Sub/Mul with overflow operations are custom lowered.
1464     MVT VT = IntVTs[i];
1465     setOperationAction(ISD::SADDO, VT, Custom);
1466     setOperationAction(ISD::UADDO, VT, Custom);
1467     setOperationAction(ISD::SSUBO, VT, Custom);
1468     setOperationAction(ISD::USUBO, VT, Custom);
1469     setOperationAction(ISD::SMULO, VT, Custom);
1470     setOperationAction(ISD::UMULO, VT, Custom);
1471   }
1472
1473   // There are no 8-bit 3-address imul/mul instructions
1474   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1476
1477   if (!Subtarget->is64Bit()) {
1478     // These libcalls are not available in 32-bit.
1479     setLibcallName(RTLIB::SHL_I128, 0);
1480     setLibcallName(RTLIB::SRL_I128, 0);
1481     setLibcallName(RTLIB::SRA_I128, 0);
1482   }
1483
1484   // Combine sin / cos into one node or libcall if possible.
1485   if (Subtarget->hasSinCos()) {
1486     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488     if (Subtarget->isTargetDarwin()) {
1489       // For MacOSX, we don't want to the normal expansion of a libcall to
1490       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1491       // traffic.
1492       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1494     }
1495   }
1496
1497   // We have target-specific dag combine patterns for the following nodes:
1498   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500   setTargetDAGCombine(ISD::VSELECT);
1501   setTargetDAGCombine(ISD::SELECT);
1502   setTargetDAGCombine(ISD::SHL);
1503   setTargetDAGCombine(ISD::SRA);
1504   setTargetDAGCombine(ISD::SRL);
1505   setTargetDAGCombine(ISD::OR);
1506   setTargetDAGCombine(ISD::AND);
1507   setTargetDAGCombine(ISD::ADD);
1508   setTargetDAGCombine(ISD::FADD);
1509   setTargetDAGCombine(ISD::FSUB);
1510   setTargetDAGCombine(ISD::FMA);
1511   setTargetDAGCombine(ISD::SUB);
1512   setTargetDAGCombine(ISD::LOAD);
1513   setTargetDAGCombine(ISD::STORE);
1514   setTargetDAGCombine(ISD::ZERO_EXTEND);
1515   setTargetDAGCombine(ISD::ANY_EXTEND);
1516   setTargetDAGCombine(ISD::SIGN_EXTEND);
1517   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518   setTargetDAGCombine(ISD::TRUNCATE);
1519   setTargetDAGCombine(ISD::SINT_TO_FP);
1520   setTargetDAGCombine(ISD::SETCC);
1521   if (Subtarget->is64Bit())
1522     setTargetDAGCombine(ISD::MUL);
1523   setTargetDAGCombine(ISD::XOR);
1524
1525   computeRegisterProperties();
1526
1527   // On Darwin, -Os means optimize for size without hurting performance,
1528   // do not reduce the limit.
1529   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535   setPrefLoopAlignment(4); // 2^4 bytes.
1536
1537   // Predictable cmov don't hurt on atom because it's in-order.
1538   PredictableSelectIsExpensive = !Subtarget->isAtom();
1539
1540   setPrefFunctionAlignment(4); // 2^4 bytes.
1541 }
1542
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544   if (!VT.isVector()) return MVT::i8;
1545   return VT.changeVectorElementTypeToInteger();
1546 }
1547
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1551   if (MaxAlign == 16)
1552     return;
1553   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554     if (VTy->getBitWidth() == 128)
1555       MaxAlign = 16;
1556   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557     unsigned EltAlign = 0;
1558     getMaxByValAlign(ATy->getElementType(), EltAlign);
1559     if (EltAlign > MaxAlign)
1560       MaxAlign = EltAlign;
1561   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563       unsigned EltAlign = 0;
1564       getMaxByValAlign(STy->getElementType(i), EltAlign);
1565       if (EltAlign > MaxAlign)
1566         MaxAlign = EltAlign;
1567       if (MaxAlign == 16)
1568         break;
1569     }
1570   }
1571 }
1572
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578   if (Subtarget->is64Bit()) {
1579     // Max of 8 and alignment of type.
1580     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1581     if (TyAlign > 8)
1582       return TyAlign;
1583     return 8;
1584   }
1585
1586   unsigned Align = 4;
1587   if (Subtarget->hasSSE1())
1588     getMaxByValAlign(Ty, Align);
1589   return Align;
1590 }
1591
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1603 EVT
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605                                        unsigned DstAlign, unsigned SrcAlign,
1606                                        bool IsMemset, bool ZeroMemset,
1607                                        bool MemcpyStrSrc,
1608                                        MachineFunction &MF) const {
1609   const Function *F = MF.getFunction();
1610   if ((!IsMemset || ZeroMemset) &&
1611       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612                                        Attribute::NoImplicitFloat)) {
1613     if (Size >= 16 &&
1614         (Subtarget->isUnalignedMemAccessFast() ||
1615          ((DstAlign == 0 || DstAlign >= 16) &&
1616           (SrcAlign == 0 || SrcAlign >= 16)))) {
1617       if (Size >= 32) {
1618         if (Subtarget->hasInt256())
1619           return MVT::v8i32;
1620         if (Subtarget->hasFp256())
1621           return MVT::v8f32;
1622       }
1623       if (Subtarget->hasSSE2())
1624         return MVT::v4i32;
1625       if (Subtarget->hasSSE1())
1626         return MVT::v4f32;
1627     } else if (!MemcpyStrSrc && Size >= 8 &&
1628                !Subtarget->is64Bit() &&
1629                Subtarget->hasSSE2()) {
1630       // Do not use f64 to lower memcpy if source is string constant. It's
1631       // better to use i32 to avoid the loads.
1632       return MVT::f64;
1633     }
1634   }
1635   if (Subtarget->is64Bit() && Size >= 8)
1636     return MVT::i64;
1637   return MVT::i32;
1638 }
1639
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1641   if (VT == MVT::f32)
1642     return X86ScalarSSEf32;
1643   else if (VT == MVT::f64)
1644     return X86ScalarSSEf64;
1645   return true;
1646 }
1647
1648 bool
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1650   if (Fast)
1651     *Fast = Subtarget->isUnalignedMemAccessFast();
1652   return true;
1653 }
1654
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function.  The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1660   // symbol.
1661   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662       Subtarget->isPICStyleGOT())
1663     return MachineJumpTableInfo::EK_Custom32;
1664
1665   // Otherwise, use the normal jump table encoding heuristics.
1666   return TargetLowering::getJumpTableEncoding();
1667 }
1668
1669 const MCExpr *
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671                                              const MachineBasicBlock *MBB,
1672                                              unsigned uid,MCContext &Ctx) const{
1673   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674          Subtarget->isPICStyleGOT());
1675   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1676   // entries.
1677   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1679 }
1680
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1682 /// jumptable.
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684                                                     SelectionDAG &DAG) const {
1685   if (!Subtarget->is64Bit())
1686     // This doesn't have SDLoc associated with it, but is not really the
1687     // same as a Register.
1688     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1689   return Table;
1690 }
1691
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1694 /// MCExpr.
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697                              MCContext &Ctx) const {
1698   // X86-64 uses RIP relative addressing based on the jump table label.
1699   if (Subtarget->isPICStyleRIPRel())
1700     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1701
1702   // Otherwise, the reference is relative to the PIC base.
1703   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1704 }
1705
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709   const TargetRegisterClass *RRC = 0;
1710   uint8_t Cost = 1;
1711   switch (VT.SimpleTy) {
1712   default:
1713     return TargetLowering::findRepresentativeClass(VT);
1714   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715     RRC = Subtarget->is64Bit() ?
1716       (const TargetRegisterClass*)&X86::GR64RegClass :
1717       (const TargetRegisterClass*)&X86::GR32RegClass;
1718     break;
1719   case MVT::x86mmx:
1720     RRC = &X86::VR64RegClass;
1721     break;
1722   case MVT::f32: case MVT::f64:
1723   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724   case MVT::v4f32: case MVT::v2f64:
1725   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1726   case MVT::v4f64:
1727     RRC = &X86::VR128RegClass;
1728     break;
1729   }
1730   return std::make_pair(RRC, Cost);
1731 }
1732
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734                                                unsigned &Offset) const {
1735   if (!Subtarget->isTargetLinux())
1736     return false;
1737
1738   if (Subtarget->is64Bit()) {
1739     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1740     Offset = 0x28;
1741     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1742       AddressSpace = 256;
1743     else
1744       AddressSpace = 257;
1745   } else {
1746     // %gs:0x14 on i386
1747     Offset = 0x14;
1748     AddressSpace = 256;
1749   }
1750   return true;
1751 }
1752
1753 //===----------------------------------------------------------------------===//
1754 //               Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1756
1757 #include "X86GenCallingConv.inc"
1758
1759 bool
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761                                   MachineFunction &MF, bool isVarArg,
1762                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1763                         LLVMContext &Context) const {
1764   SmallVector<CCValAssign, 16> RVLocs;
1765   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1766                  RVLocs, Context);
1767   return CCInfo.CheckReturn(Outs, RetCC_X86);
1768 }
1769
1770 SDValue
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772                                CallingConv::ID CallConv, bool isVarArg,
1773                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1774                                const SmallVectorImpl<SDValue> &OutVals,
1775                                SDLoc dl, SelectionDAG &DAG) const {
1776   MachineFunction &MF = DAG.getMachineFunction();
1777   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1778
1779   SmallVector<CCValAssign, 16> RVLocs;
1780   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781                  RVLocs, *DAG.getContext());
1782   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1783
1784   SDValue Flag;
1785   SmallVector<SDValue, 6> RetOps;
1786   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787   // Operand #1 = Bytes To Pop
1788   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1789                    MVT::i16));
1790
1791   // Copy the result values into the output registers.
1792   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793     CCValAssign &VA = RVLocs[i];
1794     assert(VA.isRegLoc() && "Can only return in registers!");
1795     SDValue ValToCopy = OutVals[i];
1796     EVT ValVT = ValToCopy.getValueType();
1797
1798     // Promote values to the appropriate types
1799     if (VA.getLocInfo() == CCValAssign::SExt)
1800       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801     else if (VA.getLocInfo() == CCValAssign::ZExt)
1802       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803     else if (VA.getLocInfo() == CCValAssign::AExt)
1804       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805     else if (VA.getLocInfo() == CCValAssign::BCvt)
1806       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1807
1808     // If this is x86-64, and we disabled SSE, we can't return FP values,
1809     // or SSE or MMX vectors.
1810     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813       report_fatal_error("SSE register return with SSE disabled");
1814     }
1815     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1816     // llvm-gcc has never done it right and no one has noticed, so this
1817     // should be OK for now.
1818     if (ValVT == MVT::f64 &&
1819         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820       report_fatal_error("SSE2 register return with SSE2 disabled");
1821
1822     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823     // the RET instruction and handled by the FP Stackifier.
1824     if (VA.getLocReg() == X86::ST0 ||
1825         VA.getLocReg() == X86::ST1) {
1826       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827       // change the value to the FP stack register class.
1828       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830       RetOps.push_back(ValToCopy);
1831       // Don't emit a copytoreg.
1832       continue;
1833     }
1834
1835     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836     // which is returned in RAX / RDX.
1837     if (Subtarget->is64Bit()) {
1838       if (ValVT == MVT::x86mmx) {
1839         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1842                                   ValToCopy);
1843           // If we don't have SSE2 available, convert to v4f32 so the generated
1844           // register is legal.
1845           if (!Subtarget->hasSSE2())
1846             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1847         }
1848       }
1849     }
1850
1851     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852     Flag = Chain.getValue(1);
1853     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1854   }
1855
1856   // The x86-64 ABIs require that for returning structs by value we copy
1857   // the sret argument into %rax/%eax (depending on ABI) for the return.
1858   // Win32 requires us to put the sret argument to %eax as well.
1859   // We saved the argument into a virtual register in the entry block,
1860   // so now we copy the value out and into %rax/%eax.
1861   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863     MachineFunction &MF = DAG.getMachineFunction();
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     assert(Reg &&
1867            "SRetReturnReg should have been set in LowerFormalArguments().");
1868     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1869
1870     unsigned RetValReg
1871         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872           X86::RAX : X86::EAX;
1873     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874     Flag = Chain.getValue(1);
1875
1876     // RAX/EAX now acts like a return value.
1877     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1878   }
1879
1880   RetOps[0] = Chain;  // Update chain.
1881
1882   // Add the flag if we have it.
1883   if (Flag.getNode())
1884     RetOps.push_back(Flag);
1885
1886   return DAG.getNode(X86ISD::RET_FLAG, dl,
1887                      MVT::Other, &RetOps[0], RetOps.size());
1888 }
1889
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891   if (N->getNumValues() != 1)
1892     return false;
1893   if (!N->hasNUsesOfValue(1, 0))
1894     return false;
1895
1896   SDValue TCChain = Chain;
1897   SDNode *Copy = *N->use_begin();
1898   if (Copy->getOpcode() == ISD::CopyToReg) {
1899     // If the copy has a glue operand, we conservatively assume it isn't safe to
1900     // perform a tail call.
1901     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1902       return false;
1903     TCChain = Copy->getOperand(0);
1904   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1905     return false;
1906
1907   bool HasRet = false;
1908   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1909        UI != UE; ++UI) {
1910     if (UI->getOpcode() != X86ISD::RET_FLAG)
1911       return false;
1912     HasRet = true;
1913   }
1914
1915   if (!HasRet)
1916     return false;
1917
1918   Chain = TCChain;
1919   return true;
1920 }
1921
1922 MVT
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924                                             ISD::NodeType ExtendKind) const {
1925   MVT ReturnMVT;
1926   // TODO: Is this also valid on 32-bit?
1927   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928     ReturnMVT = MVT::i8;
1929   else
1930     ReturnMVT = MVT::i32;
1931
1932   MVT MinVT = getRegisterType(ReturnMVT);
1933   return VT.bitsLT(MinVT) ? MinVT : VT;
1934 }
1935
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1938 ///
1939 SDValue
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941                                    CallingConv::ID CallConv, bool isVarArg,
1942                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1943                                    SDLoc dl, SelectionDAG &DAG,
1944                                    SmallVectorImpl<SDValue> &InVals) const {
1945
1946   // Assign locations to each value returned by this call.
1947   SmallVector<CCValAssign, 16> RVLocs;
1948   bool Is64Bit = Subtarget->is64Bit();
1949   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950                  getTargetMachine(), RVLocs, *DAG.getContext());
1951   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1952
1953   // Copy all of the result registers out of their specified physreg.
1954   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955     CCValAssign &VA = RVLocs[i];
1956     EVT CopyVT = VA.getValVT();
1957
1958     // If this is x86-64, and we disabled SSE, we can't return FP values
1959     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961       report_fatal_error("SSE register return with SSE disabled");
1962     }
1963
1964     SDValue Val;
1965
1966     // If this is a call to a function that returns an fp value on the floating
1967     // point stack, we must guarantee the value is popped from the stack, so
1968     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969     // if the return value is not used. We use the FpPOP_RETVAL instruction
1970     // instead.
1971     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972       // If we prefer to use the value in xmm registers, copy it out as f80 and
1973       // use a truncate to move it from fp stack reg to xmm reg.
1974       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975       SDValue Ops[] = { Chain, InFlag };
1976       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977                                          MVT::Other, MVT::Glue, Ops), 1);
1978       Val = Chain.getValue(0);
1979
1980       // Round the f80 to the right size, which also moves it to the appropriate
1981       // xmm register.
1982       if (CopyVT != VA.getValVT())
1983         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984                           // This truncation won't change the value.
1985                           DAG.getIntPtrConstant(1));
1986     } else {
1987       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988                                  CopyVT, InFlag).getValue(1);
1989       Val = Chain.getValue(0);
1990     }
1991     InFlag = Chain.getValue(2);
1992     InVals.push_back(Val);
1993   }
1994
1995   return Chain;
1996 }
1997
1998 //===----------------------------------------------------------------------===//
1999 //                C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 //  StdCall calling convention seems to be standard for many Windows' API
2002 //  routines and around. It differs from C calling convention just a little:
2003 //  callee should clean up the stack, not caller. Symbols should be also
2004 //  decorated in some fancy way :) It doesn't support any vector arguments.
2005 //  For info on fast calling convention see Fast Calling Convention (tail call)
2006 //  implementation LowerX86_32FastCCCallTo.
2007
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2009 /// semantics.
2010 enum StructReturnType {
2011   NotStructReturn,
2012   RegStructReturn,
2013   StackStructReturn
2014 };
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2017   if (Outs.empty())
2018     return NotStructReturn;
2019
2020   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021   if (!Flags.isSRet())
2022     return NotStructReturn;
2023   if (Flags.isInReg())
2024     return RegStructReturn;
2025   return StackStructReturn;
2026 }
2027
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2032   if (Ins.empty())
2033     return NotStructReturn;
2034
2035   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036   if (!Flags.isSRet())
2037     return NotStructReturn;
2038   if (Flags.isInReg())
2039     return RegStructReturn;
2040   return StackStructReturn;
2041 }
2042
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2047 static SDValue
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2050                           SDLoc dl) {
2051   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2052
2053   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054                        /*isVolatile*/false, /*AlwaysInline=*/true,
2055                        MachinePointerInfo(), MachinePointerInfo());
2056 }
2057
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062           CC == CallingConv::HiPE);
2063 }
2064
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068           CC == CallingConv::X86_64_SysV);
2069 }
2070
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2073     return false;
2074
2075   CallSite CS(CI);
2076   CallingConv::ID CalleeCC = CS.getCallingConv();
2077   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2078     return false;
2079
2080   return true;
2081 }
2082
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086                                    bool GuaranteedTailCallOpt) {
2087   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2088 }
2089
2090 SDValue
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092                                     CallingConv::ID CallConv,
2093                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2094                                     SDLoc dl, SelectionDAG &DAG,
2095                                     const CCValAssign &VA,
2096                                     MachineFrameInfo *MFI,
2097                                     unsigned i) const {
2098   // Create the nodes corresponding to a load from this parameter slot.
2099   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101                               getTargetMachine().Options.GuaranteedTailCallOpt);
2102   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2103   EVT ValVT;
2104
2105   // If value is passed by pointer we have address passed instead of the value
2106   // itself.
2107   if (VA.getLocInfo() == CCValAssign::Indirect)
2108     ValVT = VA.getLocVT();
2109   else
2110     ValVT = VA.getValVT();
2111
2112   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113   // changed with more analysis.
2114   // In case of tail call optimization mark all arguments mutable. Since they
2115   // could be overwritten by lowering of arguments in case of a tail call.
2116   if (Flags.isByVal()) {
2117     unsigned Bytes = Flags.getByValSize();
2118     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120     return DAG.getFrameIndex(FI, getPointerTy());
2121   } else {
2122     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123                                     VA.getLocMemOffset(), isImmutable);
2124     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125     return DAG.getLoad(ValVT, dl, Chain, FIN,
2126                        MachinePointerInfo::getFixedStack(FI),
2127                        false, false, false, 0);
2128   }
2129 }
2130
2131 SDValue
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133                                         CallingConv::ID CallConv,
2134                                         bool isVarArg,
2135                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2136                                         SDLoc dl,
2137                                         SelectionDAG &DAG,
2138                                         SmallVectorImpl<SDValue> &InVals)
2139                                           const {
2140   MachineFunction &MF = DAG.getMachineFunction();
2141   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2142
2143   const Function* Fn = MF.getFunction();
2144   if (Fn->hasExternalLinkage() &&
2145       Subtarget->isTargetCygMing() &&
2146       Fn->getName() == "main")
2147     FuncInfo->setForceFramePointer(true);
2148
2149   MachineFrameInfo *MFI = MF.getFrameInfo();
2150   bool Is64Bit = Subtarget->is64Bit();
2151   bool IsWindows = Subtarget->isTargetWindows();
2152   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2153
2154   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155          "Var args not supported with calling convention fastcc, ghc or hipe");
2156
2157   // Assign locations to all of the incoming arguments.
2158   SmallVector<CCValAssign, 16> ArgLocs;
2159   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160                  ArgLocs, *DAG.getContext());
2161
2162   // Allocate shadow area for Win64
2163   if (IsWin64)
2164     CCInfo.AllocateStack(32, 8);
2165
2166   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2167
2168   unsigned LastVal = ~0U;
2169   SDValue ArgValue;
2170   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171     CCValAssign &VA = ArgLocs[i];
2172     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2173     // places.
2174     assert(VA.getValNo() != LastVal &&
2175            "Don't support value assigned to multiple locs yet");
2176     (void)LastVal;
2177     LastVal = VA.getValNo();
2178
2179     if (VA.isRegLoc()) {
2180       EVT RegVT = VA.getLocVT();
2181       const TargetRegisterClass *RC;
2182       if (RegVT == MVT::i32)
2183         RC = &X86::GR32RegClass;
2184       else if (Is64Bit && RegVT == MVT::i64)
2185         RC = &X86::GR64RegClass;
2186       else if (RegVT == MVT::f32)
2187         RC = &X86::FR32RegClass;
2188       else if (RegVT == MVT::f64)
2189         RC = &X86::FR64RegClass;
2190       else if (RegVT.is512BitVector())
2191         RC = &X86::VR512RegClass;
2192       else if (RegVT.is256BitVector())
2193         RC = &X86::VR256RegClass;
2194       else if (RegVT.is128BitVector())
2195         RC = &X86::VR128RegClass;
2196       else if (RegVT == MVT::x86mmx)
2197         RC = &X86::VR64RegClass;
2198       else if (RegVT == MVT::v8i1)
2199         RC = &X86::VK8RegClass;
2200       else if (RegVT == MVT::v16i1)
2201         RC = &X86::VK16RegClass;
2202       else
2203         llvm_unreachable("Unknown argument type!");
2204
2205       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2207
2208       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2210       // right size.
2211       if (VA.getLocInfo() == CCValAssign::SExt)
2212         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213                                DAG.getValueType(VA.getValVT()));
2214       else if (VA.getLocInfo() == CCValAssign::ZExt)
2215         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216                                DAG.getValueType(VA.getValVT()));
2217       else if (VA.getLocInfo() == CCValAssign::BCvt)
2218         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2219
2220       if (VA.isExtInLoc()) {
2221         // Handle MMX values passed in XMM regs.
2222         if (RegVT.isVector())
2223           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2224         else
2225           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2226       }
2227     } else {
2228       assert(VA.isMemLoc());
2229       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2230     }
2231
2232     // If value is passed via pointer - do a load.
2233     if (VA.getLocInfo() == CCValAssign::Indirect)
2234       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235                              MachinePointerInfo(), false, false, false, 0);
2236
2237     InVals.push_back(ArgValue);
2238   }
2239
2240   // The x86-64 ABIs require that for returning structs by value we copy
2241   // the sret argument into %rax/%eax (depending on ABI) for the return.
2242   // Win32 requires us to put the sret argument to %eax as well.
2243   // Save the argument into a virtual register so that we can access it
2244   // from the return points.
2245   if (MF.getFunction()->hasStructRetAttr() &&
2246       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248     unsigned Reg = FuncInfo->getSRetReturnReg();
2249     if (!Reg) {
2250       MVT PtrTy = getPointerTy();
2251       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252       FuncInfo->setSRetReturnReg(Reg);
2253     }
2254     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2256   }
2257
2258   unsigned StackSize = CCInfo.getNextStackOffset();
2259   // Align stack specially for tail calls.
2260   if (FuncIsMadeTailCallSafe(CallConv,
2261                              MF.getTarget().Options.GuaranteedTailCallOpt))
2262     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2263
2264   // If the function takes variable number of arguments, make a frame index for
2265   // the start of the first vararg value... for expansion of llvm.va_start.
2266   if (isVarArg) {
2267     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268                     CallConv != CallingConv::X86_ThisCall)) {
2269       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2270     }
2271     if (Is64Bit) {
2272       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2273
2274       // FIXME: We should really autogenerate these arrays
2275       static const uint16_t GPR64ArgRegsWin64[] = {
2276         X86::RCX, X86::RDX, X86::R8,  X86::R9
2277       };
2278       static const uint16_t GPR64ArgRegs64Bit[] = {
2279         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2280       };
2281       static const uint16_t XMMArgRegs64Bit[] = {
2282         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2284       };
2285       const uint16_t *GPR64ArgRegs;
2286       unsigned NumXMMRegs = 0;
2287
2288       if (IsWin64) {
2289         // The XMM registers which might contain var arg parameters are shadowed
2290         // in their paired GPR.  So we only need to save the GPR to their home
2291         // slots.
2292         TotalNumIntRegs = 4;
2293         GPR64ArgRegs = GPR64ArgRegsWin64;
2294       } else {
2295         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296         GPR64ArgRegs = GPR64ArgRegs64Bit;
2297
2298         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2299                                                 TotalNumXMMRegs);
2300       }
2301       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2302                                                        TotalNumIntRegs);
2303
2304       bool NoImplicitFloatOps = Fn->getAttributes().
2305         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307              "SSE register cannot be used when SSE is disabled!");
2308       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309                NoImplicitFloatOps) &&
2310              "SSE register cannot be used when SSE is disabled!");
2311       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312           !Subtarget->hasSSE1())
2313         // Kernel mode asks for SSE to be disabled, so don't push them
2314         // on the stack.
2315         TotalNumXMMRegs = 0;
2316
2317       if (IsWin64) {
2318         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319         // Get to the caller-allocated home save location.  Add 8 to account
2320         // for the return address.
2321         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322         FuncInfo->setRegSaveFrameIndex(
2323           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324         // Fixup to set vararg frame on shadow area (4 x i64).
2325         if (NumIntRegs < 4)
2326           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2327       } else {
2328         // For X86-64, if there are vararg parameters that are passed via
2329         // registers, then we must store them to their spots on the stack so
2330         // they may be loaded by deferencing the result of va_next.
2331         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333         FuncInfo->setRegSaveFrameIndex(
2334           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2335                                false));
2336       }
2337
2338       // Store the integer parameter registers.
2339       SmallVector<SDValue, 8> MemOps;
2340       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2341                                         getPointerTy());
2342       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345                                   DAG.getIntPtrConstant(Offset));
2346         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347                                      &X86::GR64RegClass);
2348         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2349         SDValue Store =
2350           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351                        MachinePointerInfo::getFixedStack(
2352                          FuncInfo->getRegSaveFrameIndex(), Offset),
2353                        false, false, 0);
2354         MemOps.push_back(Store);
2355         Offset += 8;
2356       }
2357
2358       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359         // Now store the XMM (fp + vector) parameter registers.
2360         SmallVector<SDValue, 11> SaveXMMOps;
2361         SaveXMMOps.push_back(Chain);
2362
2363         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365         SaveXMMOps.push_back(ALVal);
2366
2367         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368                                FuncInfo->getRegSaveFrameIndex()));
2369         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370                                FuncInfo->getVarArgsFPOffset()));
2371
2372         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374                                        &X86::VR128RegClass);
2375           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376           SaveXMMOps.push_back(Val);
2377         }
2378         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2379                                      MVT::Other,
2380                                      &SaveXMMOps[0], SaveXMMOps.size()));
2381       }
2382
2383       if (!MemOps.empty())
2384         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385                             &MemOps[0], MemOps.size());
2386     }
2387   }
2388
2389   // Some CCs need callee pop.
2390   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2393   } else {
2394     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395     // If this is an sret function, the return should pop the hidden pointer.
2396     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397         argsAreStructReturn(Ins) == StackStructReturn)
2398       FuncInfo->setBytesToPopOnReturn(4);
2399   }
2400
2401   if (!Is64Bit) {
2402     // RegSaveFrameIndex is X86-64 only.
2403     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404     if (CallConv == CallingConv::X86_FastCall ||
2405         CallConv == CallingConv::X86_ThisCall)
2406       // fastcc functions can't have varargs.
2407       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2408   }
2409
2410   FuncInfo->setArgumentStackSize(StackSize);
2411
2412   return Chain;
2413 }
2414
2415 SDValue
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417                                     SDValue StackPtr, SDValue Arg,
2418                                     SDLoc dl, SelectionDAG &DAG,
2419                                     const CCValAssign &VA,
2420                                     ISD::ArgFlagsTy Flags) const {
2421   unsigned LocMemOffset = VA.getLocMemOffset();
2422   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424   if (Flags.isByVal())
2425     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2426
2427   return DAG.getStore(Chain, dl, Arg, PtrOff,
2428                       MachinePointerInfo::getStack(LocMemOffset),
2429                       false, false, 0);
2430 }
2431
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2434 SDValue
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436                                            SDValue &OutRetAddr, SDValue Chain,
2437                                            bool IsTailCall, bool Is64Bit,
2438                                            int FPDiff, SDLoc dl) const {
2439   // Adjust the Return address stack slot.
2440   EVT VT = getPointerTy();
2441   OutRetAddr = getReturnAddressFrameIndex(DAG);
2442
2443   // Load the "old" Return address.
2444   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445                            false, false, false, 0);
2446   return SDValue(OutRetAddr.getNode(), 1);
2447 }
2448
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2451 static SDValue
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2455   // Store the return address to the appropriate stack slot.
2456   if (!FPDiff) return Chain;
2457   // Calculate the new stack slot for the return address.
2458   int NewReturnAddrFI =
2459     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2460                                          false);
2461   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2464                        false, false, 0);
2465   return Chain;
2466 }
2467
2468 SDValue
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470                              SmallVectorImpl<SDValue> &InVals) const {
2471   SelectionDAG &DAG                     = CLI.DAG;
2472   SDLoc &dl                             = CLI.DL;
2473   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2475   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2476   SDValue Chain                         = CLI.Chain;
2477   SDValue Callee                        = CLI.Callee;
2478   CallingConv::ID CallConv              = CLI.CallConv;
2479   bool &isTailCall                      = CLI.IsTailCall;
2480   bool isVarArg                         = CLI.IsVarArg;
2481
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   bool Is64Bit        = Subtarget->is64Bit();
2484   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2485   bool IsWindows      = Subtarget->isTargetWindows();
2486   StructReturnType SR = callIsStructReturn(Outs);
2487   bool IsSibcall      = false;
2488
2489   if (MF.getTarget().Options.DisableTailCalls)
2490     isTailCall = false;
2491
2492   if (isTailCall) {
2493     // Check if it's really possible to do a tail call.
2494     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495                     isVarArg, SR != NotStructReturn,
2496                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497                     Outs, OutVals, Ins, DAG);
2498
2499     // Sibcalls are automatically detected tailcalls which do not require
2500     // ABI changes.
2501     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2502       IsSibcall = true;
2503
2504     if (isTailCall)
2505       ++NumTailCalls;
2506   }
2507
2508   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509          "Var args not supported with calling convention fastcc, ghc or hipe");
2510
2511   // Analyze operands of the call, assigning locations to each operand.
2512   SmallVector<CCValAssign, 16> ArgLocs;
2513   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514                  ArgLocs, *DAG.getContext());
2515
2516   // Allocate shadow area for Win64
2517   if (IsWin64)
2518     CCInfo.AllocateStack(32, 8);
2519
2520   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2521
2522   // Get a count of how many bytes are to be pushed on the stack.
2523   unsigned NumBytes = CCInfo.getNextStackOffset();
2524   if (IsSibcall)
2525     // This is a sibcall. The memory operands are available in caller's
2526     // own caller's stack.
2527     NumBytes = 0;
2528   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529            IsTailCallConvention(CallConv))
2530     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2531
2532   int FPDiff = 0;
2533   if (isTailCall && !IsSibcall) {
2534     // Lower arguments at fp - stackoffset + fpdiff.
2535     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2537
2538     FPDiff = NumBytesCallerPushed - NumBytes;
2539
2540     // Set the delta of movement of the returnaddr stackslot.
2541     // But only set if delta is greater than previous delta.
2542     if (FPDiff < X86Info->getTCReturnAddrDelta())
2543       X86Info->setTCReturnAddrDelta(FPDiff);
2544   }
2545
2546   if (!IsSibcall)
2547     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2548                                  dl);
2549
2550   SDValue RetAddrFrIdx;
2551   // Load return address for tail calls.
2552   if (isTailCall && FPDiff)
2553     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554                                     Is64Bit, FPDiff, dl);
2555
2556   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557   SmallVector<SDValue, 8> MemOpChains;
2558   SDValue StackPtr;
2559
2560   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2561   // of tail call optimization arguments are handle later.
2562   const X86RegisterInfo *RegInfo =
2563     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565     CCValAssign &VA = ArgLocs[i];
2566     EVT RegVT = VA.getLocVT();
2567     SDValue Arg = OutVals[i];
2568     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569     bool isByVal = Flags.isByVal();
2570
2571     // Promote the value if needed.
2572     switch (VA.getLocInfo()) {
2573     default: llvm_unreachable("Unknown loc info!");
2574     case CCValAssign::Full: break;
2575     case CCValAssign::SExt:
2576       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2577       break;
2578     case CCValAssign::ZExt:
2579       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2580       break;
2581     case CCValAssign::AExt:
2582       if (RegVT.is128BitVector()) {
2583         // Special case: passing MMX values in XMM registers.
2584         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2587       } else
2588         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2589       break;
2590     case CCValAssign::BCvt:
2591       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2592       break;
2593     case CCValAssign::Indirect: {
2594       // Store the argument.
2595       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598                            MachinePointerInfo::getFixedStack(FI),
2599                            false, false, 0);
2600       Arg = SpillSlot;
2601       break;
2602     }
2603     }
2604
2605     if (VA.isRegLoc()) {
2606       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607       if (isVarArg && IsWin64) {
2608         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609         // shadow reg if callee is a varargs function.
2610         unsigned ShadowReg = 0;
2611         switch (VA.getLocReg()) {
2612         case X86::XMM0: ShadowReg = X86::RCX; break;
2613         case X86::XMM1: ShadowReg = X86::RDX; break;
2614         case X86::XMM2: ShadowReg = X86::R8; break;
2615         case X86::XMM3: ShadowReg = X86::R9; break;
2616         }
2617         if (ShadowReg)
2618           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2619       }
2620     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621       assert(VA.isMemLoc());
2622       if (StackPtr.getNode() == 0)
2623         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2624                                       getPointerTy());
2625       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626                                              dl, DAG, VA, Flags));
2627     }
2628   }
2629
2630   if (!MemOpChains.empty())
2631     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632                         &MemOpChains[0], MemOpChains.size());
2633
2634   if (Subtarget->isPICStyleGOT()) {
2635     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2636     // GOT pointer.
2637     if (!isTailCall) {
2638       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2640     } else {
2641       // If we are tail calling and generating PIC/GOT style code load the
2642       // address of the callee into ECX. The value in ecx is used as target of
2643       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644       // for tail calls on PIC/GOT architectures. Normally we would just put the
2645       // address of GOT into ebx and then call target@PLT. But for tail calls
2646       // ebx would be restored (since ebx is callee saved) before jumping to the
2647       // target@PLT.
2648
2649       // Note: The actual moving to ECX is done further down.
2650       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652           !G->getGlobal()->hasProtectedVisibility())
2653         Callee = LowerGlobalAddress(Callee, DAG);
2654       else if (isa<ExternalSymbolSDNode>(Callee))
2655         Callee = LowerExternalSymbol(Callee, DAG);
2656     }
2657   }
2658
2659   if (Is64Bit && isVarArg && !IsWin64) {
2660     // From AMD64 ABI document:
2661     // For calls that may call functions that use varargs or stdargs
2662     // (prototype-less calls or calls to functions containing ellipsis (...) in
2663     // the declaration) %al is used as hidden argument to specify the number
2664     // of SSE registers used. The contents of %al do not need to match exactly
2665     // the number of registers, but must be an ubound on the number of SSE
2666     // registers used and is in the range 0 - 8 inclusive.
2667
2668     // Count the number of XMM registers allocated.
2669     static const uint16_t XMMArgRegs[] = {
2670       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2672     };
2673     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675            && "SSE registers cannot be used when SSE is disabled");
2676
2677     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2679   }
2680
2681   // For tail calls lower the arguments to the 'real' stack slot.
2682   if (isTailCall) {
2683     // Force all the incoming stack arguments to be loaded from the stack
2684     // before any new outgoing arguments are stored to the stack, because the
2685     // outgoing stack slots may alias the incoming argument stack slots, and
2686     // the alias isn't otherwise explicit. This is slightly more conservative
2687     // than necessary, because it means that each store effectively depends
2688     // on every argument instead of just those arguments it would clobber.
2689     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2690
2691     SmallVector<SDValue, 8> MemOpChains2;
2692     SDValue FIN;
2693     int FI = 0;
2694     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696         CCValAssign &VA = ArgLocs[i];
2697         if (VA.isRegLoc())
2698           continue;
2699         assert(VA.isMemLoc());
2700         SDValue Arg = OutVals[i];
2701         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702         // Create frame index.
2703         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706         FIN = DAG.getFrameIndex(FI, getPointerTy());
2707
2708         if (Flags.isByVal()) {
2709           // Copy relative to framepointer.
2710           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711           if (StackPtr.getNode() == 0)
2712             StackPtr = DAG.getCopyFromReg(Chain, dl,
2713                                           RegInfo->getStackRegister(),
2714                                           getPointerTy());
2715           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2716
2717           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2718                                                            ArgChain,
2719                                                            Flags, DAG, dl));
2720         } else {
2721           // Store relative to framepointer.
2722           MemOpChains2.push_back(
2723             DAG.getStore(ArgChain, dl, Arg, FIN,
2724                          MachinePointerInfo::getFixedStack(FI),
2725                          false, false, 0));
2726         }
2727       }
2728     }
2729
2730     if (!MemOpChains2.empty())
2731       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732                           &MemOpChains2[0], MemOpChains2.size());
2733
2734     // Store the return address to the appropriate stack slot.
2735     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736                                      getPointerTy(), RegInfo->getSlotSize(),
2737                                      FPDiff, dl);
2738   }
2739
2740   // Build a sequence of copy-to-reg nodes chained together with token chain
2741   // and flag operands which copy the outgoing args into registers.
2742   SDValue InFlag;
2743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745                              RegsToPass[i].second, InFlag);
2746     InFlag = Chain.getValue(1);
2747   }
2748
2749   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751     // In the 64-bit large code model, we have to make all calls
2752     // through a register, since the call instruction's 32-bit
2753     // pc-relative offset may not be large enough to hold the whole
2754     // address.
2755   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756     // If the callee is a GlobalAddress node (quite common, every direct call
2757     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2758     // it.
2759
2760     // We should use extra load for direct calls to dllimported functions in
2761     // non-JIT mode.
2762     const GlobalValue *GV = G->getGlobal();
2763     if (!GV->hasDLLImportLinkage()) {
2764       unsigned char OpFlags = 0;
2765       bool ExtraLoad = false;
2766       unsigned WrapperKind = ISD::DELETED_NODE;
2767
2768       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769       // external symbols most go through the PLT in PIC mode.  If the symbol
2770       // has hidden or protected visibility, or if it is static or local, then
2771       // we don't need to use the PLT - we can directly call it.
2772       if (Subtarget->isTargetELF() &&
2773           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775         OpFlags = X86II::MO_PLT;
2776       } else if (Subtarget->isPICStyleStubAny() &&
2777                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778                  (!Subtarget->getTargetTriple().isMacOSX() ||
2779                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780         // PC-relative references to external symbols should go through $stub,
2781         // unless we're building with the leopard linker or later, which
2782         // automatically synthesizes these stubs.
2783         OpFlags = X86II::MO_DARWIN_STUB;
2784       } else if (Subtarget->isPICStyleRIPRel() &&
2785                  isa<Function>(GV) &&
2786                  cast<Function>(GV)->getAttributes().
2787                    hasAttribute(AttributeSet::FunctionIndex,
2788                                 Attribute::NonLazyBind)) {
2789         // If the function is marked as non-lazy, generate an indirect call
2790         // which loads from the GOT directly. This avoids runtime overhead
2791         // at the cost of eager binding (and one extra byte of encoding).
2792         OpFlags = X86II::MO_GOTPCREL;
2793         WrapperKind = X86ISD::WrapperRIP;
2794         ExtraLoad = true;
2795       }
2796
2797       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798                                           G->getOffset(), OpFlags);
2799
2800       // Add a wrapper if needed.
2801       if (WrapperKind != ISD::DELETED_NODE)
2802         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803       // Add extra indirection if needed.
2804       if (ExtraLoad)
2805         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806                              MachinePointerInfo::getGOT(),
2807                              false, false, false, 0);
2808     }
2809   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810     unsigned char OpFlags = 0;
2811
2812     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813     // external symbols should go through the PLT.
2814     if (Subtarget->isTargetELF() &&
2815         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816       OpFlags = X86II::MO_PLT;
2817     } else if (Subtarget->isPICStyleStubAny() &&
2818                (!Subtarget->getTargetTriple().isMacOSX() ||
2819                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820       // PC-relative references to external symbols should go through $stub,
2821       // unless we're building with the leopard linker or later, which
2822       // automatically synthesizes these stubs.
2823       OpFlags = X86II::MO_DARWIN_STUB;
2824     }
2825
2826     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2827                                          OpFlags);
2828   }
2829
2830   // Returns a chain & a flag for retval copy to use.
2831   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832   SmallVector<SDValue, 8> Ops;
2833
2834   if (!IsSibcall && isTailCall) {
2835     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2837     InFlag = Chain.getValue(1);
2838   }
2839
2840   Ops.push_back(Chain);
2841   Ops.push_back(Callee);
2842
2843   if (isTailCall)
2844     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2845
2846   // Add argument registers to the end of the list so that they are known live
2847   // into the call.
2848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850                                   RegsToPass[i].second.getValueType()));
2851
2852   // Add a register mask operand representing the call-preserved registers.
2853   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855   assert(Mask && "Missing call preserved mask for calling convention");
2856   Ops.push_back(DAG.getRegisterMask(Mask));
2857
2858   if (InFlag.getNode())
2859     Ops.push_back(InFlag);
2860
2861   if (isTailCall) {
2862     // We used to do:
2863     //// If this is the first return lowered for this function, add the regs
2864     //// to the liveout set for the function.
2865     // This isn't right, although it's probably harmless on x86; liveouts
2866     // should be computed from returns not tail calls.  Consider a void
2867     // function making a tail call to a function returning int.
2868     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2869   }
2870
2871   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872   InFlag = Chain.getValue(1);
2873
2874   // Create the CALLSEQ_END node.
2875   unsigned NumBytesForCalleeToPush;
2876   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877                        getTargetMachine().Options.GuaranteedTailCallOpt))
2878     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2879   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880            SR == StackStructReturn)
2881     // If this is a call to a struct-return function, the callee
2882     // pops the hidden struct pointer, so we have to push it back.
2883     // This is common for Darwin/X86, Linux & Mingw32 targets.
2884     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885     NumBytesForCalleeToPush = 4;
2886   else
2887     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2888
2889   // Returns a flag for retval copy to use.
2890   if (!IsSibcall) {
2891     Chain = DAG.getCALLSEQ_END(Chain,
2892                                DAG.getIntPtrConstant(NumBytes, true),
2893                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2894                                                      true),
2895                                InFlag, dl);
2896     InFlag = Chain.getValue(1);
2897   }
2898
2899   // Handle result values, copying them out of physregs into vregs that we
2900   // return.
2901   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902                          Ins, dl, DAG, InVals);
2903 }
2904
2905 //===----------------------------------------------------------------------===//
2906 //                Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2908
2909 //  Like std call, callee cleans arguments, convention except that ECX is
2910 //  reserved for storing the tail called function address. Only 2 registers are
2911 //  free for argument passing (inreg). Tail call optimization is performed
2912 //  provided:
2913 //                * tailcallopt is enabled
2914 //                * caller/callee are fastcc
2915 //  On X86_64 architecture with GOT-style position independent code only local
2916 //  (within module) calls are supported at the moment.
2917 //  To keep the stack aligned according to platform abi the function
2918 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 //  If a tail called function callee has more arguments than the caller the
2921 //  caller needs to make sure that there is room to move the RETADDR to. This is
2922 //  achieved by reserving an area the size of the argument delta right after the
2923 //  original REtADDR, but before the saved framepointer or the spilled registers
2924 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2925 //  stack layout:
2926 //    arg1
2927 //    arg2
2928 //    RETADDR
2929 //    [ new RETADDR
2930 //      move area ]
2931 //    (possible EBP)
2932 //    ESI
2933 //    EDI
2934 //    local1 ..
2935
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2938 unsigned
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940                                                SelectionDAG& DAG) const {
2941   MachineFunction &MF = DAG.getMachineFunction();
2942   const TargetMachine &TM = MF.getTarget();
2943   const X86RegisterInfo *RegInfo =
2944     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946   unsigned StackAlignment = TFI.getStackAlignment();
2947   uint64_t AlignMask = StackAlignment - 1;
2948   int64_t Offset = StackSize;
2949   unsigned SlotSize = RegInfo->getSlotSize();
2950   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951     // Number smaller than 12 so just add the difference.
2952     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2953   } else {
2954     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955     Offset = ((~AlignMask) & Offset) + StackAlignment +
2956       (StackAlignment-SlotSize);
2957   }
2958   return Offset;
2959 }
2960
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2964 static
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967                          const X86InstrInfo *TII) {
2968   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2969   int FI = INT_MAX;
2970   if (Arg.getOpcode() == ISD::CopyFromReg) {
2971     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972     if (!TargetRegisterInfo::isVirtualRegister(VR))
2973       return false;
2974     MachineInstr *Def = MRI->getVRegDef(VR);
2975     if (!Def)
2976       return false;
2977     if (!Flags.isByVal()) {
2978       if (!TII->isLoadFromStackSlot(Def, FI))
2979         return false;
2980     } else {
2981       unsigned Opcode = Def->getOpcode();
2982       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983           Def->getOperand(1).isFI()) {
2984         FI = Def->getOperand(1).getIndex();
2985         Bytes = Flags.getByValSize();
2986       } else
2987         return false;
2988     }
2989   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990     if (Flags.isByVal())
2991       // ByVal argument is passed in as a pointer but it's now being
2992       // dereferenced. e.g.
2993       // define @foo(%struct.X* %A) {
2994       //   tail call @bar(%struct.X* byval %A)
2995       // }
2996       return false;
2997     SDValue Ptr = Ld->getBasePtr();
2998     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2999     if (!FINode)
3000       return false;
3001     FI = FINode->getIndex();
3002   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004     FI = FINode->getIndex();
3005     Bytes = Flags.getByValSize();
3006   } else
3007     return false;
3008
3009   assert(FI != INT_MAX);
3010   if (!MFI->isFixedObjectIndex(FI))
3011     return false;
3012   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3013 }
3014
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3018 bool
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020                                                      CallingConv::ID CalleeCC,
3021                                                      bool isVarArg,
3022                                                      bool isCalleeStructRet,
3023                                                      bool isCallerStructRet,
3024                                                      Type *RetTy,
3025                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3026                                     const SmallVectorImpl<SDValue> &OutVals,
3027                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3028                                                      SelectionDAG &DAG) const {
3029   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3030     return false;
3031
3032   // If -tailcallopt is specified, make fastcc functions tail-callable.
3033   const MachineFunction &MF = DAG.getMachineFunction();
3034   const Function *CallerF = MF.getFunction();
3035
3036   // If the function return type is x86_fp80 and the callee return type is not,
3037   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038   // perform a tailcall optimization here.
3039   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3040     return false;
3041
3042   CallingConv::ID CallerCC = CallerF->getCallingConv();
3043   bool CCMatch = CallerCC == CalleeCC;
3044   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3046
3047   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048     if (IsTailCallConvention(CalleeCC) && CCMatch)
3049       return true;
3050     return false;
3051   }
3052
3053   // Look for obvious safe cases to perform tail call optimization that do not
3054   // require ABI changes. This is what gcc calls sibcall.
3055
3056   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057   // emit a special epilogue.
3058   const X86RegisterInfo *RegInfo =
3059     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060   if (RegInfo->needsStackRealignment(MF))
3061     return false;
3062
3063   // Also avoid sibcall optimization if either caller or callee uses struct
3064   // return semantics.
3065   if (isCalleeStructRet || isCallerStructRet)
3066     return false;
3067
3068   // An stdcall caller is expected to clean up its arguments; the callee
3069   // isn't going to do that.
3070   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3071     return false;
3072
3073   // Do not sibcall optimize vararg calls unless all arguments are passed via
3074   // registers.
3075   if (isVarArg && !Outs.empty()) {
3076
3077     // Optimizing for varargs on Win64 is unlikely to be safe without
3078     // additional testing.
3079     if (IsCalleeWin64 || IsCallerWin64)
3080       return false;
3081
3082     SmallVector<CCValAssign, 16> ArgLocs;
3083     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084                    getTargetMachine(), ArgLocs, *DAG.getContext());
3085
3086     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088       if (!ArgLocs[i].isRegLoc())
3089         return false;
3090   }
3091
3092   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3094   // this into a sibcall.
3095   bool Unused = false;
3096   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3097     if (!Ins[i].Used) {
3098       Unused = true;
3099       break;
3100     }
3101   }
3102   if (Unused) {
3103     SmallVector<CCValAssign, 16> RVLocs;
3104     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105                    getTargetMachine(), RVLocs, *DAG.getContext());
3106     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108       CCValAssign &VA = RVLocs[i];
3109       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3110         return false;
3111     }
3112   }
3113
3114   // If the calling conventions do not match, then we'd better make sure the
3115   // results are returned in the same way as what the caller expects.
3116   if (!CCMatch) {
3117     SmallVector<CCValAssign, 16> RVLocs1;
3118     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119                     getTargetMachine(), RVLocs1, *DAG.getContext());
3120     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3121
3122     SmallVector<CCValAssign, 16> RVLocs2;
3123     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124                     getTargetMachine(), RVLocs2, *DAG.getContext());
3125     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3126
3127     if (RVLocs1.size() != RVLocs2.size())
3128       return false;
3129     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3131         return false;
3132       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3133         return false;
3134       if (RVLocs1[i].isRegLoc()) {
3135         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3136           return false;
3137       } else {
3138         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3139           return false;
3140       }
3141     }
3142   }
3143
3144   // If the callee takes no arguments then go on to check the results of the
3145   // call.
3146   if (!Outs.empty()) {
3147     // Check if stack adjustment is needed. For now, do not do this if any
3148     // argument is passed on the stack.
3149     SmallVector<CCValAssign, 16> ArgLocs;
3150     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151                    getTargetMachine(), ArgLocs, *DAG.getContext());
3152
3153     // Allocate shadow area for Win64
3154     if (IsCalleeWin64)
3155       CCInfo.AllocateStack(32, 8);
3156
3157     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158     if (CCInfo.getNextStackOffset()) {
3159       MachineFunction &MF = DAG.getMachineFunction();
3160       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3161         return false;
3162
3163       // Check if the arguments are already laid out in the right way as
3164       // the caller's fixed stack objects.
3165       MachineFrameInfo *MFI = MF.getFrameInfo();
3166       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167       const X86InstrInfo *TII =
3168         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170         CCValAssign &VA = ArgLocs[i];
3171         SDValue Arg = OutVals[i];
3172         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173         if (VA.getLocInfo() == CCValAssign::Indirect)
3174           return false;
3175         if (!VA.isRegLoc()) {
3176           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3177                                    MFI, MRI, TII))
3178             return false;
3179         }
3180       }
3181     }
3182
3183     // If the tailcall address may be in a register, then make sure it's
3184     // possible to register allocate for it. In 32-bit, the call address can
3185     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186     // callee-saved registers are restored. These happen to be the same
3187     // registers used to pass 'inreg' arguments so watch out for those.
3188     if (!Subtarget->is64Bit() &&
3189         ((!isa<GlobalAddressSDNode>(Callee) &&
3190           !isa<ExternalSymbolSDNode>(Callee)) ||
3191          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192       unsigned NumInRegs = 0;
3193       // In PIC we need an extra register to formulate the address computation
3194       // for the callee.
3195       unsigned MaxInRegs =
3196           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3197
3198       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199         CCValAssign &VA = ArgLocs[i];
3200         if (!VA.isRegLoc())
3201           continue;
3202         unsigned Reg = VA.getLocReg();
3203         switch (Reg) {
3204         default: break;
3205         case X86::EAX: case X86::EDX: case X86::ECX:
3206           if (++NumInRegs == MaxInRegs)
3207             return false;
3208           break;
3209         }
3210       }
3211     }
3212   }
3213
3214   return true;
3215 }
3216
3217 FastISel *
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219                                   const TargetLibraryInfo *libInfo) const {
3220   return X86::createFastISel(funcInfo, libInfo);
3221 }
3222
3223 //===----------------------------------------------------------------------===//
3224 //                           Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3226
3227 static bool MayFoldLoad(SDValue Op) {
3228   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3229 }
3230
3231 static bool MayFoldIntoStore(SDValue Op) {
3232   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3233 }
3234
3235 static bool isTargetShuffle(unsigned Opcode) {
3236   switch(Opcode) {
3237   default: return false;
3238   case X86ISD::PSHUFD:
3239   case X86ISD::PSHUFHW:
3240   case X86ISD::PSHUFLW:
3241   case X86ISD::SHUFP:
3242   case X86ISD::PALIGNR:
3243   case X86ISD::MOVLHPS:
3244   case X86ISD::MOVLHPD:
3245   case X86ISD::MOVHLPS:
3246   case X86ISD::MOVLPS:
3247   case X86ISD::MOVLPD:
3248   case X86ISD::MOVSHDUP:
3249   case X86ISD::MOVSLDUP:
3250   case X86ISD::MOVDDUP:
3251   case X86ISD::MOVSS:
3252   case X86ISD::MOVSD:
3253   case X86ISD::UNPCKL:
3254   case X86ISD::UNPCKH:
3255   case X86ISD::VPERMILP:
3256   case X86ISD::VPERM2X128:
3257   case X86ISD::VPERMI:
3258     return true;
3259   }
3260 }
3261
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263                                     SDValue V1, SelectionDAG &DAG) {
3264   switch(Opc) {
3265   default: llvm_unreachable("Unknown x86 shuffle node");
3266   case X86ISD::MOVSHDUP:
3267   case X86ISD::MOVSLDUP:
3268   case X86ISD::MOVDDUP:
3269     return DAG.getNode(Opc, dl, VT, V1);
3270   }
3271 }
3272
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274                                     SDValue V1, unsigned TargetMask,
3275                                     SelectionDAG &DAG) {
3276   switch(Opc) {
3277   default: llvm_unreachable("Unknown x86 shuffle node");
3278   case X86ISD::PSHUFD:
3279   case X86ISD::PSHUFHW:
3280   case X86ISD::PSHUFLW:
3281   case X86ISD::VPERMILP:
3282   case X86ISD::VPERMI:
3283     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3284   }
3285 }
3286
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288                                     SDValue V1, SDValue V2, unsigned TargetMask,
3289                                     SelectionDAG &DAG) {
3290   switch(Opc) {
3291   default: llvm_unreachable("Unknown x86 shuffle node");
3292   case X86ISD::PALIGNR:
3293   case X86ISD::SHUFP:
3294   case X86ISD::VPERM2X128:
3295     return DAG.getNode(Opc, dl, VT, V1, V2,
3296                        DAG.getConstant(TargetMask, MVT::i8));
3297   }
3298 }
3299
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3302   switch(Opc) {
3303   default: llvm_unreachable("Unknown x86 shuffle node");
3304   case X86ISD::MOVLHPS:
3305   case X86ISD::MOVLHPD:
3306   case X86ISD::MOVHLPS:
3307   case X86ISD::MOVLPS:
3308   case X86ISD::MOVLPD:
3309   case X86ISD::MOVSS:
3310   case X86ISD::MOVSD:
3311   case X86ISD::UNPCKL:
3312   case X86ISD::UNPCKH:
3313     return DAG.getNode(Opc, dl, VT, V1, V2);
3314   }
3315 }
3316
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318   MachineFunction &MF = DAG.getMachineFunction();
3319   const X86RegisterInfo *RegInfo =
3320     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322   int ReturnAddrIndex = FuncInfo->getRAIndex();
3323
3324   if (ReturnAddrIndex == 0) {
3325     // Set up a frame object for the return address.
3326     unsigned SlotSize = RegInfo->getSlotSize();
3327     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3328                                                            -(int64_t)SlotSize,
3329                                                            false);
3330     FuncInfo->setRAIndex(ReturnAddrIndex);
3331   }
3332
3333   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3334 }
3335
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337                                        bool hasSymbolicDisplacement) {
3338   // Offset should fit into 32 bit immediate field.
3339   if (!isInt<32>(Offset))
3340     return false;
3341
3342   // If we don't have a symbolic displacement - we don't have any extra
3343   // restrictions.
3344   if (!hasSymbolicDisplacement)
3345     return true;
3346
3347   // FIXME: Some tweaks might be needed for medium code model.
3348   if (M != CodeModel::Small && M != CodeModel::Kernel)
3349     return false;
3350
3351   // For small code model we assume that latest object is 16MB before end of 31
3352   // bits boundary. We may also accept pretty large negative constants knowing
3353   // that all objects are in the positive half of address space.
3354   if (M == CodeModel::Small && Offset < 16*1024*1024)
3355     return true;
3356
3357   // For kernel code model we know that all object resist in the negative half
3358   // of 32bits address space. We may not accept negative offsets, since they may
3359   // be just off and we may accept pretty large positive ones.
3360   if (M == CodeModel::Kernel && Offset > 0)
3361     return true;
3362
3363   return false;
3364 }
3365
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3370   if (IsVarArg)
3371     return false;
3372
3373   switch (CallingConv) {
3374   default:
3375     return false;
3376   case CallingConv::X86_StdCall:
3377     return !is64Bit;
3378   case CallingConv::X86_FastCall:
3379     return !is64Bit;
3380   case CallingConv::X86_ThisCall:
3381     return !is64Bit;
3382   case CallingConv::Fast:
3383     return TailCallOpt;
3384   case CallingConv::GHC:
3385     return TailCallOpt;
3386   case CallingConv::HiPE:
3387     return TailCallOpt;
3388   }
3389 }
3390
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3396   if (!isFP) {
3397     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399         // X > -1   -> X == 0, jump !sign.
3400         RHS = DAG.getConstant(0, RHS.getValueType());
3401         return X86::COND_NS;
3402       }
3403       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404         // X < 0   -> X == 0, jump on sign.
3405         return X86::COND_S;
3406       }
3407       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3408         // X < 1   -> X <= 0
3409         RHS = DAG.getConstant(0, RHS.getValueType());
3410         return X86::COND_LE;
3411       }
3412     }
3413
3414     switch (SetCCOpcode) {
3415     default: llvm_unreachable("Invalid integer condition!");
3416     case ISD::SETEQ:  return X86::COND_E;
3417     case ISD::SETGT:  return X86::COND_G;
3418     case ISD::SETGE:  return X86::COND_GE;
3419     case ISD::SETLT:  return X86::COND_L;
3420     case ISD::SETLE:  return X86::COND_LE;
3421     case ISD::SETNE:  return X86::COND_NE;
3422     case ISD::SETULT: return X86::COND_B;
3423     case ISD::SETUGT: return X86::COND_A;
3424     case ISD::SETULE: return X86::COND_BE;
3425     case ISD::SETUGE: return X86::COND_AE;
3426     }
3427   }
3428
3429   // First determine if it is required or is profitable to flip the operands.
3430
3431   // If LHS is a foldable load, but RHS is not, flip the condition.
3432   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433       !ISD::isNON_EXTLoad(RHS.getNode())) {
3434     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435     std::swap(LHS, RHS);
3436   }
3437
3438   switch (SetCCOpcode) {
3439   default: break;
3440   case ISD::SETOLT:
3441   case ISD::SETOLE:
3442   case ISD::SETUGT:
3443   case ISD::SETUGE:
3444     std::swap(LHS, RHS);
3445     break;
3446   }
3447
3448   // On a floating point condition, the flags are set as follows:
3449   // ZF  PF  CF   op
3450   //  0 | 0 | 0 | X > Y
3451   //  0 | 0 | 1 | X < Y
3452   //  1 | 0 | 0 | X == Y
3453   //  1 | 1 | 1 | unordered
3454   switch (SetCCOpcode) {
3455   default: llvm_unreachable("Condcode should be pre-legalized away");
3456   case ISD::SETUEQ:
3457   case ISD::SETEQ:   return X86::COND_E;
3458   case ISD::SETOLT:              // flipped
3459   case ISD::SETOGT:
3460   case ISD::SETGT:   return X86::COND_A;
3461   case ISD::SETOLE:              // flipped
3462   case ISD::SETOGE:
3463   case ISD::SETGE:   return X86::COND_AE;
3464   case ISD::SETUGT:              // flipped
3465   case ISD::SETULT:
3466   case ISD::SETLT:   return X86::COND_B;
3467   case ISD::SETUGE:              // flipped
3468   case ISD::SETULE:
3469   case ISD::SETLE:   return X86::COND_BE;
3470   case ISD::SETONE:
3471   case ISD::SETNE:   return X86::COND_NE;
3472   case ISD::SETUO:   return X86::COND_P;
3473   case ISD::SETO:    return X86::COND_NP;
3474   case ISD::SETOEQ:
3475   case ISD::SETUNE:  return X86::COND_INVALID;
3476   }
3477 }
3478
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3483   switch (X86CC) {
3484   default:
3485     return false;
3486   case X86::COND_B:
3487   case X86::COND_BE:
3488   case X86::COND_E:
3489   case X86::COND_P:
3490   case X86::COND_A:
3491   case X86::COND_AE:
3492   case X86::COND_NE:
3493   case X86::COND_NP:
3494     return true;
3495   }
3496 }
3497
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3504       return true;
3505   }
3506   return false;
3507 }
3508
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512   return (Val < 0) || (Val >= Low && Val < Hi);
3513 }
3514
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518   return (Val < 0 || Val == CmpVal);
3519 }
3520
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525                                        unsigned Pos, unsigned Size, int Low) {
3526   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527     if (!isUndefOrEqual(Mask[i], Low))
3528       return false;
3529   return true;
3530 }
3531
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3536   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539     return (Mask[0] < 2 && Mask[1] < 2);
3540   return false;
3541 }
3542
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3546   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3547     return false;
3548
3549   // Lower quadword copied in order or undef.
3550   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3551     return false;
3552
3553   // Upper quadword shuffled.
3554   for (unsigned i = 4; i != 8; ++i)
3555     if (!isUndefOrInRange(Mask[i], 4, 8))
3556       return false;
3557
3558   if (VT == MVT::v16i16) {
3559     // Lower quadword copied in order or undef.
3560     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3561       return false;
3562
3563     // Upper quadword shuffled.
3564     for (unsigned i = 12; i != 16; ++i)
3565       if (!isUndefOrInRange(Mask[i], 12, 16))
3566         return false;
3567   }
3568
3569   return true;
3570 }
3571
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3575   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3576     return false;
3577
3578   // Upper quadword copied in order.
3579   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3580     return false;
3581
3582   // Lower quadword shuffled.
3583   for (unsigned i = 0; i != 4; ++i)
3584     if (!isUndefOrInRange(Mask[i], 0, 4))
3585       return false;
3586
3587   if (VT == MVT::v16i16) {
3588     // Upper quadword copied in order.
3589     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3590       return false;
3591
3592     // Lower quadword shuffled.
3593     for (unsigned i = 8; i != 12; ++i)
3594       if (!isUndefOrInRange(Mask[i], 8, 12))
3595         return false;
3596   }
3597
3598   return true;
3599 }
3600
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3604                           const X86Subtarget *Subtarget) {
3605   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606       (VT.is256BitVector() && !Subtarget->hasInt256()))
3607     return false;
3608
3609   unsigned NumElts = VT.getVectorNumElements();
3610   unsigned NumLanes = VT.getSizeInBits()/128;
3611   unsigned NumLaneElts = NumElts/NumLanes;
3612
3613   // Do not handle 64-bit element shuffles with palignr.
3614   if (NumLaneElts == 2)
3615     return false;
3616
3617   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3618     unsigned i;
3619     for (i = 0; i != NumLaneElts; ++i) {
3620       if (Mask[i+l] >= 0)
3621         break;
3622     }
3623
3624     // Lane is all undef, go to next lane
3625     if (i == NumLaneElts)
3626       continue;
3627
3628     int Start = Mask[i+l];
3629
3630     // Make sure its in this lane in one of the sources
3631     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3633       return false;
3634
3635     // If not lane 0, then we must match lane 0
3636     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3637       return false;
3638
3639     // Correct second source to be contiguous with first source
3640     if (Start >= (int)NumElts)
3641       Start -= NumElts - NumLaneElts;
3642
3643     // Make sure we're shifting in the right direction.
3644     if (Start <= (int)(i+l))
3645       return false;
3646
3647     Start -= i;
3648
3649     // Check the rest of the elements to see if they are consecutive.
3650     for (++i; i != NumLaneElts; ++i) {
3651       int Idx = Mask[i+l];
3652
3653       // Make sure its in this lane
3654       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3656         return false;
3657
3658       // If not lane 0, then we must match lane 0
3659       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3660         return false;
3661
3662       if (Idx >= (int)NumElts)
3663         Idx -= NumElts - NumLaneElts;
3664
3665       if (!isUndefOrEqual(Idx, Start+i))
3666         return false;
3667
3668     }
3669   }
3670
3671   return true;
3672 }
3673
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677                                      unsigned NumElems) {
3678   for (unsigned i = 0; i != NumElems; ++i) {
3679     int idx = Mask[i];
3680     if (idx < 0)
3681       continue;
3682     else if (idx < (int)NumElems)
3683       Mask[i] = idx + NumElems;
3684     else
3685       Mask[i] = idx - NumElems;
3686   }
3687 }
3688
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3694                         bool Commuted = false) {
3695   if (!HasFp256 && VT.is256BitVector())
3696     return false;
3697
3698   unsigned NumElems = VT.getVectorNumElements();
3699   unsigned NumLanes = VT.getSizeInBits()/128;
3700   unsigned NumLaneElems = NumElems/NumLanes;
3701
3702   if (NumLaneElems != 2 && NumLaneElems != 4)
3703     return false;
3704
3705   // VSHUFPSY divides the resulting vector into 4 chunks.
3706   // The sources are also splitted into 4 chunks, and each destination
3707   // chunk must come from a different source chunk.
3708   //
3709   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3710   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3711   //
3712   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3713   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3714   //
3715   // VSHUFPDY divides the resulting vector into 4 chunks.
3716   // The sources are also splitted into 4 chunks, and each destination
3717   // chunk must come from a different source chunk.
3718   //
3719   //  SRC1 =>      X3       X2       X1       X0
3720   //  SRC2 =>      Y3       Y2       Y1       Y0
3721   //
3722   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3723   //
3724   unsigned HalfLaneElems = NumLaneElems/2;
3725   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726     for (unsigned i = 0; i != NumLaneElems; ++i) {
3727       int Idx = Mask[i+l];
3728       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3730         return false;
3731       // For VSHUFPSY, the mask of the second half must be the same as the
3732       // first but with the appropriate offsets. This works in the same way as
3733       // VPERMILPS works with masks.
3734       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3735         continue;
3736       if (!isUndefOrEqual(Idx, Mask[i]+l))
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, EVT 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, EVT 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, EVT 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, EVT 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->getValueType(0).getSimpleVT();
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, EVT VT,
3874                          bool HasInt256, bool V2IsSplat = false) {
3875   unsigned NumElts = VT.getVectorNumElements();
3876
3877   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3878          "Unsupported vector type for unpckh");
3879
3880   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3881       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3882     return false;
3883
3884   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3885   // independently on 128-bit lanes.
3886   unsigned NumLanes = VT.getSizeInBits()/128;
3887   unsigned NumLaneElts = NumElts/NumLanes;
3888
3889   for (unsigned l = 0; l != NumLanes; ++l) {
3890     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3891          i != (l+1)*NumLaneElts;
3892          i += 2, ++j) {
3893       int BitI  = Mask[i];
3894       int BitI1 = Mask[i+1];
3895       if (!isUndefOrEqual(BitI, j))
3896         return false;
3897       if (V2IsSplat) {
3898         if (!isUndefOrEqual(BitI1, NumElts))
3899           return false;
3900       } else {
3901         if (!isUndefOrEqual(BitI1, j + NumElts))
3902           return false;
3903       }
3904     }
3905   }
3906
3907   return true;
3908 }
3909
3910 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3912 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3913                          bool HasInt256, bool V2IsSplat = false) {
3914   unsigned NumElts = VT.getVectorNumElements();
3915
3916   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3917          "Unsupported vector type for unpckh");
3918
3919   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3920       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3921     return false;
3922
3923   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3924   // independently on 128-bit lanes.
3925   unsigned NumLanes = VT.getSizeInBits()/128;
3926   unsigned NumLaneElts = NumElts/NumLanes;
3927
3928   for (unsigned l = 0; l != NumLanes; ++l) {
3929     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3930          i != (l+1)*NumLaneElts; i += 2, ++j) {
3931       int BitI  = Mask[i];
3932       int BitI1 = Mask[i+1];
3933       if (!isUndefOrEqual(BitI, j))
3934         return false;
3935       if (V2IsSplat) {
3936         if (isUndefOrEqual(BitI1, NumElts))
3937           return false;
3938       } else {
3939         if (!isUndefOrEqual(BitI1, j+NumElts))
3940           return false;
3941       }
3942     }
3943   }
3944   return true;
3945 }
3946
3947 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3948 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3949 /// <0, 0, 1, 1>
3950 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3951   unsigned NumElts = VT.getVectorNumElements();
3952   bool Is256BitVec = VT.is256BitVector();
3953
3954   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3955          "Unsupported vector type for unpckh");
3956
3957   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3958       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3959     return false;
3960
3961   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3962   // FIXME: Need a better way to get rid of this, there's no latency difference
3963   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3964   // the former later. We should also remove the "_undef" special mask.
3965   if (NumElts == 4 && Is256BitVec)
3966     return false;
3967
3968   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3969   // independently on 128-bit lanes.
3970   unsigned NumLanes = VT.getSizeInBits()/128;
3971   unsigned NumLaneElts = NumElts/NumLanes;
3972
3973   for (unsigned l = 0; l != NumLanes; ++l) {
3974     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3975          i != (l+1)*NumLaneElts;
3976          i += 2, ++j) {
3977       int BitI  = Mask[i];
3978       int BitI1 = Mask[i+1];
3979
3980       if (!isUndefOrEqual(BitI, j))
3981         return false;
3982       if (!isUndefOrEqual(BitI1, j))
3983         return false;
3984     }
3985   }
3986
3987   return true;
3988 }
3989
3990 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3991 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3992 /// <2, 2, 3, 3>
3993 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3994   unsigned NumElts = VT.getVectorNumElements();
3995
3996   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3997          "Unsupported vector type for unpckh");
3998
3999   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4000       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4001     return false;
4002
4003   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4004   // independently on 128-bit lanes.
4005   unsigned NumLanes = VT.getSizeInBits()/128;
4006   unsigned NumLaneElts = NumElts/NumLanes;
4007
4008   for (unsigned l = 0; l != NumLanes; ++l) {
4009     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
4010          i != (l+1)*NumLaneElts; i += 2, ++j) {
4011       int BitI  = Mask[i];
4012       int BitI1 = Mask[i+1];
4013       if (!isUndefOrEqual(BitI, j))
4014         return false;
4015       if (!isUndefOrEqual(BitI1, j))
4016         return false;
4017     }
4018   }
4019   return true;
4020 }
4021
4022 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4023 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4024 /// MOVSD, and MOVD, i.e. setting the lowest element.
4025 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4026   if (VT.getVectorElementType().getSizeInBits() < 32)
4027     return false;
4028   if (!VT.is128BitVector())
4029     return false;
4030
4031   unsigned NumElts = VT.getVectorNumElements();
4032
4033   if (!isUndefOrEqual(Mask[0], NumElts))
4034     return false;
4035
4036   for (unsigned i = 1; i != NumElts; ++i)
4037     if (!isUndefOrEqual(Mask[i], i))
4038       return false;
4039
4040   return true;
4041 }
4042
4043 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4044 /// as permutations between 128-bit chunks or halves. As an example: this
4045 /// shuffle bellow:
4046 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4047 /// The first half comes from the second half of V1 and the second half from the
4048 /// the second half of V2.
4049 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4050   if (!HasFp256 || !VT.is256BitVector())
4051     return false;
4052
4053   // The shuffle result is divided into half A and half B. In total the two
4054   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4055   // B must come from C, D, E or F.
4056   unsigned HalfSize = VT.getVectorNumElements()/2;
4057   bool MatchA = false, MatchB = false;
4058
4059   // Check if A comes from one of C, D, E, F.
4060   for (unsigned Half = 0; Half != 4; ++Half) {
4061     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4062       MatchA = true;
4063       break;
4064     }
4065   }
4066
4067   // Check if B comes from one of C, D, E, F.
4068   for (unsigned Half = 0; Half != 4; ++Half) {
4069     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4070       MatchB = true;
4071       break;
4072     }
4073   }
4074
4075   return MatchA && MatchB;
4076 }
4077
4078 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4079 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4080 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4081   MVT VT = SVOp->getValueType(0).getSimpleVT();
4082
4083   unsigned HalfSize = VT.getVectorNumElements()/2;
4084
4085   unsigned FstHalf = 0, SndHalf = 0;
4086   for (unsigned i = 0; i < HalfSize; ++i) {
4087     if (SVOp->getMaskElt(i) > 0) {
4088       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4089       break;
4090     }
4091   }
4092   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4093     if (SVOp->getMaskElt(i) > 0) {
4094       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4095       break;
4096     }
4097   }
4098
4099   return (FstHalf | (SndHalf << 4));
4100 }
4101
4102 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4103 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4104 /// Note that VPERMIL mask matching is different depending whether theunderlying
4105 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4106 /// to the same elements of the low, but to the higher half of the source.
4107 /// In VPERMILPD the two lanes could be shuffled independently of each other
4108 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4109 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4110   if (!HasFp256)
4111     return false;
4112
4113   unsigned NumElts = VT.getVectorNumElements();
4114   // Only match 256-bit with 32/64-bit types
4115   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4116     return false;
4117
4118   unsigned NumLanes = VT.getSizeInBits()/128;
4119   unsigned LaneSize = NumElts/NumLanes;
4120   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4121     for (unsigned i = 0; i != LaneSize; ++i) {
4122       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4123         return false;
4124       if (NumElts != 8 || l == 0)
4125         continue;
4126       // VPERMILPS handling
4127       if (Mask[i] < 0)
4128         continue;
4129       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4130         return false;
4131     }
4132   }
4133
4134   return true;
4135 }
4136
4137 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4138 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4139 /// element of vector 2 and the other elements to come from vector 1 in order.
4140 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4141                                bool V2IsSplat = false, bool V2IsUndef = false) {
4142   if (!VT.is128BitVector())
4143     return false;
4144
4145   unsigned NumOps = VT.getVectorNumElements();
4146   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4147     return false;
4148
4149   if (!isUndefOrEqual(Mask[0], 0))
4150     return false;
4151
4152   for (unsigned i = 1; i != NumOps; ++i)
4153     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4154           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4155           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4156       return false;
4157
4158   return true;
4159 }
4160
4161 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4162 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4163 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4164 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4165                            const X86Subtarget *Subtarget) {
4166   if (!Subtarget->hasSSE3())
4167     return false;
4168
4169   unsigned NumElems = VT.getVectorNumElements();
4170
4171   if ((VT.is128BitVector() && NumElems != 4) ||
4172       (VT.is256BitVector() && NumElems != 8))
4173     return false;
4174
4175   // "i+1" is the value the indexed mask element must have
4176   for (unsigned i = 0; i != NumElems; i += 2)
4177     if (!isUndefOrEqual(Mask[i], i+1) ||
4178         !isUndefOrEqual(Mask[i+1], i+1))
4179       return false;
4180
4181   return true;
4182 }
4183
4184 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4185 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4186 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4187 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4188                            const X86Subtarget *Subtarget) {
4189   if (!Subtarget->hasSSE3())
4190     return false;
4191
4192   unsigned NumElems = VT.getVectorNumElements();
4193
4194   if ((VT.is128BitVector() && NumElems != 4) ||
4195       (VT.is256BitVector() && NumElems != 8))
4196     return false;
4197
4198   // "i" is the value the indexed mask element must have
4199   for (unsigned i = 0; i != NumElems; i += 2)
4200     if (!isUndefOrEqual(Mask[i], i) ||
4201         !isUndefOrEqual(Mask[i+1], i))
4202       return false;
4203
4204   return true;
4205 }
4206
4207 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4208 /// specifies a shuffle of elements that is suitable for input to 256-bit
4209 /// version of MOVDDUP.
4210 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4211   if (!HasFp256 || !VT.is256BitVector())
4212     return false;
4213
4214   unsigned NumElts = VT.getVectorNumElements();
4215   if (NumElts != 4)
4216     return false;
4217
4218   for (unsigned i = 0; i != NumElts/2; ++i)
4219     if (!isUndefOrEqual(Mask[i], 0))
4220       return false;
4221   for (unsigned i = NumElts/2; i != NumElts; ++i)
4222     if (!isUndefOrEqual(Mask[i], NumElts/2))
4223       return false;
4224   return true;
4225 }
4226
4227 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4228 /// specifies a shuffle of elements that is suitable for input to 128-bit
4229 /// version of MOVDDUP.
4230 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4231   if (!VT.is128BitVector())
4232     return false;
4233
4234   unsigned e = VT.getVectorNumElements() / 2;
4235   for (unsigned i = 0; i != e; ++i)
4236     if (!isUndefOrEqual(Mask[i], i))
4237       return false;
4238   for (unsigned i = 0; i != e; ++i)
4239     if (!isUndefOrEqual(Mask[e+i], i))
4240       return false;
4241   return true;
4242 }
4243
4244 /// isVEXTRACTIndex - Return true if the specified
4245 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4246 /// suitable for instruction that extract 128 or 256 bit vectors
4247 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4248   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4249   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4250     return false;
4251
4252   // The index should be aligned on a vecWidth-bit boundary.
4253   uint64_t Index =
4254     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4255
4256   MVT VT = N->getValueType(0).getSimpleVT();
4257   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4258   bool Result = (Index * ElSize) % vecWidth == 0;
4259
4260   return Result;
4261 }
4262
4263 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4264 /// operand specifies a subvector insert that is suitable for input to
4265 /// insertion of 128 or 256-bit subvectors
4266 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4267   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4268   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4269     return false;
4270   // The index should be aligned on a vecWidth-bit boundary.
4271   uint64_t Index =
4272     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4273
4274   MVT VT = N->getValueType(0).getSimpleVT();
4275   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4276   bool Result = (Index * ElSize) % vecWidth == 0;
4277
4278   return Result;
4279 }
4280
4281 bool X86::isVINSERT128Index(SDNode *N) {
4282   return isVINSERTIndex(N, 128);
4283 }
4284
4285 bool X86::isVINSERT256Index(SDNode *N) {
4286   return isVINSERTIndex(N, 256);
4287 }
4288
4289 bool X86::isVEXTRACT128Index(SDNode *N) {
4290   return isVEXTRACTIndex(N, 128);
4291 }
4292
4293 bool X86::isVEXTRACT256Index(SDNode *N) {
4294   return isVEXTRACTIndex(N, 256);
4295 }
4296
4297 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4298 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4299 /// Handles 128-bit and 256-bit.
4300 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4301   MVT VT = N->getValueType(0).getSimpleVT();
4302
4303   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4304          "Unsupported vector type for PSHUF/SHUFP");
4305
4306   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4307   // independently on 128-bit lanes.
4308   unsigned NumElts = VT.getVectorNumElements();
4309   unsigned NumLanes = VT.getSizeInBits()/128;
4310   unsigned NumLaneElts = NumElts/NumLanes;
4311
4312   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4313          "Only supports 2 or 4 elements per lane");
4314
4315   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4316   unsigned Mask = 0;
4317   for (unsigned i = 0; i != NumElts; ++i) {
4318     int Elt = N->getMaskElt(i);
4319     if (Elt < 0) continue;
4320     Elt &= NumLaneElts - 1;
4321     unsigned ShAmt = (i << Shift) % 8;
4322     Mask |= Elt << ShAmt;
4323   }
4324
4325   return Mask;
4326 }
4327
4328 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4329 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4330 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4331   MVT VT = N->getValueType(0).getSimpleVT();
4332
4333   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4334          "Unsupported vector type for PSHUFHW");
4335
4336   unsigned NumElts = VT.getVectorNumElements();
4337
4338   unsigned Mask = 0;
4339   for (unsigned l = 0; l != NumElts; l += 8) {
4340     // 8 nodes per lane, but we only care about the last 4.
4341     for (unsigned i = 0; i < 4; ++i) {
4342       int Elt = N->getMaskElt(l+i+4);
4343       if (Elt < 0) continue;
4344       Elt &= 0x3; // only 2-bits.
4345       Mask |= Elt << (i * 2);
4346     }
4347   }
4348
4349   return Mask;
4350 }
4351
4352 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4353 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4354 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4355   MVT VT = N->getValueType(0).getSimpleVT();
4356
4357   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4358          "Unsupported vector type for PSHUFHW");
4359
4360   unsigned NumElts = VT.getVectorNumElements();
4361
4362   unsigned Mask = 0;
4363   for (unsigned l = 0; l != NumElts; l += 8) {
4364     // 8 nodes per lane, but we only care about the first 4.
4365     for (unsigned i = 0; i < 4; ++i) {
4366       int Elt = N->getMaskElt(l+i);
4367       if (Elt < 0) continue;
4368       Elt &= 0x3; // only 2-bits
4369       Mask |= Elt << (i * 2);
4370     }
4371   }
4372
4373   return Mask;
4374 }
4375
4376 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4377 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4378 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4379   MVT VT = SVOp->getValueType(0).getSimpleVT();
4380   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4381
4382   unsigned NumElts = VT.getVectorNumElements();
4383   unsigned NumLanes = VT.getSizeInBits()/128;
4384   unsigned NumLaneElts = NumElts/NumLanes;
4385
4386   int Val = 0;
4387   unsigned i;
4388   for (i = 0; i != NumElts; ++i) {
4389     Val = SVOp->getMaskElt(i);
4390     if (Val >= 0)
4391       break;
4392   }
4393   if (Val >= (int)NumElts)
4394     Val -= NumElts - NumLaneElts;
4395
4396   assert(Val - i > 0 && "PALIGNR imm should be positive");
4397   return (Val - i) * EltSize;
4398 }
4399
4400 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4401   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4402   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4403     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4404
4405   uint64_t Index =
4406     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4407
4408   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4409   MVT ElVT = VecVT.getVectorElementType();
4410
4411   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4412   return Index / NumElemsPerChunk;
4413 }
4414
4415 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4416   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4417   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4418     llvm_unreachable("Illegal insert subvector for VINSERT");
4419
4420   uint64_t Index =
4421     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4422
4423   MVT VecVT = N->getValueType(0).getSimpleVT();
4424   MVT ElVT = VecVT.getVectorElementType();
4425
4426   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4427   return Index / NumElemsPerChunk;
4428 }
4429
4430 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4431 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4432 /// and VINSERTI128 instructions.
4433 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4434   return getExtractVEXTRACTImmediate(N, 128);
4435 }
4436
4437 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4438 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4439 /// and VINSERTI64x4 instructions.
4440 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4441   return getExtractVEXTRACTImmediate(N, 256);
4442 }
4443
4444 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4445 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4446 /// and VINSERTI128 instructions.
4447 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4448   return getInsertVINSERTImmediate(N, 128);
4449 }
4450
4451 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4452 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4453 /// and VINSERTI64x4 instructions.
4454 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4455   return getInsertVINSERTImmediate(N, 256);
4456 }
4457
4458 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4459 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4460 /// Handles 256-bit.
4461 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4462   MVT VT = N->getValueType(0).getSimpleVT();
4463
4464   unsigned NumElts = VT.getVectorNumElements();
4465
4466   assert((VT.is256BitVector() && NumElts == 4) &&
4467          "Unsupported vector type for VPERMQ/VPERMPD");
4468
4469   unsigned Mask = 0;
4470   for (unsigned i = 0; i != NumElts; ++i) {
4471     int Elt = N->getMaskElt(i);
4472     if (Elt < 0)
4473       continue;
4474     Mask |= Elt << (i*2);
4475   }
4476
4477   return Mask;
4478 }
4479 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4480 /// constant +0.0.
4481 bool X86::isZeroNode(SDValue Elt) {
4482   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4483     return CN->isNullValue();
4484   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4485     return CFP->getValueAPF().isPosZero();
4486   return false;
4487 }
4488
4489 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4490 /// their permute mask.
4491 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4492                                     SelectionDAG &DAG) {
4493   MVT VT = SVOp->getValueType(0).getSimpleVT();
4494   unsigned NumElems = VT.getVectorNumElements();
4495   SmallVector<int, 8> MaskVec;
4496
4497   for (unsigned i = 0; i != NumElems; ++i) {
4498     int Idx = SVOp->getMaskElt(i);
4499     if (Idx >= 0) {
4500       if (Idx < (int)NumElems)
4501         Idx += NumElems;
4502       else
4503         Idx -= NumElems;
4504     }
4505     MaskVec.push_back(Idx);
4506   }
4507   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4508                               SVOp->getOperand(0), &MaskVec[0]);
4509 }
4510
4511 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4512 /// match movhlps. The lower half elements should come from upper half of
4513 /// V1 (and in order), and the upper half elements should come from the upper
4514 /// half of V2 (and in order).
4515 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4516   if (!VT.is128BitVector())
4517     return false;
4518   if (VT.getVectorNumElements() != 4)
4519     return false;
4520   for (unsigned i = 0, e = 2; i != e; ++i)
4521     if (!isUndefOrEqual(Mask[i], i+2))
4522       return false;
4523   for (unsigned i = 2; i != 4; ++i)
4524     if (!isUndefOrEqual(Mask[i], i+4))
4525       return false;
4526   return true;
4527 }
4528
4529 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4530 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4531 /// required.
4532 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4533   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4534     return false;
4535   N = N->getOperand(0).getNode();
4536   if (!ISD::isNON_EXTLoad(N))
4537     return false;
4538   if (LD)
4539     *LD = cast<LoadSDNode>(N);
4540   return true;
4541 }
4542
4543 // Test whether the given value is a vector value which will be legalized
4544 // into a load.
4545 static bool WillBeConstantPoolLoad(SDNode *N) {
4546   if (N->getOpcode() != ISD::BUILD_VECTOR)
4547     return false;
4548
4549   // Check for any non-constant elements.
4550   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4551     switch (N->getOperand(i).getNode()->getOpcode()) {
4552     case ISD::UNDEF:
4553     case ISD::ConstantFP:
4554     case ISD::Constant:
4555       break;
4556     default:
4557       return false;
4558     }
4559
4560   // Vectors of all-zeros and all-ones are materialized with special
4561   // instructions rather than being loaded.
4562   return !ISD::isBuildVectorAllZeros(N) &&
4563          !ISD::isBuildVectorAllOnes(N);
4564 }
4565
4566 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4567 /// match movlp{s|d}. The lower half elements should come from lower half of
4568 /// V1 (and in order), and the upper half elements should come from the upper
4569 /// half of V2 (and in order). And since V1 will become the source of the
4570 /// MOVLP, it must be either a vector load or a scalar load to vector.
4571 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4572                                ArrayRef<int> Mask, EVT VT) {
4573   if (!VT.is128BitVector())
4574     return false;
4575
4576   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4577     return false;
4578   // Is V2 is a vector load, don't do this transformation. We will try to use
4579   // load folding shufps op.
4580   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4581     return false;
4582
4583   unsigned NumElems = VT.getVectorNumElements();
4584
4585   if (NumElems != 2 && NumElems != 4)
4586     return false;
4587   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4588     if (!isUndefOrEqual(Mask[i], i))
4589       return false;
4590   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4591     if (!isUndefOrEqual(Mask[i], i+NumElems))
4592       return false;
4593   return true;
4594 }
4595
4596 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4597 /// all the same.
4598 static bool isSplatVector(SDNode *N) {
4599   if (N->getOpcode() != ISD::BUILD_VECTOR)
4600     return false;
4601
4602   SDValue SplatValue = N->getOperand(0);
4603   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4604     if (N->getOperand(i) != SplatValue)
4605       return false;
4606   return true;
4607 }
4608
4609 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4610 /// to an zero vector.
4611 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4612 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4613   SDValue V1 = N->getOperand(0);
4614   SDValue V2 = N->getOperand(1);
4615   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4616   for (unsigned i = 0; i != NumElems; ++i) {
4617     int Idx = N->getMaskElt(i);
4618     if (Idx >= (int)NumElems) {
4619       unsigned Opc = V2.getOpcode();
4620       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4621         continue;
4622       if (Opc != ISD::BUILD_VECTOR ||
4623           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4624         return false;
4625     } else if (Idx >= 0) {
4626       unsigned Opc = V1.getOpcode();
4627       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4628         continue;
4629       if (Opc != ISD::BUILD_VECTOR ||
4630           !X86::isZeroNode(V1.getOperand(Idx)))
4631         return false;
4632     }
4633   }
4634   return true;
4635 }
4636
4637 /// getZeroVector - Returns a vector of specified type with all zero elements.
4638 ///
4639 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4640                              SelectionDAG &DAG, SDLoc dl) {
4641   assert(VT.isVector() && "Expected a vector type");
4642
4643   // Always build SSE zero vectors as <4 x i32> bitcasted
4644   // to their dest type. This ensures they get CSE'd.
4645   SDValue Vec;
4646   if (VT.is128BitVector()) {  // SSE
4647     if (Subtarget->hasSSE2()) {  // SSE2
4648       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4649       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4650     } else { // SSE1
4651       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4652       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4653     }
4654   } else if (VT.is256BitVector()) { // AVX
4655     if (Subtarget->hasInt256()) { // AVX2
4656       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4657       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4658       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4659                         array_lengthof(Ops));
4660     } else {
4661       // 256-bit logic and arithmetic instructions in AVX are all
4662       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4663       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4664       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4665       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4666                         array_lengthof(Ops));
4667     }
4668   } else
4669     llvm_unreachable("Unexpected vector type");
4670
4671   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4672 }
4673
4674 /// getOnesVector - Returns a vector of specified type with all bits set.
4675 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4676 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4677 /// Then bitcast to their original type, ensuring they get CSE'd.
4678 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4679                              SDLoc dl) {
4680   assert(VT.isVector() && "Expected a vector type");
4681
4682   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4683   SDValue Vec;
4684   if (VT.is256BitVector()) {
4685     if (HasInt256) { // AVX2
4686       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4688                         array_lengthof(Ops));
4689     } else { // AVX
4690       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4691       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4692     }
4693   } else if (VT.is128BitVector()) {
4694     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4695   } else
4696     llvm_unreachable("Unexpected vector type");
4697
4698   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4699 }
4700
4701 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4702 /// that point to V2 points to its first element.
4703 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4704   for (unsigned i = 0; i != NumElems; ++i) {
4705     if (Mask[i] > (int)NumElems) {
4706       Mask[i] = NumElems;
4707     }
4708   }
4709 }
4710
4711 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4712 /// operation of specified width.
4713 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4714                        SDValue V2) {
4715   unsigned NumElems = VT.getVectorNumElements();
4716   SmallVector<int, 8> Mask;
4717   Mask.push_back(NumElems);
4718   for (unsigned i = 1; i != NumElems; ++i)
4719     Mask.push_back(i);
4720   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4721 }
4722
4723 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4724 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4725                           SDValue V2) {
4726   unsigned NumElems = VT.getVectorNumElements();
4727   SmallVector<int, 8> Mask;
4728   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4729     Mask.push_back(i);
4730     Mask.push_back(i + NumElems);
4731   }
4732   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4733 }
4734
4735 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4736 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4737                           SDValue V2) {
4738   unsigned NumElems = VT.getVectorNumElements();
4739   SmallVector<int, 8> Mask;
4740   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4741     Mask.push_back(i + Half);
4742     Mask.push_back(i + NumElems + Half);
4743   }
4744   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4745 }
4746
4747 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4748 // a generic shuffle instruction because the target has no such instructions.
4749 // Generate shuffles which repeat i16 and i8 several times until they can be
4750 // represented by v4f32 and then be manipulated by target suported shuffles.
4751 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4752   EVT VT = V.getValueType();
4753   int NumElems = VT.getVectorNumElements();
4754   SDLoc dl(V);
4755
4756   while (NumElems > 4) {
4757     if (EltNo < NumElems/2) {
4758       V = getUnpackl(DAG, dl, VT, V, V);
4759     } else {
4760       V = getUnpackh(DAG, dl, VT, V, V);
4761       EltNo -= NumElems/2;
4762     }
4763     NumElems >>= 1;
4764   }
4765   return V;
4766 }
4767
4768 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4769 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4770   EVT VT = V.getValueType();
4771   SDLoc dl(V);
4772
4773   if (VT.is128BitVector()) {
4774     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4775     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4776     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4777                              &SplatMask[0]);
4778   } else if (VT.is256BitVector()) {
4779     // To use VPERMILPS to splat scalars, the second half of indicies must
4780     // refer to the higher part, which is a duplication of the lower one,
4781     // because VPERMILPS can only handle in-lane permutations.
4782     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4783                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4784
4785     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4786     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4787                              &SplatMask[0]);
4788   } else
4789     llvm_unreachable("Vector size not supported");
4790
4791   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4792 }
4793
4794 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4795 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4796   EVT SrcVT = SV->getValueType(0);
4797   SDValue V1 = SV->getOperand(0);
4798   SDLoc dl(SV);
4799
4800   int EltNo = SV->getSplatIndex();
4801   int NumElems = SrcVT.getVectorNumElements();
4802   bool Is256BitVec = SrcVT.is256BitVector();
4803
4804   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4805          "Unknown how to promote splat for type");
4806
4807   // Extract the 128-bit part containing the splat element and update
4808   // the splat element index when it refers to the higher register.
4809   if (Is256BitVec) {
4810     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4811     if (EltNo >= NumElems/2)
4812       EltNo -= NumElems/2;
4813   }
4814
4815   // All i16 and i8 vector types can't be used directly by a generic shuffle
4816   // instruction because the target has no such instruction. Generate shuffles
4817   // which repeat i16 and i8 several times until they fit in i32, and then can
4818   // be manipulated by target suported shuffles.
4819   EVT EltVT = SrcVT.getVectorElementType();
4820   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4821     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4822
4823   // Recreate the 256-bit vector and place the same 128-bit vector
4824   // into the low and high part. This is necessary because we want
4825   // to use VPERM* to shuffle the vectors
4826   if (Is256BitVec) {
4827     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4828   }
4829
4830   return getLegalSplat(DAG, V1, EltNo);
4831 }
4832
4833 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4834 /// vector of zero or undef vector.  This produces a shuffle where the low
4835 /// element of V2 is swizzled into the zero/undef vector, landing at element
4836 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4837 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4838                                            bool IsZero,
4839                                            const X86Subtarget *Subtarget,
4840                                            SelectionDAG &DAG) {
4841   EVT VT = V2.getValueType();
4842   SDValue V1 = IsZero
4843     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4844   unsigned NumElems = VT.getVectorNumElements();
4845   SmallVector<int, 16> MaskVec;
4846   for (unsigned i = 0; i != NumElems; ++i)
4847     // If this is the insertion idx, put the low elt of V2 here.
4848     MaskVec.push_back(i == Idx ? NumElems : i);
4849   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4850 }
4851
4852 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4853 /// target specific opcode. Returns true if the Mask could be calculated.
4854 /// Sets IsUnary to true if only uses one source.
4855 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4856                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4857   unsigned NumElems = VT.getVectorNumElements();
4858   SDValue ImmN;
4859
4860   IsUnary = false;
4861   switch(N->getOpcode()) {
4862   case X86ISD::SHUFP:
4863     ImmN = N->getOperand(N->getNumOperands()-1);
4864     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4865     break;
4866   case X86ISD::UNPCKH:
4867     DecodeUNPCKHMask(VT, Mask);
4868     break;
4869   case X86ISD::UNPCKL:
4870     DecodeUNPCKLMask(VT, Mask);
4871     break;
4872   case X86ISD::MOVHLPS:
4873     DecodeMOVHLPSMask(NumElems, Mask);
4874     break;
4875   case X86ISD::MOVLHPS:
4876     DecodeMOVLHPSMask(NumElems, Mask);
4877     break;
4878   case X86ISD::PALIGNR:
4879     ImmN = N->getOperand(N->getNumOperands()-1);
4880     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4881     break;
4882   case X86ISD::PSHUFD:
4883   case X86ISD::VPERMILP:
4884     ImmN = N->getOperand(N->getNumOperands()-1);
4885     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4886     IsUnary = true;
4887     break;
4888   case X86ISD::PSHUFHW:
4889     ImmN = N->getOperand(N->getNumOperands()-1);
4890     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4891     IsUnary = true;
4892     break;
4893   case X86ISD::PSHUFLW:
4894     ImmN = N->getOperand(N->getNumOperands()-1);
4895     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4896     IsUnary = true;
4897     break;
4898   case X86ISD::VPERMI:
4899     ImmN = N->getOperand(N->getNumOperands()-1);
4900     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4901     IsUnary = true;
4902     break;
4903   case X86ISD::MOVSS:
4904   case X86ISD::MOVSD: {
4905     // The index 0 always comes from the first element of the second source,
4906     // this is why MOVSS and MOVSD are used in the first place. The other
4907     // elements come from the other positions of the first source vector
4908     Mask.push_back(NumElems);
4909     for (unsigned i = 1; i != NumElems; ++i) {
4910       Mask.push_back(i);
4911     }
4912     break;
4913   }
4914   case X86ISD::VPERM2X128:
4915     ImmN = N->getOperand(N->getNumOperands()-1);
4916     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4917     if (Mask.empty()) return false;
4918     break;
4919   case X86ISD::MOVDDUP:
4920   case X86ISD::MOVLHPD:
4921   case X86ISD::MOVLPD:
4922   case X86ISD::MOVLPS:
4923   case X86ISD::MOVSHDUP:
4924   case X86ISD::MOVSLDUP:
4925     // Not yet implemented
4926     return false;
4927   default: llvm_unreachable("unknown target shuffle node");
4928   }
4929
4930   return true;
4931 }
4932
4933 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4934 /// element of the result of the vector shuffle.
4935 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4936                                    unsigned Depth) {
4937   if (Depth == 6)
4938     return SDValue();  // Limit search depth.
4939
4940   SDValue V = SDValue(N, 0);
4941   EVT VT = V.getValueType();
4942   unsigned Opcode = V.getOpcode();
4943
4944   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4945   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4946     int Elt = SV->getMaskElt(Index);
4947
4948     if (Elt < 0)
4949       return DAG.getUNDEF(VT.getVectorElementType());
4950
4951     unsigned NumElems = VT.getVectorNumElements();
4952     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4953                                          : SV->getOperand(1);
4954     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4955   }
4956
4957   // Recurse into target specific vector shuffles to find scalars.
4958   if (isTargetShuffle(Opcode)) {
4959     MVT ShufVT = V.getValueType().getSimpleVT();
4960     unsigned NumElems = ShufVT.getVectorNumElements();
4961     SmallVector<int, 16> ShuffleMask;
4962     bool IsUnary;
4963
4964     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4965       return SDValue();
4966
4967     int Elt = ShuffleMask[Index];
4968     if (Elt < 0)
4969       return DAG.getUNDEF(ShufVT.getVectorElementType());
4970
4971     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4972                                          : N->getOperand(1);
4973     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4974                                Depth+1);
4975   }
4976
4977   // Actual nodes that may contain scalar elements
4978   if (Opcode == ISD::BITCAST) {
4979     V = V.getOperand(0);
4980     EVT SrcVT = V.getValueType();
4981     unsigned NumElems = VT.getVectorNumElements();
4982
4983     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4984       return SDValue();
4985   }
4986
4987   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4988     return (Index == 0) ? V.getOperand(0)
4989                         : DAG.getUNDEF(VT.getVectorElementType());
4990
4991   if (V.getOpcode() == ISD::BUILD_VECTOR)
4992     return V.getOperand(Index);
4993
4994   return SDValue();
4995 }
4996
4997 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4998 /// shuffle operation which come from a consecutively from a zero. The
4999 /// search can start in two different directions, from left or right.
5000 /// We count undefs as zeros until PreferredNum is reached.
5001 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5002                                          unsigned NumElems, bool ZerosFromLeft,
5003                                          SelectionDAG &DAG,
5004                                          unsigned PreferredNum = -1U) {
5005   unsigned NumZeros = 0;
5006   for (unsigned i = 0; i != NumElems; ++i) {
5007     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5008     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5009     if (!Elt.getNode())
5010       break;
5011
5012     if (X86::isZeroNode(Elt))
5013       ++NumZeros;
5014     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5015       NumZeros = std::min(NumZeros + 1, PreferredNum);
5016     else
5017       break;
5018   }
5019
5020   return NumZeros;
5021 }
5022
5023 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5024 /// correspond consecutively to elements from one of the vector operands,
5025 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5026 static
5027 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5028                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5029                               unsigned NumElems, unsigned &OpNum) {
5030   bool SeenV1 = false;
5031   bool SeenV2 = false;
5032
5033   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5034     int Idx = SVOp->getMaskElt(i);
5035     // Ignore undef indicies
5036     if (Idx < 0)
5037       continue;
5038
5039     if (Idx < (int)NumElems)
5040       SeenV1 = true;
5041     else
5042       SeenV2 = true;
5043
5044     // Only accept consecutive elements from the same vector
5045     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5046       return false;
5047   }
5048
5049   OpNum = SeenV1 ? 0 : 1;
5050   return true;
5051 }
5052
5053 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5054 /// logical left shift of a vector.
5055 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5056                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5057   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5058   unsigned NumZeros = getNumOfConsecutiveZeros(
5059       SVOp, NumElems, false /* check zeros from right */, DAG,
5060       SVOp->getMaskElt(0));
5061   unsigned OpSrc;
5062
5063   if (!NumZeros)
5064     return false;
5065
5066   // Considering the elements in the mask that are not consecutive zeros,
5067   // check if they consecutively come from only one of the source vectors.
5068   //
5069   //               V1 = {X, A, B, C}     0
5070   //                         \  \  \    /
5071   //   vector_shuffle V1, V2 <1, 2, 3, X>
5072   //
5073   if (!isShuffleMaskConsecutive(SVOp,
5074             0,                   // Mask Start Index
5075             NumElems-NumZeros,   // Mask End Index(exclusive)
5076             NumZeros,            // Where to start looking in the src vector
5077             NumElems,            // Number of elements in vector
5078             OpSrc))              // Which source operand ?
5079     return false;
5080
5081   isLeft = false;
5082   ShAmt = NumZeros;
5083   ShVal = SVOp->getOperand(OpSrc);
5084   return true;
5085 }
5086
5087 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5088 /// logical left shift of a vector.
5089 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5090                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5091   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5092   unsigned NumZeros = getNumOfConsecutiveZeros(
5093       SVOp, NumElems, true /* check zeros from left */, DAG,
5094       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5095   unsigned OpSrc;
5096
5097   if (!NumZeros)
5098     return false;
5099
5100   // Considering the elements in the mask that are not consecutive zeros,
5101   // check if they consecutively come from only one of the source vectors.
5102   //
5103   //                           0    { A, B, X, X } = V2
5104   //                          / \    /  /
5105   //   vector_shuffle V1, V2 <X, X, 4, 5>
5106   //
5107   if (!isShuffleMaskConsecutive(SVOp,
5108             NumZeros,     // Mask Start Index
5109             NumElems,     // Mask End Index(exclusive)
5110             0,            // Where to start looking in the src vector
5111             NumElems,     // Number of elements in vector
5112             OpSrc))       // Which source operand ?
5113     return false;
5114
5115   isLeft = true;
5116   ShAmt = NumZeros;
5117   ShVal = SVOp->getOperand(OpSrc);
5118   return true;
5119 }
5120
5121 /// isVectorShift - Returns true if the shuffle can be implemented as a
5122 /// logical left or right shift of a vector.
5123 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5124                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5125   // Although the logic below support any bitwidth size, there are no
5126   // shift instructions which handle more than 128-bit vectors.
5127   if (!SVOp->getValueType(0).is128BitVector())
5128     return false;
5129
5130   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5131       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5132     return true;
5133
5134   return false;
5135 }
5136
5137 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5138 ///
5139 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5140                                        unsigned NumNonZero, unsigned NumZero,
5141                                        SelectionDAG &DAG,
5142                                        const X86Subtarget* Subtarget,
5143                                        const TargetLowering &TLI) {
5144   if (NumNonZero > 8)
5145     return SDValue();
5146
5147   SDLoc dl(Op);
5148   SDValue V(0, 0);
5149   bool First = true;
5150   for (unsigned i = 0; i < 16; ++i) {
5151     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5152     if (ThisIsNonZero && First) {
5153       if (NumZero)
5154         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5155       else
5156         V = DAG.getUNDEF(MVT::v8i16);
5157       First = false;
5158     }
5159
5160     if ((i & 1) != 0) {
5161       SDValue ThisElt(0, 0), LastElt(0, 0);
5162       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5163       if (LastIsNonZero) {
5164         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5165                               MVT::i16, Op.getOperand(i-1));
5166       }
5167       if (ThisIsNonZero) {
5168         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5169         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5170                               ThisElt, DAG.getConstant(8, MVT::i8));
5171         if (LastIsNonZero)
5172           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5173       } else
5174         ThisElt = LastElt;
5175
5176       if (ThisElt.getNode())
5177         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5178                         DAG.getIntPtrConstant(i/2));
5179     }
5180   }
5181
5182   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5183 }
5184
5185 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5186 ///
5187 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5188                                      unsigned NumNonZero, unsigned NumZero,
5189                                      SelectionDAG &DAG,
5190                                      const X86Subtarget* Subtarget,
5191                                      const TargetLowering &TLI) {
5192   if (NumNonZero > 4)
5193     return SDValue();
5194
5195   SDLoc dl(Op);
5196   SDValue V(0, 0);
5197   bool First = true;
5198   for (unsigned i = 0; i < 8; ++i) {
5199     bool isNonZero = (NonZeros & (1 << i)) != 0;
5200     if (isNonZero) {
5201       if (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       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5209                       MVT::v8i16, V, Op.getOperand(i),
5210                       DAG.getIntPtrConstant(i));
5211     }
5212   }
5213
5214   return V;
5215 }
5216
5217 /// getVShift - Return a vector logical shift node.
5218 ///
5219 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5220                          unsigned NumBits, SelectionDAG &DAG,
5221                          const TargetLowering &TLI, SDLoc dl) {
5222   assert(VT.is128BitVector() && "Unknown type for VShift");
5223   EVT ShVT = MVT::v2i64;
5224   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5225   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5226   return DAG.getNode(ISD::BITCAST, dl, VT,
5227                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5228                              DAG.getConstant(NumBits,
5229                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5230 }
5231
5232 SDValue
5233 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5234                                           SelectionDAG &DAG) const {
5235
5236   // Check if the scalar load can be widened into a vector load. And if
5237   // the address is "base + cst" see if the cst can be "absorbed" into
5238   // the shuffle mask.
5239   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5240     SDValue Ptr = LD->getBasePtr();
5241     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5242       return SDValue();
5243     EVT PVT = LD->getValueType(0);
5244     if (PVT != MVT::i32 && PVT != MVT::f32)
5245       return SDValue();
5246
5247     int FI = -1;
5248     int64_t Offset = 0;
5249     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5250       FI = FINode->getIndex();
5251       Offset = 0;
5252     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5253                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5254       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5255       Offset = Ptr.getConstantOperandVal(1);
5256       Ptr = Ptr.getOperand(0);
5257     } else {
5258       return SDValue();
5259     }
5260
5261     // FIXME: 256-bit vector instructions don't require a strict alignment,
5262     // improve this code to support it better.
5263     unsigned RequiredAlign = VT.getSizeInBits()/8;
5264     SDValue Chain = LD->getChain();
5265     // Make sure the stack object alignment is at least 16 or 32.
5266     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5267     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5268       if (MFI->isFixedObjectIndex(FI)) {
5269         // Can't change the alignment. FIXME: It's possible to compute
5270         // the exact stack offset and reference FI + adjust offset instead.
5271         // If someone *really* cares about this. That's the way to implement it.
5272         return SDValue();
5273       } else {
5274         MFI->setObjectAlignment(FI, RequiredAlign);
5275       }
5276     }
5277
5278     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5279     // Ptr + (Offset & ~15).
5280     if (Offset < 0)
5281       return SDValue();
5282     if ((Offset % RequiredAlign) & 3)
5283       return SDValue();
5284     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5285     if (StartOffset)
5286       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5287                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5288
5289     int EltNo = (Offset - StartOffset) >> 2;
5290     unsigned NumElems = VT.getVectorNumElements();
5291
5292     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5293     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5294                              LD->getPointerInfo().getWithOffset(StartOffset),
5295                              false, false, false, 0);
5296
5297     SmallVector<int, 8> Mask;
5298     for (unsigned i = 0; i != NumElems; ++i)
5299       Mask.push_back(EltNo);
5300
5301     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5302   }
5303
5304   return SDValue();
5305 }
5306
5307 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5308 /// vector of type 'VT', see if the elements can be replaced by a single large
5309 /// load which has the same value as a build_vector whose operands are 'elts'.
5310 ///
5311 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5312 ///
5313 /// FIXME: we'd also like to handle the case where the last elements are zero
5314 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5315 /// There's even a handy isZeroNode for that purpose.
5316 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5317                                         SDLoc &DL, SelectionDAG &DAG) {
5318   EVT EltVT = VT.getVectorElementType();
5319   unsigned NumElems = Elts.size();
5320
5321   LoadSDNode *LDBase = NULL;
5322   unsigned LastLoadedElt = -1U;
5323
5324   // For each element in the initializer, see if we've found a load or an undef.
5325   // If we don't find an initial load element, or later load elements are
5326   // non-consecutive, bail out.
5327   for (unsigned i = 0; i < NumElems; ++i) {
5328     SDValue Elt = Elts[i];
5329
5330     if (!Elt.getNode() ||
5331         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5332       return SDValue();
5333     if (!LDBase) {
5334       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5335         return SDValue();
5336       LDBase = cast<LoadSDNode>(Elt.getNode());
5337       LastLoadedElt = i;
5338       continue;
5339     }
5340     if (Elt.getOpcode() == ISD::UNDEF)
5341       continue;
5342
5343     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5344     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5345       return SDValue();
5346     LastLoadedElt = i;
5347   }
5348
5349   // If we have found an entire vector of loads and undefs, then return a large
5350   // load of the entire vector width starting at the base pointer.  If we found
5351   // consecutive loads for the low half, generate a vzext_load node.
5352   if (LastLoadedElt == NumElems - 1) {
5353     SDValue NewLd = SDValue();
5354     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5355       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5356                           LDBase->getPointerInfo(),
5357                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5358                           LDBase->isInvariant(), 0);
5359     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5360                         LDBase->getPointerInfo(),
5361                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5362                         LDBase->isInvariant(), LDBase->getAlignment());
5363
5364     if (LDBase->hasAnyUseOfValue(1)) {
5365       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5366                                      SDValue(LDBase, 1),
5367                                      SDValue(NewLd.getNode(), 1));
5368       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5369       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5370                              SDValue(NewLd.getNode(), 1));
5371     }
5372
5373     return NewLd;
5374   }
5375   if (NumElems == 4 && LastLoadedElt == 1 &&
5376       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5377     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5378     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5379     SDValue ResNode =
5380         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5381                                 array_lengthof(Ops), MVT::i64,
5382                                 LDBase->getPointerInfo(),
5383                                 LDBase->getAlignment(),
5384                                 false/*isVolatile*/, true/*ReadMem*/,
5385                                 false/*WriteMem*/);
5386
5387     // Make sure the newly-created LOAD is in the same position as LDBase in
5388     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5389     // update uses of LDBase's output chain to use the TokenFactor.
5390     if (LDBase->hasAnyUseOfValue(1)) {
5391       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5392                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5393       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5394       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5395                              SDValue(ResNode.getNode(), 1));
5396     }
5397
5398     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5399   }
5400   return SDValue();
5401 }
5402
5403 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5404 /// to generate a splat value for the following cases:
5405 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5406 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5407 /// a scalar load, or a constant.
5408 /// The VBROADCAST node is returned when a pattern is found,
5409 /// or SDValue() otherwise.
5410 SDValue
5411 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5412   if (!Subtarget->hasFp256())
5413     return SDValue();
5414
5415   MVT VT = Op.getValueType().getSimpleVT();
5416   SDLoc dl(Op);
5417
5418   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5419          "Unsupported vector type for broadcast.");
5420
5421   SDValue Ld;
5422   bool ConstSplatVal;
5423
5424   switch (Op.getOpcode()) {
5425     default:
5426       // Unknown pattern found.
5427       return SDValue();
5428
5429     case ISD::BUILD_VECTOR: {
5430       // The BUILD_VECTOR node must be a splat.
5431       if (!isSplatVector(Op.getNode()))
5432         return SDValue();
5433
5434       Ld = Op.getOperand(0);
5435       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5436                      Ld.getOpcode() == ISD::ConstantFP);
5437
5438       // The suspected load node has several users. Make sure that all
5439       // of its users are from the BUILD_VECTOR node.
5440       // Constants may have multiple users.
5441       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5442         return SDValue();
5443       break;
5444     }
5445
5446     case ISD::VECTOR_SHUFFLE: {
5447       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5448
5449       // Shuffles must have a splat mask where the first element is
5450       // broadcasted.
5451       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5452         return SDValue();
5453
5454       SDValue Sc = Op.getOperand(0);
5455       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5456           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5457
5458         if (!Subtarget->hasInt256())
5459           return SDValue();
5460
5461         // Use the register form of the broadcast instruction available on AVX2.
5462         if (VT.is256BitVector())
5463           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5464         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5465       }
5466
5467       Ld = Sc.getOperand(0);
5468       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5469                        Ld.getOpcode() == ISD::ConstantFP);
5470
5471       // The scalar_to_vector node and the suspected
5472       // load node must have exactly one user.
5473       // Constants may have multiple users.
5474       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5475         return SDValue();
5476       break;
5477     }
5478   }
5479
5480   bool Is256 = VT.is256BitVector();
5481
5482   // Handle the broadcasting a single constant scalar from the constant pool
5483   // into a vector. On Sandybridge it is still better to load a constant vector
5484   // from the constant pool and not to broadcast it from a scalar.
5485   if (ConstSplatVal && Subtarget->hasInt256()) {
5486     EVT CVT = Ld.getValueType();
5487     assert(!CVT.isVector() && "Must not broadcast a vector type");
5488     unsigned ScalarSize = CVT.getSizeInBits();
5489
5490     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5491       const Constant *C = 0;
5492       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5493         C = CI->getConstantIntValue();
5494       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5495         C = CF->getConstantFPValue();
5496
5497       assert(C && "Invalid constant type");
5498
5499       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5500       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5501       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5502                        MachinePointerInfo::getConstantPool(),
5503                        false, false, false, Alignment);
5504
5505       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5506     }
5507   }
5508
5509   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5510   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5511
5512   // Handle AVX2 in-register broadcasts.
5513   if (!IsLoad && Subtarget->hasInt256() &&
5514       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5515     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5516
5517   // The scalar source must be a normal load.
5518   if (!IsLoad)
5519     return SDValue();
5520
5521   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5522     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5523
5524   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5525   // double since there is no vbroadcastsd xmm
5526   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5527     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5528       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5529   }
5530
5531   // Unsupported broadcast.
5532   return SDValue();
5533 }
5534
5535 SDValue
5536 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5537   EVT VT = Op.getValueType();
5538
5539   // Skip if insert_vec_elt is not supported.
5540   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5541     return SDValue();
5542
5543   SDLoc DL(Op);
5544   unsigned NumElems = Op.getNumOperands();
5545
5546   SDValue VecIn1;
5547   SDValue VecIn2;
5548   SmallVector<unsigned, 4> InsertIndices;
5549   SmallVector<int, 8> Mask(NumElems, -1);
5550
5551   for (unsigned i = 0; i != NumElems; ++i) {
5552     unsigned Opc = Op.getOperand(i).getOpcode();
5553
5554     if (Opc == ISD::UNDEF)
5555       continue;
5556
5557     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5558       // Quit if more than 1 elements need inserting.
5559       if (InsertIndices.size() > 1)
5560         return SDValue();
5561
5562       InsertIndices.push_back(i);
5563       continue;
5564     }
5565
5566     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5567     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5568
5569     // Quit if extracted from vector of different type.
5570     if (ExtractedFromVec.getValueType() != VT)
5571       return SDValue();
5572
5573     // Quit if non-constant index.
5574     if (!isa<ConstantSDNode>(ExtIdx))
5575       return SDValue();
5576
5577     if (VecIn1.getNode() == 0)
5578       VecIn1 = ExtractedFromVec;
5579     else if (VecIn1 != ExtractedFromVec) {
5580       if (VecIn2.getNode() == 0)
5581         VecIn2 = ExtractedFromVec;
5582       else if (VecIn2 != ExtractedFromVec)
5583         // Quit if more than 2 vectors to shuffle
5584         return SDValue();
5585     }
5586
5587     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5588
5589     if (ExtractedFromVec == VecIn1)
5590       Mask[i] = Idx;
5591     else if (ExtractedFromVec == VecIn2)
5592       Mask[i] = Idx + NumElems;
5593   }
5594
5595   if (VecIn1.getNode() == 0)
5596     return SDValue();
5597
5598   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5599   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5600   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5601     unsigned Idx = InsertIndices[i];
5602     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5603                      DAG.getIntPtrConstant(Idx));
5604   }
5605
5606   return NV;
5607 }
5608
5609 SDValue
5610 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5611   SDLoc dl(Op);
5612
5613   MVT VT = Op.getValueType().getSimpleVT();
5614   MVT ExtVT = VT.getVectorElementType();
5615   unsigned NumElems = Op.getNumOperands();
5616
5617   // Vectors containing all zeros can be matched by pxor and xorps later
5618   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5619     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5620     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5621     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5622       return Op;
5623
5624     return getZeroVector(VT, Subtarget, DAG, dl);
5625   }
5626
5627   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5628   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5629   // vpcmpeqd on 256-bit vectors.
5630   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5631     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5632       return Op;
5633
5634     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5635   }
5636
5637   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5638   if (Broadcast.getNode())
5639     return Broadcast;
5640
5641   unsigned EVTBits = ExtVT.getSizeInBits();
5642
5643   unsigned NumZero  = 0;
5644   unsigned NumNonZero = 0;
5645   unsigned NonZeros = 0;
5646   bool IsAllConstants = true;
5647   SmallSet<SDValue, 8> Values;
5648   for (unsigned i = 0; i < NumElems; ++i) {
5649     SDValue Elt = Op.getOperand(i);
5650     if (Elt.getOpcode() == ISD::UNDEF)
5651       continue;
5652     Values.insert(Elt);
5653     if (Elt.getOpcode() != ISD::Constant &&
5654         Elt.getOpcode() != ISD::ConstantFP)
5655       IsAllConstants = false;
5656     if (X86::isZeroNode(Elt))
5657       NumZero++;
5658     else {
5659       NonZeros |= (1 << i);
5660       NumNonZero++;
5661     }
5662   }
5663
5664   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5665   if (NumNonZero == 0)
5666     return DAG.getUNDEF(VT);
5667
5668   // Special case for single non-zero, non-undef, element.
5669   if (NumNonZero == 1) {
5670     unsigned Idx = countTrailingZeros(NonZeros);
5671     SDValue Item = Op.getOperand(Idx);
5672
5673     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5674     // the value are obviously zero, truncate the value to i32 and do the
5675     // insertion that way.  Only do this if the value is non-constant or if the
5676     // value is a constant being inserted into element 0.  It is cheaper to do
5677     // a constant pool load than it is to do a movd + shuffle.
5678     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5679         (!IsAllConstants || Idx == 0)) {
5680       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5681         // Handle SSE only.
5682         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5683         EVT VecVT = MVT::v4i32;
5684         unsigned VecElts = 4;
5685
5686         // Truncate the value (which may itself be a constant) to i32, and
5687         // convert it to a vector with movd (S2V+shuffle to zero extend).
5688         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5689         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5690         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5691
5692         // Now we have our 32-bit value zero extended in the low element of
5693         // a vector.  If Idx != 0, swizzle it into place.
5694         if (Idx != 0) {
5695           SmallVector<int, 4> Mask;
5696           Mask.push_back(Idx);
5697           for (unsigned i = 1; i != VecElts; ++i)
5698             Mask.push_back(i);
5699           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5700                                       &Mask[0]);
5701         }
5702         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5703       }
5704     }
5705
5706     // If we have a constant or non-constant insertion into the low element of
5707     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5708     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5709     // depending on what the source datatype is.
5710     if (Idx == 0) {
5711       if (NumZero == 0)
5712         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5713
5714       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5715           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5716         if (VT.is256BitVector()) {
5717           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5718           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5719                              Item, DAG.getIntPtrConstant(0));
5720         }
5721         assert(VT.is128BitVector() && "Expected an SSE value type!");
5722         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5723         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5724         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5725       }
5726
5727       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5728         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5729         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5730         if (VT.is256BitVector()) {
5731           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5732           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5733         } else {
5734           assert(VT.is128BitVector() && "Expected an SSE value type!");
5735           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5736         }
5737         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5738       }
5739     }
5740
5741     // Is it a vector logical left shift?
5742     if (NumElems == 2 && Idx == 1 &&
5743         X86::isZeroNode(Op.getOperand(0)) &&
5744         !X86::isZeroNode(Op.getOperand(1))) {
5745       unsigned NumBits = VT.getSizeInBits();
5746       return getVShift(true, VT,
5747                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5748                                    VT, Op.getOperand(1)),
5749                        NumBits/2, DAG, *this, dl);
5750     }
5751
5752     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5753       return SDValue();
5754
5755     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5756     // is a non-constant being inserted into an element other than the low one,
5757     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5758     // movd/movss) to move this into the low element, then shuffle it into
5759     // place.
5760     if (EVTBits == 32) {
5761       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5762
5763       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5764       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5765       SmallVector<int, 8> MaskVec;
5766       for (unsigned i = 0; i != NumElems; ++i)
5767         MaskVec.push_back(i == Idx ? 0 : 1);
5768       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5769     }
5770   }
5771
5772   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5773   if (Values.size() == 1) {
5774     if (EVTBits == 32) {
5775       // Instead of a shuffle like this:
5776       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5777       // Check if it's possible to issue this instead.
5778       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5779       unsigned Idx = countTrailingZeros(NonZeros);
5780       SDValue Item = Op.getOperand(Idx);
5781       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5782         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5783     }
5784     return SDValue();
5785   }
5786
5787   // A vector full of immediates; various special cases are already
5788   // handled, so this is best done with a single constant-pool load.
5789   if (IsAllConstants)
5790     return SDValue();
5791
5792   // For AVX-length vectors, build the individual 128-bit pieces and use
5793   // shuffles to put them in place.
5794   if (VT.is256BitVector()) {
5795     SmallVector<SDValue, 32> V;
5796     for (unsigned i = 0; i != NumElems; ++i)
5797       V.push_back(Op.getOperand(i));
5798
5799     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5800
5801     // Build both the lower and upper subvector.
5802     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5803     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5804                                 NumElems/2);
5805
5806     // Recreate the wider vector with the lower and upper part.
5807     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5808   }
5809
5810   // Let legalizer expand 2-wide build_vectors.
5811   if (EVTBits == 64) {
5812     if (NumNonZero == 1) {
5813       // One half is zero or undef.
5814       unsigned Idx = countTrailingZeros(NonZeros);
5815       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5816                                  Op.getOperand(Idx));
5817       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5818     }
5819     return SDValue();
5820   }
5821
5822   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5823   if (EVTBits == 8 && NumElems == 16) {
5824     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5825                                         Subtarget, *this);
5826     if (V.getNode()) return V;
5827   }
5828
5829   if (EVTBits == 16 && NumElems == 8) {
5830     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5831                                       Subtarget, *this);
5832     if (V.getNode()) return V;
5833   }
5834
5835   // If element VT is == 32 bits, turn it into a number of shuffles.
5836   SmallVector<SDValue, 8> V(NumElems);
5837   if (NumElems == 4 && NumZero > 0) {
5838     for (unsigned i = 0; i < 4; ++i) {
5839       bool isZero = !(NonZeros & (1 << i));
5840       if (isZero)
5841         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5842       else
5843         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5844     }
5845
5846     for (unsigned i = 0; i < 2; ++i) {
5847       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5848         default: break;
5849         case 0:
5850           V[i] = V[i*2];  // Must be a zero vector.
5851           break;
5852         case 1:
5853           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5854           break;
5855         case 2:
5856           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5857           break;
5858         case 3:
5859           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5860           break;
5861       }
5862     }
5863
5864     bool Reverse1 = (NonZeros & 0x3) == 2;
5865     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5866     int MaskVec[] = {
5867       Reverse1 ? 1 : 0,
5868       Reverse1 ? 0 : 1,
5869       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5870       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5871     };
5872     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5873   }
5874
5875   if (Values.size() > 1 && VT.is128BitVector()) {
5876     // Check for a build vector of consecutive loads.
5877     for (unsigned i = 0; i < NumElems; ++i)
5878       V[i] = Op.getOperand(i);
5879
5880     // Check for elements which are consecutive loads.
5881     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5882     if (LD.getNode())
5883       return LD;
5884
5885     // Check for a build vector from mostly shuffle plus few inserting.
5886     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5887     if (Sh.getNode())
5888       return Sh;
5889
5890     // For SSE 4.1, use insertps to put the high elements into the low element.
5891     if (getSubtarget()->hasSSE41()) {
5892       SDValue Result;
5893       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5894         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5895       else
5896         Result = DAG.getUNDEF(VT);
5897
5898       for (unsigned i = 1; i < NumElems; ++i) {
5899         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5900         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5901                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5902       }
5903       return Result;
5904     }
5905
5906     // Otherwise, expand into a number of unpckl*, start by extending each of
5907     // our (non-undef) elements to the full vector width with the element in the
5908     // bottom slot of the vector (which generates no code for SSE).
5909     for (unsigned i = 0; i < NumElems; ++i) {
5910       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5911         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5912       else
5913         V[i] = DAG.getUNDEF(VT);
5914     }
5915
5916     // Next, we iteratively mix elements, e.g. for v4f32:
5917     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5918     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5919     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5920     unsigned EltStride = NumElems >> 1;
5921     while (EltStride != 0) {
5922       for (unsigned i = 0; i < EltStride; ++i) {
5923         // If V[i+EltStride] is undef and this is the first round of mixing,
5924         // then it is safe to just drop this shuffle: V[i] is already in the
5925         // right place, the one element (since it's the first round) being
5926         // inserted as undef can be dropped.  This isn't safe for successive
5927         // rounds because they will permute elements within both vectors.
5928         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5929             EltStride == NumElems/2)
5930           continue;
5931
5932         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5933       }
5934       EltStride >>= 1;
5935     }
5936     return V[0];
5937   }
5938   return SDValue();
5939 }
5940
5941 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5942 // to create 256-bit vectors from two other 128-bit ones.
5943 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5944   SDLoc dl(Op);
5945   MVT ResVT = Op.getValueType().getSimpleVT();
5946
5947   assert((ResVT.is256BitVector() ||
5948           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5949
5950   SDValue V1 = Op.getOperand(0);
5951   SDValue V2 = Op.getOperand(1);
5952   unsigned NumElems = ResVT.getVectorNumElements();
5953   if(ResVT.is256BitVector())
5954     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5955
5956   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5957 }
5958
5959 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5960   assert(Op.getNumOperands() == 2);
5961
5962   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
5963   // from two other 128-bit ones.
5964   return LowerAVXCONCAT_VECTORS(Op, DAG);
5965 }
5966
5967 // Try to lower a shuffle node into a simple blend instruction.
5968 static SDValue
5969 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5970                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5971   SDValue V1 = SVOp->getOperand(0);
5972   SDValue V2 = SVOp->getOperand(1);
5973   SDLoc dl(SVOp);
5974   MVT VT = SVOp->getValueType(0).getSimpleVT();
5975   MVT EltVT = VT.getVectorElementType();
5976   unsigned NumElems = VT.getVectorNumElements();
5977
5978   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5979     return SDValue();
5980   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5981     return SDValue();
5982
5983   // Check the mask for BLEND and build the value.
5984   unsigned MaskValue = 0;
5985   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5986   unsigned NumLanes = (NumElems-1)/8 + 1;
5987   unsigned NumElemsInLane = NumElems / NumLanes;
5988
5989   // Blend for v16i16 should be symetric for the both lanes.
5990   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5991
5992     int SndLaneEltIdx = (NumLanes == 2) ?
5993       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5994     int EltIdx = SVOp->getMaskElt(i);
5995
5996     if ((EltIdx < 0 || EltIdx == (int)i) &&
5997         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5998       continue;
5999
6000     if (((unsigned)EltIdx == (i + NumElems)) &&
6001         (SndLaneEltIdx < 0 ||
6002          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6003       MaskValue |= (1<<i);
6004     else
6005       return SDValue();
6006   }
6007
6008   // Convert i32 vectors to floating point if it is not AVX2.
6009   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6010   MVT BlendVT = VT;
6011   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6012     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6013                                NumElems);
6014     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6015     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6016   }
6017
6018   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6019                             DAG.getConstant(MaskValue, MVT::i32));
6020   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6021 }
6022
6023 // v8i16 shuffles - Prefer shuffles in the following order:
6024 // 1. [all]   pshuflw, pshufhw, optional move
6025 // 2. [ssse3] 1 x pshufb
6026 // 3. [ssse3] 2 x pshufb + 1 x por
6027 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6028 static SDValue
6029 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6030                          SelectionDAG &DAG) {
6031   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6032   SDValue V1 = SVOp->getOperand(0);
6033   SDValue V2 = SVOp->getOperand(1);
6034   SDLoc dl(SVOp);
6035   SmallVector<int, 8> MaskVals;
6036
6037   // Determine if more than 1 of the words in each of the low and high quadwords
6038   // of the result come from the same quadword of one of the two inputs.  Undef
6039   // mask values count as coming from any quadword, for better codegen.
6040   unsigned LoQuad[] = { 0, 0, 0, 0 };
6041   unsigned HiQuad[] = { 0, 0, 0, 0 };
6042   std::bitset<4> InputQuads;
6043   for (unsigned i = 0; i < 8; ++i) {
6044     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6045     int EltIdx = SVOp->getMaskElt(i);
6046     MaskVals.push_back(EltIdx);
6047     if (EltIdx < 0) {
6048       ++Quad[0];
6049       ++Quad[1];
6050       ++Quad[2];
6051       ++Quad[3];
6052       continue;
6053     }
6054     ++Quad[EltIdx / 4];
6055     InputQuads.set(EltIdx / 4);
6056   }
6057
6058   int BestLoQuad = -1;
6059   unsigned MaxQuad = 1;
6060   for (unsigned i = 0; i < 4; ++i) {
6061     if (LoQuad[i] > MaxQuad) {
6062       BestLoQuad = i;
6063       MaxQuad = LoQuad[i];
6064     }
6065   }
6066
6067   int BestHiQuad = -1;
6068   MaxQuad = 1;
6069   for (unsigned i = 0; i < 4; ++i) {
6070     if (HiQuad[i] > MaxQuad) {
6071       BestHiQuad = i;
6072       MaxQuad = HiQuad[i];
6073     }
6074   }
6075
6076   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6077   // of the two input vectors, shuffle them into one input vector so only a
6078   // single pshufb instruction is necessary. If There are more than 2 input
6079   // quads, disable the next transformation since it does not help SSSE3.
6080   bool V1Used = InputQuads[0] || InputQuads[1];
6081   bool V2Used = InputQuads[2] || InputQuads[3];
6082   if (Subtarget->hasSSSE3()) {
6083     if (InputQuads.count() == 2 && V1Used && V2Used) {
6084       BestLoQuad = InputQuads[0] ? 0 : 1;
6085       BestHiQuad = InputQuads[2] ? 2 : 3;
6086     }
6087     if (InputQuads.count() > 2) {
6088       BestLoQuad = -1;
6089       BestHiQuad = -1;
6090     }
6091   }
6092
6093   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6094   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6095   // words from all 4 input quadwords.
6096   SDValue NewV;
6097   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6098     int MaskV[] = {
6099       BestLoQuad < 0 ? 0 : BestLoQuad,
6100       BestHiQuad < 0 ? 1 : BestHiQuad
6101     };
6102     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6103                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6104                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6105     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6106
6107     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6108     // source words for the shuffle, to aid later transformations.
6109     bool AllWordsInNewV = true;
6110     bool InOrder[2] = { true, true };
6111     for (unsigned i = 0; i != 8; ++i) {
6112       int idx = MaskVals[i];
6113       if (idx != (int)i)
6114         InOrder[i/4] = false;
6115       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6116         continue;
6117       AllWordsInNewV = false;
6118       break;
6119     }
6120
6121     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6122     if (AllWordsInNewV) {
6123       for (int i = 0; i != 8; ++i) {
6124         int idx = MaskVals[i];
6125         if (idx < 0)
6126           continue;
6127         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6128         if ((idx != i) && idx < 4)
6129           pshufhw = false;
6130         if ((idx != i) && idx > 3)
6131           pshuflw = false;
6132       }
6133       V1 = NewV;
6134       V2Used = false;
6135       BestLoQuad = 0;
6136       BestHiQuad = 1;
6137     }
6138
6139     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6140     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6141     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6142       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6143       unsigned TargetMask = 0;
6144       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6145                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6146       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6147       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6148                              getShufflePSHUFLWImmediate(SVOp);
6149       V1 = NewV.getOperand(0);
6150       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6151     }
6152   }
6153
6154   // Promote splats to a larger type which usually leads to more efficient code.
6155   // FIXME: Is this true if pshufb is available?
6156   if (SVOp->isSplat())
6157     return PromoteSplat(SVOp, DAG);
6158
6159   // If we have SSSE3, and all words of the result are from 1 input vector,
6160   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6161   // is present, fall back to case 4.
6162   if (Subtarget->hasSSSE3()) {
6163     SmallVector<SDValue,16> pshufbMask;
6164
6165     // If we have elements from both input vectors, set the high bit of the
6166     // shuffle mask element to zero out elements that come from V2 in the V1
6167     // mask, and elements that come from V1 in the V2 mask, so that the two
6168     // results can be OR'd together.
6169     bool TwoInputs = V1Used && V2Used;
6170     for (unsigned i = 0; i != 8; ++i) {
6171       int EltIdx = MaskVals[i] * 2;
6172       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6173       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6174       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6175       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6176     }
6177     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6178     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6179                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6180                                  MVT::v16i8, &pshufbMask[0], 16));
6181     if (!TwoInputs)
6182       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6183
6184     // Calculate the shuffle mask for the second input, shuffle it, and
6185     // OR it with the first shuffled input.
6186     pshufbMask.clear();
6187     for (unsigned i = 0; i != 8; ++i) {
6188       int EltIdx = MaskVals[i] * 2;
6189       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6190       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6191       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6192       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6193     }
6194     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6195     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6196                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6197                                  MVT::v16i8, &pshufbMask[0], 16));
6198     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6199     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6200   }
6201
6202   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6203   // and update MaskVals with new element order.
6204   std::bitset<8> InOrder;
6205   if (BestLoQuad >= 0) {
6206     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6207     for (int i = 0; i != 4; ++i) {
6208       int idx = MaskVals[i];
6209       if (idx < 0) {
6210         InOrder.set(i);
6211       } else if ((idx / 4) == BestLoQuad) {
6212         MaskV[i] = idx & 3;
6213         InOrder.set(i);
6214       }
6215     }
6216     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6217                                 &MaskV[0]);
6218
6219     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6220       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6221       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6222                                   NewV.getOperand(0),
6223                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6224     }
6225   }
6226
6227   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6228   // and update MaskVals with the new element order.
6229   if (BestHiQuad >= 0) {
6230     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6231     for (unsigned i = 4; i != 8; ++i) {
6232       int idx = MaskVals[i];
6233       if (idx < 0) {
6234         InOrder.set(i);
6235       } else if ((idx / 4) == BestHiQuad) {
6236         MaskV[i] = (idx & 3) + 4;
6237         InOrder.set(i);
6238       }
6239     }
6240     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6241                                 &MaskV[0]);
6242
6243     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6244       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6245       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6246                                   NewV.getOperand(0),
6247                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6248     }
6249   }
6250
6251   // In case BestHi & BestLo were both -1, which means each quadword has a word
6252   // from each of the four input quadwords, calculate the InOrder bitvector now
6253   // before falling through to the insert/extract cleanup.
6254   if (BestLoQuad == -1 && BestHiQuad == -1) {
6255     NewV = V1;
6256     for (int i = 0; i != 8; ++i)
6257       if (MaskVals[i] < 0 || MaskVals[i] == i)
6258         InOrder.set(i);
6259   }
6260
6261   // The other elements are put in the right place using pextrw and pinsrw.
6262   for (unsigned i = 0; i != 8; ++i) {
6263     if (InOrder[i])
6264       continue;
6265     int EltIdx = MaskVals[i];
6266     if (EltIdx < 0)
6267       continue;
6268     SDValue ExtOp = (EltIdx < 8) ?
6269       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6270                   DAG.getIntPtrConstant(EltIdx)) :
6271       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6272                   DAG.getIntPtrConstant(EltIdx - 8));
6273     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6274                        DAG.getIntPtrConstant(i));
6275   }
6276   return NewV;
6277 }
6278
6279 // v16i8 shuffles - Prefer shuffles in the following order:
6280 // 1. [ssse3] 1 x pshufb
6281 // 2. [ssse3] 2 x pshufb + 1 x por
6282 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6283 static
6284 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6285                                  SelectionDAG &DAG,
6286                                  const X86TargetLowering &TLI) {
6287   SDValue V1 = SVOp->getOperand(0);
6288   SDValue V2 = SVOp->getOperand(1);
6289   SDLoc dl(SVOp);
6290   ArrayRef<int> MaskVals = SVOp->getMask();
6291
6292   // Promote splats to a larger type which usually leads to more efficient code.
6293   // FIXME: Is this true if pshufb is available?
6294   if (SVOp->isSplat())
6295     return PromoteSplat(SVOp, DAG);
6296
6297   // If we have SSSE3, case 1 is generated when all result bytes come from
6298   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6299   // present, fall back to case 3.
6300
6301   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6302   if (TLI.getSubtarget()->hasSSSE3()) {
6303     SmallVector<SDValue,16> pshufbMask;
6304
6305     // If all result elements are from one input vector, then only translate
6306     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6307     //
6308     // Otherwise, we have elements from both input vectors, and must zero out
6309     // elements that come from V2 in the first mask, and V1 in the second mask
6310     // so that we can OR them together.
6311     for (unsigned i = 0; i != 16; ++i) {
6312       int EltIdx = MaskVals[i];
6313       if (EltIdx < 0 || EltIdx >= 16)
6314         EltIdx = 0x80;
6315       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6316     }
6317     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6318                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6319                                  MVT::v16i8, &pshufbMask[0], 16));
6320
6321     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6322     // the 2nd operand if it's undefined or zero.
6323     if (V2.getOpcode() == ISD::UNDEF ||
6324         ISD::isBuildVectorAllZeros(V2.getNode()))
6325       return V1;
6326
6327     // Calculate the shuffle mask for the second input, shuffle it, and
6328     // OR it with the first shuffled input.
6329     pshufbMask.clear();
6330     for (unsigned i = 0; i != 16; ++i) {
6331       int EltIdx = MaskVals[i];
6332       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6333       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6334     }
6335     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6336                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6337                                  MVT::v16i8, &pshufbMask[0], 16));
6338     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6339   }
6340
6341   // No SSSE3 - Calculate in place words and then fix all out of place words
6342   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6343   // the 16 different words that comprise the two doublequadword input vectors.
6344   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6345   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6346   SDValue NewV = V1;
6347   for (int i = 0; i != 8; ++i) {
6348     int Elt0 = MaskVals[i*2];
6349     int Elt1 = MaskVals[i*2+1];
6350
6351     // This word of the result is all undef, skip it.
6352     if (Elt0 < 0 && Elt1 < 0)
6353       continue;
6354
6355     // This word of the result is already in the correct place, skip it.
6356     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6357       continue;
6358
6359     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6360     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6361     SDValue InsElt;
6362
6363     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6364     // using a single extract together, load it and store it.
6365     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6366       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6367                            DAG.getIntPtrConstant(Elt1 / 2));
6368       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6369                         DAG.getIntPtrConstant(i));
6370       continue;
6371     }
6372
6373     // If Elt1 is defined, extract it from the appropriate source.  If the
6374     // source byte is not also odd, shift the extracted word left 8 bits
6375     // otherwise clear the bottom 8 bits if we need to do an or.
6376     if (Elt1 >= 0) {
6377       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6378                            DAG.getIntPtrConstant(Elt1 / 2));
6379       if ((Elt1 & 1) == 0)
6380         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6381                              DAG.getConstant(8,
6382                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6383       else if (Elt0 >= 0)
6384         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6385                              DAG.getConstant(0xFF00, MVT::i16));
6386     }
6387     // If Elt0 is defined, extract it from the appropriate source.  If the
6388     // source byte is not also even, shift the extracted word right 8 bits. If
6389     // Elt1 was also defined, OR the extracted values together before
6390     // inserting them in the result.
6391     if (Elt0 >= 0) {
6392       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6393                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6394       if ((Elt0 & 1) != 0)
6395         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6396                               DAG.getConstant(8,
6397                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6398       else if (Elt1 >= 0)
6399         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6400                              DAG.getConstant(0x00FF, MVT::i16));
6401       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6402                          : InsElt0;
6403     }
6404     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6405                        DAG.getIntPtrConstant(i));
6406   }
6407   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6408 }
6409
6410 // v32i8 shuffles - Translate to VPSHUFB if possible.
6411 static
6412 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6413                                  const X86Subtarget *Subtarget,
6414                                  SelectionDAG &DAG) {
6415   MVT VT = SVOp->getValueType(0).getSimpleVT();
6416   SDValue V1 = SVOp->getOperand(0);
6417   SDValue V2 = SVOp->getOperand(1);
6418   SDLoc dl(SVOp);
6419   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6420
6421   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6422   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6423   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6424
6425   // VPSHUFB may be generated if
6426   // (1) one of input vector is undefined or zeroinitializer.
6427   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6428   // And (2) the mask indexes don't cross the 128-bit lane.
6429   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6430       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6431     return SDValue();
6432
6433   if (V1IsAllZero && !V2IsAllZero) {
6434     CommuteVectorShuffleMask(MaskVals, 32);
6435     V1 = V2;
6436   }
6437   SmallVector<SDValue, 32> pshufbMask;
6438   for (unsigned i = 0; i != 32; i++) {
6439     int EltIdx = MaskVals[i];
6440     if (EltIdx < 0 || EltIdx >= 32)
6441       EltIdx = 0x80;
6442     else {
6443       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6444         // Cross lane is not allowed.
6445         return SDValue();
6446       EltIdx &= 0xf;
6447     }
6448     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6449   }
6450   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6451                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6452                                   MVT::v32i8, &pshufbMask[0], 32));
6453 }
6454
6455 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6456 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6457 /// done when every pair / quad of shuffle mask elements point to elements in
6458 /// the right sequence. e.g.
6459 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6460 static
6461 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6462                                  SelectionDAG &DAG) {
6463   MVT VT = SVOp->getValueType(0).getSimpleVT();
6464   SDLoc dl(SVOp);
6465   unsigned NumElems = VT.getVectorNumElements();
6466   MVT NewVT;
6467   unsigned Scale;
6468   switch (VT.SimpleTy) {
6469   default: llvm_unreachable("Unexpected!");
6470   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6471   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6472   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6473   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6474   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6475   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6476   }
6477
6478   SmallVector<int, 8> MaskVec;
6479   for (unsigned i = 0; i != NumElems; i += Scale) {
6480     int StartIdx = -1;
6481     for (unsigned j = 0; j != Scale; ++j) {
6482       int EltIdx = SVOp->getMaskElt(i+j);
6483       if (EltIdx < 0)
6484         continue;
6485       if (StartIdx < 0)
6486         StartIdx = (EltIdx / Scale);
6487       if (EltIdx != (int)(StartIdx*Scale + j))
6488         return SDValue();
6489     }
6490     MaskVec.push_back(StartIdx);
6491   }
6492
6493   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6494   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6495   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6496 }
6497
6498 /// getVZextMovL - Return a zero-extending vector move low node.
6499 ///
6500 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6501                             SDValue SrcOp, SelectionDAG &DAG,
6502                             const X86Subtarget *Subtarget, SDLoc dl) {
6503   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6504     LoadSDNode *LD = NULL;
6505     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6506       LD = dyn_cast<LoadSDNode>(SrcOp);
6507     if (!LD) {
6508       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6509       // instead.
6510       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6511       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6512           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6513           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6514           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6515         // PR2108
6516         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6517         return DAG.getNode(ISD::BITCAST, dl, VT,
6518                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6519                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6520                                                    OpVT,
6521                                                    SrcOp.getOperand(0)
6522                                                           .getOperand(0))));
6523       }
6524     }
6525   }
6526
6527   return DAG.getNode(ISD::BITCAST, dl, VT,
6528                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6529                                  DAG.getNode(ISD::BITCAST, dl,
6530                                              OpVT, SrcOp)));
6531 }
6532
6533 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6534 /// which could not be matched by any known target speficic shuffle
6535 static SDValue
6536 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6537
6538   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6539   if (NewOp.getNode())
6540     return NewOp;
6541
6542   MVT VT = SVOp->getValueType(0).getSimpleVT();
6543
6544   unsigned NumElems = VT.getVectorNumElements();
6545   unsigned NumLaneElems = NumElems / 2;
6546
6547   SDLoc dl(SVOp);
6548   MVT EltVT = VT.getVectorElementType();
6549   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6550   SDValue Output[2];
6551
6552   SmallVector<int, 16> Mask;
6553   for (unsigned l = 0; l < 2; ++l) {
6554     // Build a shuffle mask for the output, discovering on the fly which
6555     // input vectors to use as shuffle operands (recorded in InputUsed).
6556     // If building a suitable shuffle vector proves too hard, then bail
6557     // out with UseBuildVector set.
6558     bool UseBuildVector = false;
6559     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6560     unsigned LaneStart = l * NumLaneElems;
6561     for (unsigned i = 0; i != NumLaneElems; ++i) {
6562       // The mask element.  This indexes into the input.
6563       int Idx = SVOp->getMaskElt(i+LaneStart);
6564       if (Idx < 0) {
6565         // the mask element does not index into any input vector.
6566         Mask.push_back(-1);
6567         continue;
6568       }
6569
6570       // The input vector this mask element indexes into.
6571       int Input = Idx / NumLaneElems;
6572
6573       // Turn the index into an offset from the start of the input vector.
6574       Idx -= Input * NumLaneElems;
6575
6576       // Find or create a shuffle vector operand to hold this input.
6577       unsigned OpNo;
6578       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6579         if (InputUsed[OpNo] == Input)
6580           // This input vector is already an operand.
6581           break;
6582         if (InputUsed[OpNo] < 0) {
6583           // Create a new operand for this input vector.
6584           InputUsed[OpNo] = Input;
6585           break;
6586         }
6587       }
6588
6589       if (OpNo >= array_lengthof(InputUsed)) {
6590         // More than two input vectors used!  Give up on trying to create a
6591         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6592         UseBuildVector = true;
6593         break;
6594       }
6595
6596       // Add the mask index for the new shuffle vector.
6597       Mask.push_back(Idx + OpNo * NumLaneElems);
6598     }
6599
6600     if (UseBuildVector) {
6601       SmallVector<SDValue, 16> SVOps;
6602       for (unsigned i = 0; i != NumLaneElems; ++i) {
6603         // The mask element.  This indexes into the input.
6604         int Idx = SVOp->getMaskElt(i+LaneStart);
6605         if (Idx < 0) {
6606           SVOps.push_back(DAG.getUNDEF(EltVT));
6607           continue;
6608         }
6609
6610         // The input vector this mask element indexes into.
6611         int Input = Idx / NumElems;
6612
6613         // Turn the index into an offset from the start of the input vector.
6614         Idx -= Input * NumElems;
6615
6616         // Extract the vector element by hand.
6617         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6618                                     SVOp->getOperand(Input),
6619                                     DAG.getIntPtrConstant(Idx)));
6620       }
6621
6622       // Construct the output using a BUILD_VECTOR.
6623       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6624                               SVOps.size());
6625     } else if (InputUsed[0] < 0) {
6626       // No input vectors were used! The result is undefined.
6627       Output[l] = DAG.getUNDEF(NVT);
6628     } else {
6629       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6630                                         (InputUsed[0] % 2) * NumLaneElems,
6631                                         DAG, dl);
6632       // If only one input was used, use an undefined vector for the other.
6633       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6634         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6635                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6636       // At least one input vector was used. Create a new shuffle vector.
6637       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6638     }
6639
6640     Mask.clear();
6641   }
6642
6643   // Concatenate the result back
6644   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6645 }
6646
6647 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6648 /// 4 elements, and match them with several different shuffle types.
6649 static SDValue
6650 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6651   SDValue V1 = SVOp->getOperand(0);
6652   SDValue V2 = SVOp->getOperand(1);
6653   SDLoc dl(SVOp);
6654   MVT VT = SVOp->getValueType(0).getSimpleVT();
6655
6656   assert(VT.is128BitVector() && "Unsupported vector size");
6657
6658   std::pair<int, int> Locs[4];
6659   int Mask1[] = { -1, -1, -1, -1 };
6660   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6661
6662   unsigned NumHi = 0;
6663   unsigned NumLo = 0;
6664   for (unsigned i = 0; i != 4; ++i) {
6665     int Idx = PermMask[i];
6666     if (Idx < 0) {
6667       Locs[i] = std::make_pair(-1, -1);
6668     } else {
6669       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6670       if (Idx < 4) {
6671         Locs[i] = std::make_pair(0, NumLo);
6672         Mask1[NumLo] = Idx;
6673         NumLo++;
6674       } else {
6675         Locs[i] = std::make_pair(1, NumHi);
6676         if (2+NumHi < 4)
6677           Mask1[2+NumHi] = Idx;
6678         NumHi++;
6679       }
6680     }
6681   }
6682
6683   if (NumLo <= 2 && NumHi <= 2) {
6684     // If no more than two elements come from either vector. This can be
6685     // implemented with two shuffles. First shuffle gather the elements.
6686     // The second shuffle, which takes the first shuffle as both of its
6687     // vector operands, put the elements into the right order.
6688     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6689
6690     int Mask2[] = { -1, -1, -1, -1 };
6691
6692     for (unsigned i = 0; i != 4; ++i)
6693       if (Locs[i].first != -1) {
6694         unsigned Idx = (i < 2) ? 0 : 4;
6695         Idx += Locs[i].first * 2 + Locs[i].second;
6696         Mask2[i] = Idx;
6697       }
6698
6699     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6700   }
6701
6702   if (NumLo == 3 || NumHi == 3) {
6703     // Otherwise, we must have three elements from one vector, call it X, and
6704     // one element from the other, call it Y.  First, use a shufps to build an
6705     // intermediate vector with the one element from Y and the element from X
6706     // that will be in the same half in the final destination (the indexes don't
6707     // matter). Then, use a shufps to build the final vector, taking the half
6708     // containing the element from Y from the intermediate, and the other half
6709     // from X.
6710     if (NumHi == 3) {
6711       // Normalize it so the 3 elements come from V1.
6712       CommuteVectorShuffleMask(PermMask, 4);
6713       std::swap(V1, V2);
6714     }
6715
6716     // Find the element from V2.
6717     unsigned HiIndex;
6718     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6719       int Val = PermMask[HiIndex];
6720       if (Val < 0)
6721         continue;
6722       if (Val >= 4)
6723         break;
6724     }
6725
6726     Mask1[0] = PermMask[HiIndex];
6727     Mask1[1] = -1;
6728     Mask1[2] = PermMask[HiIndex^1];
6729     Mask1[3] = -1;
6730     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6731
6732     if (HiIndex >= 2) {
6733       Mask1[0] = PermMask[0];
6734       Mask1[1] = PermMask[1];
6735       Mask1[2] = HiIndex & 1 ? 6 : 4;
6736       Mask1[3] = HiIndex & 1 ? 4 : 6;
6737       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6738     }
6739
6740     Mask1[0] = HiIndex & 1 ? 2 : 0;
6741     Mask1[1] = HiIndex & 1 ? 0 : 2;
6742     Mask1[2] = PermMask[2];
6743     Mask1[3] = PermMask[3];
6744     if (Mask1[2] >= 0)
6745       Mask1[2] += 4;
6746     if (Mask1[3] >= 0)
6747       Mask1[3] += 4;
6748     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6749   }
6750
6751   // Break it into (shuffle shuffle_hi, shuffle_lo).
6752   int LoMask[] = { -1, -1, -1, -1 };
6753   int HiMask[] = { -1, -1, -1, -1 };
6754
6755   int *MaskPtr = LoMask;
6756   unsigned MaskIdx = 0;
6757   unsigned LoIdx = 0;
6758   unsigned HiIdx = 2;
6759   for (unsigned i = 0; i != 4; ++i) {
6760     if (i == 2) {
6761       MaskPtr = HiMask;
6762       MaskIdx = 1;
6763       LoIdx = 0;
6764       HiIdx = 2;
6765     }
6766     int Idx = PermMask[i];
6767     if (Idx < 0) {
6768       Locs[i] = std::make_pair(-1, -1);
6769     } else if (Idx < 4) {
6770       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6771       MaskPtr[LoIdx] = Idx;
6772       LoIdx++;
6773     } else {
6774       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6775       MaskPtr[HiIdx] = Idx;
6776       HiIdx++;
6777     }
6778   }
6779
6780   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6781   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6782   int MaskOps[] = { -1, -1, -1, -1 };
6783   for (unsigned i = 0; i != 4; ++i)
6784     if (Locs[i].first != -1)
6785       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6786   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6787 }
6788
6789 static bool MayFoldVectorLoad(SDValue V) {
6790   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6791     V = V.getOperand(0);
6792
6793   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6794     V = V.getOperand(0);
6795   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6796       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6797     // BUILD_VECTOR (load), undef
6798     V = V.getOperand(0);
6799
6800   return MayFoldLoad(V);
6801 }
6802
6803 static
6804 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6805   EVT VT = Op.getValueType();
6806
6807   // Canonizalize to v2f64.
6808   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6809   return DAG.getNode(ISD::BITCAST, dl, VT,
6810                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6811                                           V1, DAG));
6812 }
6813
6814 static
6815 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6816                         bool HasSSE2) {
6817   SDValue V1 = Op.getOperand(0);
6818   SDValue V2 = Op.getOperand(1);
6819   EVT VT = Op.getValueType();
6820
6821   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6822
6823   if (HasSSE2 && VT == MVT::v2f64)
6824     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6825
6826   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6827   return DAG.getNode(ISD::BITCAST, dl, VT,
6828                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6829                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6830                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6831 }
6832
6833 static
6834 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6835   SDValue V1 = Op.getOperand(0);
6836   SDValue V2 = Op.getOperand(1);
6837   EVT VT = Op.getValueType();
6838
6839   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6840          "unsupported shuffle type");
6841
6842   if (V2.getOpcode() == ISD::UNDEF)
6843     V2 = V1;
6844
6845   // v4i32 or v4f32
6846   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6847 }
6848
6849 static
6850 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6851   SDValue V1 = Op.getOperand(0);
6852   SDValue V2 = Op.getOperand(1);
6853   EVT VT = Op.getValueType();
6854   unsigned NumElems = VT.getVectorNumElements();
6855
6856   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6857   // operand of these instructions is only memory, so check if there's a
6858   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6859   // same masks.
6860   bool CanFoldLoad = false;
6861
6862   // Trivial case, when V2 comes from a load.
6863   if (MayFoldVectorLoad(V2))
6864     CanFoldLoad = true;
6865
6866   // When V1 is a load, it can be folded later into a store in isel, example:
6867   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6868   //    turns into:
6869   //  (MOVLPSmr addr:$src1, VR128:$src2)
6870   // So, recognize this potential and also use MOVLPS or MOVLPD
6871   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6872     CanFoldLoad = true;
6873
6874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6875   if (CanFoldLoad) {
6876     if (HasSSE2 && NumElems == 2)
6877       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6878
6879     if (NumElems == 4)
6880       // If we don't care about the second element, proceed to use movss.
6881       if (SVOp->getMaskElt(1) != -1)
6882         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6883   }
6884
6885   // movl and movlp will both match v2i64, but v2i64 is never matched by
6886   // movl earlier because we make it strict to avoid messing with the movlp load
6887   // folding logic (see the code above getMOVLP call). Match it here then,
6888   // this is horrible, but will stay like this until we move all shuffle
6889   // matching to x86 specific nodes. Note that for the 1st condition all
6890   // types are matched with movsd.
6891   if (HasSSE2) {
6892     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6893     // as to remove this logic from here, as much as possible
6894     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6895       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6896     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6897   }
6898
6899   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6900
6901   // Invert the operand order and use SHUFPS to match it.
6902   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6903                               getShuffleSHUFImmediate(SVOp), DAG);
6904 }
6905
6906 // Reduce a vector shuffle to zext.
6907 SDValue
6908 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6909   // PMOVZX is only available from SSE41.
6910   if (!Subtarget->hasSSE41())
6911     return SDValue();
6912
6913   EVT VT = Op.getValueType();
6914
6915   // Only AVX2 support 256-bit vector integer extending.
6916   if (!Subtarget->hasInt256() && VT.is256BitVector())
6917     return SDValue();
6918
6919   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6920   SDLoc DL(Op);
6921   SDValue V1 = Op.getOperand(0);
6922   SDValue V2 = Op.getOperand(1);
6923   unsigned NumElems = VT.getVectorNumElements();
6924
6925   // Extending is an unary operation and the element type of the source vector
6926   // won't be equal to or larger than i64.
6927   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6928       VT.getVectorElementType() == MVT::i64)
6929     return SDValue();
6930
6931   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6932   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6933   while ((1U << Shift) < NumElems) {
6934     if (SVOp->getMaskElt(1U << Shift) == 1)
6935       break;
6936     Shift += 1;
6937     // The maximal ratio is 8, i.e. from i8 to i64.
6938     if (Shift > 3)
6939       return SDValue();
6940   }
6941
6942   // Check the shuffle mask.
6943   unsigned Mask = (1U << Shift) - 1;
6944   for (unsigned i = 0; i != NumElems; ++i) {
6945     int EltIdx = SVOp->getMaskElt(i);
6946     if ((i & Mask) != 0 && EltIdx != -1)
6947       return SDValue();
6948     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6949       return SDValue();
6950   }
6951
6952   LLVMContext *Context = DAG.getContext();
6953   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6954   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6955   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6956
6957   if (!isTypeLegal(NVT))
6958     return SDValue();
6959
6960   // Simplify the operand as it's prepared to be fed into shuffle.
6961   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6962   if (V1.getOpcode() == ISD::BITCAST &&
6963       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6964       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6965       V1.getOperand(0)
6966         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6967     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6968     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6969     ConstantSDNode *CIdx =
6970       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6971     // If it's foldable, i.e. normal load with single use, we will let code
6972     // selection to fold it. Otherwise, we will short the conversion sequence.
6973     if (CIdx && CIdx->getZExtValue() == 0 &&
6974         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6975       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6976         // The "ext_vec_elt" node is wider than the result node.
6977         // In this case we should extract subvector from V.
6978         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6979         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6980         EVT FullVT = V.getValueType();
6981         EVT SubVecVT = EVT::getVectorVT(*Context,
6982                                         FullVT.getVectorElementType(),
6983                                         FullVT.getVectorNumElements()/Ratio);
6984         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6985                         DAG.getIntPtrConstant(0));
6986       }
6987       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6988     }
6989   }
6990
6991   return DAG.getNode(ISD::BITCAST, DL, VT,
6992                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6993 }
6994
6995 SDValue
6996 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6997   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6998   MVT VT = Op.getValueType().getSimpleVT();
6999   SDLoc dl(Op);
7000   SDValue V1 = Op.getOperand(0);
7001   SDValue V2 = Op.getOperand(1);
7002
7003   if (isZeroShuffle(SVOp))
7004     return getZeroVector(VT, Subtarget, DAG, dl);
7005
7006   // Handle splat operations
7007   if (SVOp->isSplat()) {
7008     // Use vbroadcast whenever the splat comes from a foldable load
7009     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7010     if (Broadcast.getNode())
7011       return Broadcast;
7012   }
7013
7014   // Check integer expanding shuffles.
7015   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7016   if (NewOp.getNode())
7017     return NewOp;
7018
7019   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7020   // do it!
7021   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7022       VT == MVT::v16i16 || VT == MVT::v32i8) {
7023     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7024     if (NewOp.getNode())
7025       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7026   } else if ((VT == MVT::v4i32 ||
7027              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7028     // FIXME: Figure out a cleaner way to do this.
7029     // Try to make use of movq to zero out the top part.
7030     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7031       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7032       if (NewOp.getNode()) {
7033         MVT NewVT = NewOp.getValueType().getSimpleVT();
7034         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7035                                NewVT, true, false))
7036           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7037                               DAG, Subtarget, dl);
7038       }
7039     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7040       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7041       if (NewOp.getNode()) {
7042         MVT NewVT = NewOp.getValueType().getSimpleVT();
7043         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7044           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7045                               DAG, Subtarget, dl);
7046       }
7047     }
7048   }
7049   return SDValue();
7050 }
7051
7052 SDValue
7053 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7054   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7055   SDValue V1 = Op.getOperand(0);
7056   SDValue V2 = Op.getOperand(1);
7057   MVT VT = Op.getValueType().getSimpleVT();
7058   SDLoc dl(Op);
7059   unsigned NumElems = VT.getVectorNumElements();
7060   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7061   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7062   bool V1IsSplat = false;
7063   bool V2IsSplat = false;
7064   bool HasSSE2 = Subtarget->hasSSE2();
7065   bool HasFp256    = Subtarget->hasFp256();
7066   bool HasInt256   = Subtarget->hasInt256();
7067   MachineFunction &MF = DAG.getMachineFunction();
7068   bool OptForSize = MF.getFunction()->getAttributes().
7069     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7070
7071   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7072
7073   if (V1IsUndef && V2IsUndef)
7074     return DAG.getUNDEF(VT);
7075
7076   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7077
7078   // Vector shuffle lowering takes 3 steps:
7079   //
7080   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7081   //    narrowing and commutation of operands should be handled.
7082   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7083   //    shuffle nodes.
7084   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7085   //    so the shuffle can be broken into other shuffles and the legalizer can
7086   //    try the lowering again.
7087   //
7088   // The general idea is that no vector_shuffle operation should be left to
7089   // be matched during isel, all of them must be converted to a target specific
7090   // node here.
7091
7092   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7093   // narrowing and commutation of operands should be handled. The actual code
7094   // doesn't include all of those, work in progress...
7095   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7096   if (NewOp.getNode())
7097     return NewOp;
7098
7099   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7100
7101   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7102   // unpckh_undef). Only use pshufd if speed is more important than size.
7103   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7104     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7105   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7106     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7107
7108   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7109       V2IsUndef && MayFoldVectorLoad(V1))
7110     return getMOVDDup(Op, dl, V1, DAG);
7111
7112   if (isMOVHLPS_v_undef_Mask(M, VT))
7113     return getMOVHighToLow(Op, dl, DAG);
7114
7115   // Use to match splats
7116   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7117       (VT == MVT::v2f64 || VT == MVT::v2i64))
7118     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7119
7120   if (isPSHUFDMask(M, VT)) {
7121     // The actual implementation will match the mask in the if above and then
7122     // during isel it can match several different instructions, not only pshufd
7123     // as its name says, sad but true, emulate the behavior for now...
7124     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7125       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7126
7127     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7128
7129     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7130       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7131
7132     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7133       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7134                                   DAG);
7135
7136     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7137                                 TargetMask, DAG);
7138   }
7139
7140   if (isPALIGNRMask(M, VT, Subtarget))
7141     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7142                                 getShufflePALIGNRImmediate(SVOp),
7143                                 DAG);
7144
7145   // Check if this can be converted into a logical shift.
7146   bool isLeft = false;
7147   unsigned ShAmt = 0;
7148   SDValue ShVal;
7149   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7150   if (isShift && ShVal.hasOneUse()) {
7151     // If the shifted value has multiple uses, it may be cheaper to use
7152     // v_set0 + movlhps or movhlps, etc.
7153     MVT EltVT = VT.getVectorElementType();
7154     ShAmt *= EltVT.getSizeInBits();
7155     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7156   }
7157
7158   if (isMOVLMask(M, VT)) {
7159     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7160       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7161     if (!isMOVLPMask(M, VT)) {
7162       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7163         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7164
7165       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7166         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7167     }
7168   }
7169
7170   // FIXME: fold these into legal mask.
7171   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7172     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7173
7174   if (isMOVHLPSMask(M, VT))
7175     return getMOVHighToLow(Op, dl, DAG);
7176
7177   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7178     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7179
7180   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7181     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7182
7183   if (isMOVLPMask(M, VT))
7184     return getMOVLP(Op, dl, DAG, HasSSE2);
7185
7186   if (ShouldXformToMOVHLPS(M, VT) ||
7187       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7188     return CommuteVectorShuffle(SVOp, DAG);
7189
7190   if (isShift) {
7191     // No better options. Use a vshldq / vsrldq.
7192     MVT EltVT = VT.getVectorElementType();
7193     ShAmt *= EltVT.getSizeInBits();
7194     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7195   }
7196
7197   bool Commuted = false;
7198   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7199   // 1,1,1,1 -> v8i16 though.
7200   V1IsSplat = isSplatVector(V1.getNode());
7201   V2IsSplat = isSplatVector(V2.getNode());
7202
7203   // Canonicalize the splat or undef, if present, to be on the RHS.
7204   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7205     CommuteVectorShuffleMask(M, NumElems);
7206     std::swap(V1, V2);
7207     std::swap(V1IsSplat, V2IsSplat);
7208     Commuted = true;
7209   }
7210
7211   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7212     // Shuffling low element of v1 into undef, just return v1.
7213     if (V2IsUndef)
7214       return V1;
7215     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7216     // the instruction selector will not match, so get a canonical MOVL with
7217     // swapped operands to undo the commute.
7218     return getMOVL(DAG, dl, VT, V2, V1);
7219   }
7220
7221   if (isUNPCKLMask(M, VT, HasInt256))
7222     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7223
7224   if (isUNPCKHMask(M, VT, HasInt256))
7225     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7226
7227   if (V2IsSplat) {
7228     // Normalize mask so all entries that point to V2 points to its first
7229     // element then try to match unpck{h|l} again. If match, return a
7230     // new vector_shuffle with the corrected mask.p
7231     SmallVector<int, 8> NewMask(M.begin(), M.end());
7232     NormalizeMask(NewMask, NumElems);
7233     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7234       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7235     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7236       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7237   }
7238
7239   if (Commuted) {
7240     // Commute is back and try unpck* again.
7241     // FIXME: this seems wrong.
7242     CommuteVectorShuffleMask(M, NumElems);
7243     std::swap(V1, V2);
7244     std::swap(V1IsSplat, V2IsSplat);
7245     Commuted = false;
7246
7247     if (isUNPCKLMask(M, VT, HasInt256))
7248       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7249
7250     if (isUNPCKHMask(M, VT, HasInt256))
7251       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7252   }
7253
7254   // Normalize the node to match x86 shuffle ops if needed
7255   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7256     return CommuteVectorShuffle(SVOp, DAG);
7257
7258   // The checks below are all present in isShuffleMaskLegal, but they are
7259   // inlined here right now to enable us to directly emit target specific
7260   // nodes, and remove one by one until they don't return Op anymore.
7261
7262   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7263       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7264     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7265       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7266   }
7267
7268   if (isPSHUFHWMask(M, VT, HasInt256))
7269     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7270                                 getShufflePSHUFHWImmediate(SVOp),
7271                                 DAG);
7272
7273   if (isPSHUFLWMask(M, VT, HasInt256))
7274     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7275                                 getShufflePSHUFLWImmediate(SVOp),
7276                                 DAG);
7277
7278   if (isSHUFPMask(M, VT, HasFp256))
7279     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7280                                 getShuffleSHUFImmediate(SVOp), DAG);
7281
7282   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7283     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7284   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7285     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7286
7287   //===--------------------------------------------------------------------===//
7288   // Generate target specific nodes for 128 or 256-bit shuffles only
7289   // supported in the AVX instruction set.
7290   //
7291
7292   // Handle VMOVDDUPY permutations
7293   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7294     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7295
7296   // Handle VPERMILPS/D* permutations
7297   if (isVPERMILPMask(M, VT, HasFp256)) {
7298     if (HasInt256 && VT == MVT::v8i32)
7299       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7300                                   getShuffleSHUFImmediate(SVOp), DAG);
7301     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7302                                 getShuffleSHUFImmediate(SVOp), DAG);
7303   }
7304
7305   // Handle VPERM2F128/VPERM2I128 permutations
7306   if (isVPERM2X128Mask(M, VT, HasFp256))
7307     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7308                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7309
7310   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7311   if (BlendOp.getNode())
7312     return BlendOp;
7313
7314   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7315     SmallVector<SDValue, 8> permclMask;
7316     for (unsigned i = 0; i != 8; ++i) {
7317       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7318     }
7319     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7320                                &permclMask[0], 8);
7321     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7322     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7323                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7324   }
7325
7326   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7327     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7328                                 getShuffleCLImmediate(SVOp), DAG);
7329
7330   //===--------------------------------------------------------------------===//
7331   // Since no target specific shuffle was selected for this generic one,
7332   // lower it into other known shuffles. FIXME: this isn't true yet, but
7333   // this is the plan.
7334   //
7335
7336   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7337   if (VT == MVT::v8i16) {
7338     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7339     if (NewOp.getNode())
7340       return NewOp;
7341   }
7342
7343   if (VT == MVT::v16i8) {
7344     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7345     if (NewOp.getNode())
7346       return NewOp;
7347   }
7348
7349   if (VT == MVT::v32i8) {
7350     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7351     if (NewOp.getNode())
7352       return NewOp;
7353   }
7354
7355   // Handle all 128-bit wide vectors with 4 elements, and match them with
7356   // several different shuffle types.
7357   if (NumElems == 4 && VT.is128BitVector())
7358     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7359
7360   // Handle general 256-bit shuffles
7361   if (VT.is256BitVector())
7362     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7363
7364   return SDValue();
7365 }
7366
7367 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7368   MVT VT = Op.getValueType().getSimpleVT();
7369   SDLoc dl(Op);
7370
7371   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7372     return SDValue();
7373
7374   if (VT.getSizeInBits() == 8) {
7375     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7376                                   Op.getOperand(0), Op.getOperand(1));
7377     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7378                                   DAG.getValueType(VT));
7379     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7380   }
7381
7382   if (VT.getSizeInBits() == 16) {
7383     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7384     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7385     if (Idx == 0)
7386       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7387                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7388                                      DAG.getNode(ISD::BITCAST, dl,
7389                                                  MVT::v4i32,
7390                                                  Op.getOperand(0)),
7391                                      Op.getOperand(1)));
7392     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7393                                   Op.getOperand(0), Op.getOperand(1));
7394     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7395                                   DAG.getValueType(VT));
7396     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7397   }
7398
7399   if (VT == MVT::f32) {
7400     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7401     // the result back to FR32 register. It's only worth matching if the
7402     // result has a single use which is a store or a bitcast to i32.  And in
7403     // the case of a store, it's not worth it if the index is a constant 0,
7404     // because a MOVSSmr can be used instead, which is smaller and faster.
7405     if (!Op.hasOneUse())
7406       return SDValue();
7407     SDNode *User = *Op.getNode()->use_begin();
7408     if ((User->getOpcode() != ISD::STORE ||
7409          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7410           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7411         (User->getOpcode() != ISD::BITCAST ||
7412          User->getValueType(0) != MVT::i32))
7413       return SDValue();
7414     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7415                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7416                                               Op.getOperand(0)),
7417                                               Op.getOperand(1));
7418     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7419   }
7420
7421   if (VT == MVT::i32 || VT == MVT::i64) {
7422     // ExtractPS/pextrq works with constant index.
7423     if (isa<ConstantSDNode>(Op.getOperand(1)))
7424       return Op;
7425   }
7426   return SDValue();
7427 }
7428
7429 SDValue
7430 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7431                                            SelectionDAG &DAG) const {
7432   SDLoc dl(Op);
7433   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7434     return SDValue();
7435
7436   SDValue Vec = Op.getOperand(0);
7437   MVT VecVT = Vec.getValueType().getSimpleVT();
7438
7439   // If this is a 256-bit vector result, first extract the 128-bit vector and
7440   // then extract the element from the 128-bit vector.
7441   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7442     SDValue Idx = Op.getOperand(1);
7443     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7444
7445     // Get the 128-bit vector.
7446     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7447     EVT EltVT = VecVT.getVectorElementType();
7448
7449     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7450
7451     //if (IdxVal >= NumElems/2)
7452     //  IdxVal -= NumElems/2;
7453     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7454     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7455                        DAG.getConstant(IdxVal, MVT::i32));
7456   }
7457
7458   assert(VecVT.is128BitVector() && "Unexpected vector length");
7459
7460   if (Subtarget->hasSSE41()) {
7461     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7462     if (Res.getNode())
7463       return Res;
7464   }
7465
7466   MVT VT = Op.getValueType().getSimpleVT();
7467   // TODO: handle v16i8.
7468   if (VT.getSizeInBits() == 16) {
7469     SDValue Vec = Op.getOperand(0);
7470     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7471     if (Idx == 0)
7472       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7473                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7474                                      DAG.getNode(ISD::BITCAST, dl,
7475                                                  MVT::v4i32, Vec),
7476                                      Op.getOperand(1)));
7477     // Transform it so it match pextrw which produces a 32-bit result.
7478     MVT EltVT = MVT::i32;
7479     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7480                                   Op.getOperand(0), Op.getOperand(1));
7481     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7482                                   DAG.getValueType(VT));
7483     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7484   }
7485
7486   if (VT.getSizeInBits() == 32) {
7487     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7488     if (Idx == 0)
7489       return Op;
7490
7491     // SHUFPS the element to the lowest double word, then movss.
7492     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7493     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7494     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7495                                        DAG.getUNDEF(VVT), Mask);
7496     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7497                        DAG.getIntPtrConstant(0));
7498   }
7499
7500   if (VT.getSizeInBits() == 64) {
7501     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7502     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7503     //        to match extract_elt for f64.
7504     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7505     if (Idx == 0)
7506       return Op;
7507
7508     // UNPCKHPD the element to the lowest double word, then movsd.
7509     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7510     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7511     int Mask[2] = { 1, -1 };
7512     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7513     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7514                                        DAG.getUNDEF(VVT), Mask);
7515     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7516                        DAG.getIntPtrConstant(0));
7517   }
7518
7519   return SDValue();
7520 }
7521
7522 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7523   MVT VT = Op.getValueType().getSimpleVT();
7524   MVT EltVT = VT.getVectorElementType();
7525   SDLoc dl(Op);
7526
7527   SDValue N0 = Op.getOperand(0);
7528   SDValue N1 = Op.getOperand(1);
7529   SDValue N2 = Op.getOperand(2);
7530
7531   if (!VT.is128BitVector())
7532     return SDValue();
7533
7534   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7535       isa<ConstantSDNode>(N2)) {
7536     unsigned Opc;
7537     if (VT == MVT::v8i16)
7538       Opc = X86ISD::PINSRW;
7539     else if (VT == MVT::v16i8)
7540       Opc = X86ISD::PINSRB;
7541     else
7542       Opc = X86ISD::PINSRB;
7543
7544     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7545     // argument.
7546     if (N1.getValueType() != MVT::i32)
7547       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7548     if (N2.getValueType() != MVT::i32)
7549       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7550     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7551   }
7552
7553   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7554     // Bits [7:6] of the constant are the source select.  This will always be
7555     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7556     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7557     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7558     // Bits [5:4] of the constant are the destination select.  This is the
7559     //  value of the incoming immediate.
7560     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7561     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7562     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7563     // Create this as a scalar to vector..
7564     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7565     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7566   }
7567
7568   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7569     // PINSR* works with constant index.
7570     return Op;
7571   }
7572   return SDValue();
7573 }
7574
7575 SDValue
7576 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7577   MVT VT = Op.getValueType().getSimpleVT();
7578   MVT EltVT = VT.getVectorElementType();
7579
7580   SDLoc dl(Op);
7581   SDValue N0 = Op.getOperand(0);
7582   SDValue N1 = Op.getOperand(1);
7583   SDValue N2 = Op.getOperand(2);
7584
7585   // If this is a 256-bit vector result, first extract the 128-bit vector,
7586   // insert the element into the extracted half and then place it back.
7587   if (VT.is256BitVector() || VT.is512BitVector()) {
7588     if (!isa<ConstantSDNode>(N2))
7589       return SDValue();
7590
7591     // Get the desired 128-bit vector half.
7592     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7593     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7594
7595     // Insert the element into the desired half.
7596     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7597     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7598
7599     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7600                     DAG.getConstant(IdxIn128, MVT::i32));
7601
7602     // Insert the changed part back to the 256-bit vector
7603     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7604   }
7605
7606   if (Subtarget->hasSSE41())
7607     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7608
7609   if (EltVT == MVT::i8)
7610     return SDValue();
7611
7612   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7613     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7614     // as its second argument.
7615     if (N1.getValueType() != MVT::i32)
7616       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7617     if (N2.getValueType() != MVT::i32)
7618       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7619     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7620   }
7621   return SDValue();
7622 }
7623
7624 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7625   LLVMContext *Context = DAG.getContext();
7626   SDLoc dl(Op);
7627   MVT OpVT = Op.getValueType().getSimpleVT();
7628
7629   // If this is a 256-bit vector result, first insert into a 128-bit
7630   // vector and then insert into the 256-bit vector.
7631   if (!OpVT.is128BitVector()) {
7632     // Insert into a 128-bit vector.
7633     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7634     EVT VT128 = EVT::getVectorVT(*Context,
7635                                  OpVT.getVectorElementType(),
7636                                  OpVT.getVectorNumElements() / SizeFactor);
7637
7638     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7639
7640     // Insert the 128-bit vector.
7641     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7642   }
7643
7644   if (OpVT == MVT::v1i64 &&
7645       Op.getOperand(0).getValueType() == MVT::i64)
7646     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7647
7648   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7649   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7650   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7651                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7652 }
7653
7654 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7655 // a simple subregister reference or explicit instructions to grab
7656 // upper bits of a vector.
7657 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7658                                       SelectionDAG &DAG) {
7659   SDLoc dl(Op);
7660   SDValue In =  Op.getOperand(0);
7661   SDValue Idx = Op.getOperand(1);
7662   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7663   EVT ResVT   = Op.getValueType();
7664   EVT InVT    = In.getValueType();
7665
7666   if (Subtarget->hasFp256()) {
7667     if (ResVT.is128BitVector() &&
7668         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7669         isa<ConstantSDNode>(Idx)) {
7670       return Extract128BitVector(In, IdxVal, DAG, dl);
7671     }
7672     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7673         isa<ConstantSDNode>(Idx)) {
7674       return Extract256BitVector(In, IdxVal, DAG, dl);
7675     }
7676   }
7677   return SDValue();
7678 }
7679
7680 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7681 // simple superregister reference or explicit instructions to insert
7682 // the upper bits of a vector.
7683 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7684                                      SelectionDAG &DAG) {
7685   if (Subtarget->hasFp256()) {
7686     SDLoc dl(Op.getNode());
7687     SDValue Vec = Op.getNode()->getOperand(0);
7688     SDValue SubVec = Op.getNode()->getOperand(1);
7689     SDValue Idx = Op.getNode()->getOperand(2);
7690
7691     if ((Op.getNode()->getValueType(0).is256BitVector() ||
7692          Op.getNode()->getValueType(0).is512BitVector()) &&
7693         SubVec.getNode()->getValueType(0).is128BitVector() &&
7694         isa<ConstantSDNode>(Idx)) {
7695       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7696       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7697     }
7698
7699     if (Op.getNode()->getValueType(0).is512BitVector() &&
7700         SubVec.getNode()->getValueType(0).is256BitVector() &&
7701         isa<ConstantSDNode>(Idx)) {
7702       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7703       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7704     }
7705   }
7706   return SDValue();
7707 }
7708
7709 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7710 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7711 // one of the above mentioned nodes. It has to be wrapped because otherwise
7712 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7713 // be used to form addressing mode. These wrapped nodes will be selected
7714 // into MOV32ri.
7715 SDValue
7716 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7717   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7718
7719   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7720   // global base reg.
7721   unsigned char OpFlag = 0;
7722   unsigned WrapperKind = X86ISD::Wrapper;
7723   CodeModel::Model M = getTargetMachine().getCodeModel();
7724
7725   if (Subtarget->isPICStyleRIPRel() &&
7726       (M == CodeModel::Small || M == CodeModel::Kernel))
7727     WrapperKind = X86ISD::WrapperRIP;
7728   else if (Subtarget->isPICStyleGOT())
7729     OpFlag = X86II::MO_GOTOFF;
7730   else if (Subtarget->isPICStyleStubPIC())
7731     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7732
7733   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7734                                              CP->getAlignment(),
7735                                              CP->getOffset(), OpFlag);
7736   SDLoc DL(CP);
7737   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7738   // With PIC, the address is actually $g + Offset.
7739   if (OpFlag) {
7740     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7741                          DAG.getNode(X86ISD::GlobalBaseReg,
7742                                      SDLoc(), getPointerTy()),
7743                          Result);
7744   }
7745
7746   return Result;
7747 }
7748
7749 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7750   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7751
7752   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7753   // global base reg.
7754   unsigned char OpFlag = 0;
7755   unsigned WrapperKind = X86ISD::Wrapper;
7756   CodeModel::Model M = getTargetMachine().getCodeModel();
7757
7758   if (Subtarget->isPICStyleRIPRel() &&
7759       (M == CodeModel::Small || M == CodeModel::Kernel))
7760     WrapperKind = X86ISD::WrapperRIP;
7761   else if (Subtarget->isPICStyleGOT())
7762     OpFlag = X86II::MO_GOTOFF;
7763   else if (Subtarget->isPICStyleStubPIC())
7764     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7765
7766   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7767                                           OpFlag);
7768   SDLoc DL(JT);
7769   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7770
7771   // With PIC, the address is actually $g + Offset.
7772   if (OpFlag)
7773     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7774                          DAG.getNode(X86ISD::GlobalBaseReg,
7775                                      SDLoc(), getPointerTy()),
7776                          Result);
7777
7778   return Result;
7779 }
7780
7781 SDValue
7782 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7783   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7784
7785   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7786   // global base reg.
7787   unsigned char OpFlag = 0;
7788   unsigned WrapperKind = X86ISD::Wrapper;
7789   CodeModel::Model M = getTargetMachine().getCodeModel();
7790
7791   if (Subtarget->isPICStyleRIPRel() &&
7792       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7793     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7794       OpFlag = X86II::MO_GOTPCREL;
7795     WrapperKind = X86ISD::WrapperRIP;
7796   } else if (Subtarget->isPICStyleGOT()) {
7797     OpFlag = X86II::MO_GOT;
7798   } else if (Subtarget->isPICStyleStubPIC()) {
7799     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7800   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7801     OpFlag = X86II::MO_DARWIN_NONLAZY;
7802   }
7803
7804   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7805
7806   SDLoc DL(Op);
7807   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7808
7809   // With PIC, the address is actually $g + Offset.
7810   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7811       !Subtarget->is64Bit()) {
7812     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7813                          DAG.getNode(X86ISD::GlobalBaseReg,
7814                                      SDLoc(), getPointerTy()),
7815                          Result);
7816   }
7817
7818   // For symbols that require a load from a stub to get the address, emit the
7819   // load.
7820   if (isGlobalStubReference(OpFlag))
7821     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7822                          MachinePointerInfo::getGOT(), false, false, false, 0);
7823
7824   return Result;
7825 }
7826
7827 SDValue
7828 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7829   // Create the TargetBlockAddressAddress node.
7830   unsigned char OpFlags =
7831     Subtarget->ClassifyBlockAddressReference();
7832   CodeModel::Model M = getTargetMachine().getCodeModel();
7833   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7834   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7835   SDLoc dl(Op);
7836   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7837                                              OpFlags);
7838
7839   if (Subtarget->isPICStyleRIPRel() &&
7840       (M == CodeModel::Small || M == CodeModel::Kernel))
7841     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7842   else
7843     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7844
7845   // With PIC, the address is actually $g + Offset.
7846   if (isGlobalRelativeToPICBase(OpFlags)) {
7847     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7848                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7849                          Result);
7850   }
7851
7852   return Result;
7853 }
7854
7855 SDValue
7856 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7857                                       int64_t Offset, SelectionDAG &DAG) const {
7858   // Create the TargetGlobalAddress node, folding in the constant
7859   // offset if it is legal.
7860   unsigned char OpFlags =
7861     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7862   CodeModel::Model M = getTargetMachine().getCodeModel();
7863   SDValue Result;
7864   if (OpFlags == X86II::MO_NO_FLAG &&
7865       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7866     // A direct static reference to a global.
7867     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7868     Offset = 0;
7869   } else {
7870     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7871   }
7872
7873   if (Subtarget->isPICStyleRIPRel() &&
7874       (M == CodeModel::Small || M == CodeModel::Kernel))
7875     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7876   else
7877     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7878
7879   // With PIC, the address is actually $g + Offset.
7880   if (isGlobalRelativeToPICBase(OpFlags)) {
7881     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7882                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7883                          Result);
7884   }
7885
7886   // For globals that require a load from a stub to get the address, emit the
7887   // load.
7888   if (isGlobalStubReference(OpFlags))
7889     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7890                          MachinePointerInfo::getGOT(), false, false, false, 0);
7891
7892   // If there was a non-zero offset that we didn't fold, create an explicit
7893   // addition for it.
7894   if (Offset != 0)
7895     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7896                          DAG.getConstant(Offset, getPointerTy()));
7897
7898   return Result;
7899 }
7900
7901 SDValue
7902 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7903   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7904   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7905   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7906 }
7907
7908 static SDValue
7909 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7910            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7911            unsigned char OperandFlags, bool LocalDynamic = false) {
7912   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7913   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7914   SDLoc dl(GA);
7915   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7916                                            GA->getValueType(0),
7917                                            GA->getOffset(),
7918                                            OperandFlags);
7919
7920   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7921                                            : X86ISD::TLSADDR;
7922
7923   if (InFlag) {
7924     SDValue Ops[] = { Chain,  TGA, *InFlag };
7925     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7926   } else {
7927     SDValue Ops[]  = { Chain, TGA };
7928     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7929   }
7930
7931   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7932   MFI->setAdjustsStack(true);
7933
7934   SDValue Flag = Chain.getValue(1);
7935   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7936 }
7937
7938 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7939 static SDValue
7940 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7941                                 const EVT PtrVT) {
7942   SDValue InFlag;
7943   SDLoc dl(GA);  // ? function entry point might be better
7944   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7945                                    DAG.getNode(X86ISD::GlobalBaseReg,
7946                                                SDLoc(), PtrVT), InFlag);
7947   InFlag = Chain.getValue(1);
7948
7949   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7950 }
7951
7952 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7953 static SDValue
7954 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7955                                 const EVT PtrVT) {
7956   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7957                     X86::RAX, X86II::MO_TLSGD);
7958 }
7959
7960 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7961                                            SelectionDAG &DAG,
7962                                            const EVT PtrVT,
7963                                            bool is64Bit) {
7964   SDLoc dl(GA);
7965
7966   // Get the start address of the TLS block for this module.
7967   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7968       .getInfo<X86MachineFunctionInfo>();
7969   MFI->incNumLocalDynamicTLSAccesses();
7970
7971   SDValue Base;
7972   if (is64Bit) {
7973     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7974                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7975   } else {
7976     SDValue InFlag;
7977     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7978         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7979     InFlag = Chain.getValue(1);
7980     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7981                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7982   }
7983
7984   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7985   // of Base.
7986
7987   // Build x@dtpoff.
7988   unsigned char OperandFlags = X86II::MO_DTPOFF;
7989   unsigned WrapperKind = X86ISD::Wrapper;
7990   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7991                                            GA->getValueType(0),
7992                                            GA->getOffset(), OperandFlags);
7993   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7994
7995   // Add x@dtpoff with the base.
7996   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7997 }
7998
7999 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8000 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8001                                    const EVT PtrVT, TLSModel::Model model,
8002                                    bool is64Bit, bool isPIC) {
8003   SDLoc dl(GA);
8004
8005   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8006   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8007                                                          is64Bit ? 257 : 256));
8008
8009   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8010                                       DAG.getIntPtrConstant(0),
8011                                       MachinePointerInfo(Ptr),
8012                                       false, false, false, 0);
8013
8014   unsigned char OperandFlags = 0;
8015   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8016   // initialexec.
8017   unsigned WrapperKind = X86ISD::Wrapper;
8018   if (model == TLSModel::LocalExec) {
8019     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8020   } else if (model == TLSModel::InitialExec) {
8021     if (is64Bit) {
8022       OperandFlags = X86II::MO_GOTTPOFF;
8023       WrapperKind = X86ISD::WrapperRIP;
8024     } else {
8025       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8026     }
8027   } else {
8028     llvm_unreachable("Unexpected model");
8029   }
8030
8031   // emit "addl x@ntpoff,%eax" (local exec)
8032   // or "addl x@indntpoff,%eax" (initial exec)
8033   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8034   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8035                                            GA->getValueType(0),
8036                                            GA->getOffset(), OperandFlags);
8037   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8038
8039   if (model == TLSModel::InitialExec) {
8040     if (isPIC && !is64Bit) {
8041       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8042                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8043                            Offset);
8044     }
8045
8046     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8047                          MachinePointerInfo::getGOT(), false, false, false,
8048                          0);
8049   }
8050
8051   // The address of the thread local variable is the add of the thread
8052   // pointer with the offset of the variable.
8053   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8054 }
8055
8056 SDValue
8057 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8058
8059   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8060   const GlobalValue *GV = GA->getGlobal();
8061
8062   if (Subtarget->isTargetELF()) {
8063     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8064
8065     switch (model) {
8066       case TLSModel::GeneralDynamic:
8067         if (Subtarget->is64Bit())
8068           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8069         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8070       case TLSModel::LocalDynamic:
8071         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8072                                            Subtarget->is64Bit());
8073       case TLSModel::InitialExec:
8074       case TLSModel::LocalExec:
8075         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8076                                    Subtarget->is64Bit(),
8077                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8078     }
8079     llvm_unreachable("Unknown TLS model.");
8080   }
8081
8082   if (Subtarget->isTargetDarwin()) {
8083     // Darwin only has one model of TLS.  Lower to that.
8084     unsigned char OpFlag = 0;
8085     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8086                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8087
8088     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8089     // global base reg.
8090     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8091                   !Subtarget->is64Bit();
8092     if (PIC32)
8093       OpFlag = X86II::MO_TLVP_PIC_BASE;
8094     else
8095       OpFlag = X86II::MO_TLVP;
8096     SDLoc DL(Op);
8097     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8098                                                 GA->getValueType(0),
8099                                                 GA->getOffset(), OpFlag);
8100     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8101
8102     // With PIC32, the address is actually $g + Offset.
8103     if (PIC32)
8104       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8105                            DAG.getNode(X86ISD::GlobalBaseReg,
8106                                        SDLoc(), getPointerTy()),
8107                            Offset);
8108
8109     // Lowering the machine isd will make sure everything is in the right
8110     // location.
8111     SDValue Chain = DAG.getEntryNode();
8112     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8113     SDValue Args[] = { Chain, Offset };
8114     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8115
8116     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8117     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8118     MFI->setAdjustsStack(true);
8119
8120     // And our return value (tls address) is in the standard call return value
8121     // location.
8122     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8123     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8124                               Chain.getValue(1));
8125   }
8126
8127   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8128     // Just use the implicit TLS architecture
8129     // Need to generate someting similar to:
8130     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8131     //                                  ; from TEB
8132     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8133     //   mov     rcx, qword [rdx+rcx*8]
8134     //   mov     eax, .tls$:tlsvar
8135     //   [rax+rcx] contains the address
8136     // Windows 64bit: gs:0x58
8137     // Windows 32bit: fs:__tls_array
8138
8139     // If GV is an alias then use the aliasee for determining
8140     // thread-localness.
8141     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8142       GV = GA->resolveAliasedGlobal(false);
8143     SDLoc dl(GA);
8144     SDValue Chain = DAG.getEntryNode();
8145
8146     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8147     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8148     // use its literal value of 0x2C.
8149     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8150                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8151                                                              256)
8152                                         : Type::getInt32PtrTy(*DAG.getContext(),
8153                                                               257));
8154
8155     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8156       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8157         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8158
8159     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8160                                         MachinePointerInfo(Ptr),
8161                                         false, false, false, 0);
8162
8163     // Load the _tls_index variable
8164     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8165     if (Subtarget->is64Bit())
8166       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8167                            IDX, MachinePointerInfo(), MVT::i32,
8168                            false, false, 0);
8169     else
8170       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8171                         false, false, false, 0);
8172
8173     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8174                                     getPointerTy());
8175     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8176
8177     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8178     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8179                       false, false, false, 0);
8180
8181     // Get the offset of start of .tls section
8182     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8183                                              GA->getValueType(0),
8184                                              GA->getOffset(), X86II::MO_SECREL);
8185     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8186
8187     // The address of the thread local variable is the add of the thread
8188     // pointer with the offset of the variable.
8189     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8190   }
8191
8192   llvm_unreachable("TLS not implemented for this target.");
8193 }
8194
8195 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8196 /// and take a 2 x i32 value to shift plus a shift amount.
8197 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8198   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8199   EVT VT = Op.getValueType();
8200   unsigned VTBits = VT.getSizeInBits();
8201   SDLoc dl(Op);
8202   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8203   SDValue ShOpLo = Op.getOperand(0);
8204   SDValue ShOpHi = Op.getOperand(1);
8205   SDValue ShAmt  = Op.getOperand(2);
8206   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8207                                      DAG.getConstant(VTBits - 1, MVT::i8))
8208                        : DAG.getConstant(0, VT);
8209
8210   SDValue Tmp2, Tmp3;
8211   if (Op.getOpcode() == ISD::SHL_PARTS) {
8212     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8213     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8214   } else {
8215     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8216     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8217   }
8218
8219   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8220                                 DAG.getConstant(VTBits, MVT::i8));
8221   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8222                              AndNode, DAG.getConstant(0, MVT::i8));
8223
8224   SDValue Hi, Lo;
8225   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8226   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8227   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8228
8229   if (Op.getOpcode() == ISD::SHL_PARTS) {
8230     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8231     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8232   } else {
8233     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8234     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8235   }
8236
8237   SDValue Ops[2] = { Lo, Hi };
8238   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8239 }
8240
8241 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8242                                            SelectionDAG &DAG) const {
8243   EVT SrcVT = Op.getOperand(0).getValueType();
8244
8245   if (SrcVT.isVector())
8246     return SDValue();
8247
8248   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8249          "Unknown SINT_TO_FP to lower!");
8250
8251   // These are really Legal; return the operand so the caller accepts it as
8252   // Legal.
8253   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8254     return Op;
8255   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8256       Subtarget->is64Bit()) {
8257     return Op;
8258   }
8259
8260   SDLoc dl(Op);
8261   unsigned Size = SrcVT.getSizeInBits()/8;
8262   MachineFunction &MF = DAG.getMachineFunction();
8263   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8264   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8265   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8266                                StackSlot,
8267                                MachinePointerInfo::getFixedStack(SSFI),
8268                                false, false, 0);
8269   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8270 }
8271
8272 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8273                                      SDValue StackSlot,
8274                                      SelectionDAG &DAG) const {
8275   // Build the FILD
8276   SDLoc DL(Op);
8277   SDVTList Tys;
8278   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8279   if (useSSE)
8280     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8281   else
8282     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8283
8284   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8285
8286   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8287   MachineMemOperand *MMO;
8288   if (FI) {
8289     int SSFI = FI->getIndex();
8290     MMO =
8291       DAG.getMachineFunction()
8292       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8293                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8294   } else {
8295     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8296     StackSlot = StackSlot.getOperand(1);
8297   }
8298   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8299   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8300                                            X86ISD::FILD, DL,
8301                                            Tys, Ops, array_lengthof(Ops),
8302                                            SrcVT, MMO);
8303
8304   if (useSSE) {
8305     Chain = Result.getValue(1);
8306     SDValue InFlag = Result.getValue(2);
8307
8308     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8309     // shouldn't be necessary except that RFP cannot be live across
8310     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8311     MachineFunction &MF = DAG.getMachineFunction();
8312     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8313     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8314     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8315     Tys = DAG.getVTList(MVT::Other);
8316     SDValue Ops[] = {
8317       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8318     };
8319     MachineMemOperand *MMO =
8320       DAG.getMachineFunction()
8321       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8322                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8323
8324     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8325                                     Ops, array_lengthof(Ops),
8326                                     Op.getValueType(), MMO);
8327     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8328                          MachinePointerInfo::getFixedStack(SSFI),
8329                          false, false, false, 0);
8330   }
8331
8332   return Result;
8333 }
8334
8335 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8336 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8337                                                SelectionDAG &DAG) const {
8338   // This algorithm is not obvious. Here it is what we're trying to output:
8339   /*
8340      movq       %rax,  %xmm0
8341      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8342      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8343      #ifdef __SSE3__
8344        haddpd   %xmm0, %xmm0
8345      #else
8346        pshufd   $0x4e, %xmm0, %xmm1
8347        addpd    %xmm1, %xmm0
8348      #endif
8349   */
8350
8351   SDLoc dl(Op);
8352   LLVMContext *Context = DAG.getContext();
8353
8354   // Build some magic constants.
8355   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8356   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8357   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8358
8359   SmallVector<Constant*,2> CV1;
8360   CV1.push_back(
8361     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8362                                       APInt(64, 0x4330000000000000ULL))));
8363   CV1.push_back(
8364     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8365                                       APInt(64, 0x4530000000000000ULL))));
8366   Constant *C1 = ConstantVector::get(CV1);
8367   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8368
8369   // Load the 64-bit value into an XMM register.
8370   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8371                             Op.getOperand(0));
8372   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8373                               MachinePointerInfo::getConstantPool(),
8374                               false, false, false, 16);
8375   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8376                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8377                               CLod0);
8378
8379   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8380                               MachinePointerInfo::getConstantPool(),
8381                               false, false, false, 16);
8382   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8383   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8384   SDValue Result;
8385
8386   if (Subtarget->hasSSE3()) {
8387     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8388     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8389   } else {
8390     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8391     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8392                                            S2F, 0x4E, DAG);
8393     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8394                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8395                          Sub);
8396   }
8397
8398   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8399                      DAG.getIntPtrConstant(0));
8400 }
8401
8402 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8403 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8404                                                SelectionDAG &DAG) const {
8405   SDLoc dl(Op);
8406   // FP constant to bias correct the final result.
8407   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8408                                    MVT::f64);
8409
8410   // Load the 32-bit value into an XMM register.
8411   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8412                              Op.getOperand(0));
8413
8414   // Zero out the upper parts of the register.
8415   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8416
8417   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8418                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8419                      DAG.getIntPtrConstant(0));
8420
8421   // Or the load with the bias.
8422   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8423                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8424                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8425                                                    MVT::v2f64, Load)),
8426                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8427                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8428                                                    MVT::v2f64, Bias)));
8429   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8430                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8431                    DAG.getIntPtrConstant(0));
8432
8433   // Subtract the bias.
8434   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8435
8436   // Handle final rounding.
8437   EVT DestVT = Op.getValueType();
8438
8439   if (DestVT.bitsLT(MVT::f64))
8440     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8441                        DAG.getIntPtrConstant(0));
8442   if (DestVT.bitsGT(MVT::f64))
8443     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8444
8445   // Handle final rounding.
8446   return Sub;
8447 }
8448
8449 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8450                                                SelectionDAG &DAG) const {
8451   SDValue N0 = Op.getOperand(0);
8452   EVT SVT = N0.getValueType();
8453   SDLoc dl(Op);
8454
8455   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8456           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8457          "Custom UINT_TO_FP is not supported!");
8458
8459   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8460                              SVT.getVectorNumElements());
8461   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8462                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8463 }
8464
8465 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8466                                            SelectionDAG &DAG) const {
8467   SDValue N0 = Op.getOperand(0);
8468   SDLoc dl(Op);
8469
8470   if (Op.getValueType().isVector())
8471     return lowerUINT_TO_FP_vec(Op, DAG);
8472
8473   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8474   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8475   // the optimization here.
8476   if (DAG.SignBitIsZero(N0))
8477     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8478
8479   EVT SrcVT = N0.getValueType();
8480   EVT DstVT = Op.getValueType();
8481   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8482     return LowerUINT_TO_FP_i64(Op, DAG);
8483   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8484     return LowerUINT_TO_FP_i32(Op, DAG);
8485   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8486     return SDValue();
8487
8488   // Make a 64-bit buffer, and use it to build an FILD.
8489   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8490   if (SrcVT == MVT::i32) {
8491     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8492     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8493                                      getPointerTy(), StackSlot, WordOff);
8494     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8495                                   StackSlot, MachinePointerInfo(),
8496                                   false, false, 0);
8497     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8498                                   OffsetSlot, MachinePointerInfo(),
8499                                   false, false, 0);
8500     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8501     return Fild;
8502   }
8503
8504   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8505   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8506                                StackSlot, MachinePointerInfo(),
8507                                false, false, 0);
8508   // For i64 source, we need to add the appropriate power of 2 if the input
8509   // was negative.  This is the same as the optimization in
8510   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8511   // we must be careful to do the computation in x87 extended precision, not
8512   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8513   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8514   MachineMemOperand *MMO =
8515     DAG.getMachineFunction()
8516     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8517                           MachineMemOperand::MOLoad, 8, 8);
8518
8519   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8520   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8521   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8522                                          array_lengthof(Ops), MVT::i64, MMO);
8523
8524   APInt FF(32, 0x5F800000ULL);
8525
8526   // Check whether the sign bit is set.
8527   SDValue SignSet = DAG.getSetCC(dl,
8528                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8529                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8530                                  ISD::SETLT);
8531
8532   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8533   SDValue FudgePtr = DAG.getConstantPool(
8534                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8535                                          getPointerTy());
8536
8537   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8538   SDValue Zero = DAG.getIntPtrConstant(0);
8539   SDValue Four = DAG.getIntPtrConstant(4);
8540   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8541                                Zero, Four);
8542   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8543
8544   // Load the value out, extending it from f32 to f80.
8545   // FIXME: Avoid the extend by constructing the right constant pool?
8546   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8547                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8548                                  MVT::f32, false, false, 4);
8549   // Extend everything to 80 bits to force it to be done on x87.
8550   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8551   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8552 }
8553
8554 std::pair<SDValue,SDValue>
8555 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8556                                     bool IsSigned, bool IsReplace) const {
8557   SDLoc DL(Op);
8558
8559   EVT DstTy = Op.getValueType();
8560
8561   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8562     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8563     DstTy = MVT::i64;
8564   }
8565
8566   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8567          DstTy.getSimpleVT() >= MVT::i16 &&
8568          "Unknown FP_TO_INT to lower!");
8569
8570   // These are really Legal.
8571   if (DstTy == MVT::i32 &&
8572       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8573     return std::make_pair(SDValue(), SDValue());
8574   if (Subtarget->is64Bit() &&
8575       DstTy == MVT::i64 &&
8576       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8577     return std::make_pair(SDValue(), SDValue());
8578
8579   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8580   // stack slot, or into the FTOL runtime function.
8581   MachineFunction &MF = DAG.getMachineFunction();
8582   unsigned MemSize = DstTy.getSizeInBits()/8;
8583   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8584   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8585
8586   unsigned Opc;
8587   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8588     Opc = X86ISD::WIN_FTOL;
8589   else
8590     switch (DstTy.getSimpleVT().SimpleTy) {
8591     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8592     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8593     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8594     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8595     }
8596
8597   SDValue Chain = DAG.getEntryNode();
8598   SDValue Value = Op.getOperand(0);
8599   EVT TheVT = Op.getOperand(0).getValueType();
8600   // FIXME This causes a redundant load/store if the SSE-class value is already
8601   // in memory, such as if it is on the callstack.
8602   if (isScalarFPTypeInSSEReg(TheVT)) {
8603     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8604     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8605                          MachinePointerInfo::getFixedStack(SSFI),
8606                          false, false, 0);
8607     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8608     SDValue Ops[] = {
8609       Chain, StackSlot, DAG.getValueType(TheVT)
8610     };
8611
8612     MachineMemOperand *MMO =
8613       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8614                               MachineMemOperand::MOLoad, MemSize, MemSize);
8615     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8616                                     array_lengthof(Ops), DstTy, MMO);
8617     Chain = Value.getValue(1);
8618     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8619     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8620   }
8621
8622   MachineMemOperand *MMO =
8623     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8624                             MachineMemOperand::MOStore, MemSize, MemSize);
8625
8626   if (Opc != X86ISD::WIN_FTOL) {
8627     // Build the FP_TO_INT*_IN_MEM
8628     SDValue Ops[] = { Chain, Value, StackSlot };
8629     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8630                                            Ops, array_lengthof(Ops), DstTy,
8631                                            MMO);
8632     return std::make_pair(FIST, StackSlot);
8633   } else {
8634     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8635       DAG.getVTList(MVT::Other, MVT::Glue),
8636       Chain, Value);
8637     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8638       MVT::i32, ftol.getValue(1));
8639     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8640       MVT::i32, eax.getValue(2));
8641     SDValue Ops[] = { eax, edx };
8642     SDValue pair = IsReplace
8643       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8644       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8645     return std::make_pair(pair, SDValue());
8646   }
8647 }
8648
8649 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8650                               const X86Subtarget *Subtarget) {
8651   MVT VT = Op->getValueType(0).getSimpleVT();
8652   SDValue In = Op->getOperand(0);
8653   MVT InVT = In.getValueType().getSimpleVT();
8654   SDLoc dl(Op);
8655
8656   // Optimize vectors in AVX mode:
8657   //
8658   //   v8i16 -> v8i32
8659   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8660   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8661   //   Concat upper and lower parts.
8662   //
8663   //   v4i32 -> v4i64
8664   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8665   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8666   //   Concat upper and lower parts.
8667   //
8668
8669   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8670       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8671     return SDValue();
8672
8673   if (Subtarget->hasInt256())
8674     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8675
8676   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8677   SDValue Undef = DAG.getUNDEF(InVT);
8678   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8679   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8680   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8681
8682   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8683                              VT.getVectorNumElements()/2);
8684
8685   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8686   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8687
8688   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8689 }
8690
8691 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8692                                            SelectionDAG &DAG) const {
8693   if (Subtarget->hasFp256()) {
8694     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8695     if (Res.getNode())
8696       return Res;
8697   }
8698
8699   return SDValue();
8700 }
8701 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8702                                             SelectionDAG &DAG) const {
8703   SDLoc DL(Op);
8704   MVT VT = Op.getValueType().getSimpleVT();
8705   SDValue In = Op.getOperand(0);
8706   MVT SVT = In.getValueType().getSimpleVT();
8707
8708   if (Subtarget->hasFp256()) {
8709     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8710     if (Res.getNode())
8711       return Res;
8712   }
8713
8714   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8715       VT.getVectorNumElements() != SVT.getVectorNumElements())
8716     return SDValue();
8717
8718   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8719
8720   // AVX2 has better support of integer extending.
8721   if (Subtarget->hasInt256())
8722     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8723
8724   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8725   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8726   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8727                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8728                                                 DAG.getUNDEF(MVT::v8i16),
8729                                                 &Mask[0]));
8730
8731   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8732 }
8733
8734 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8735   SDLoc DL(Op);
8736   MVT VT = Op.getValueType().getSimpleVT();
8737   SDValue In = Op.getOperand(0);
8738   MVT SVT = In.getValueType().getSimpleVT();
8739
8740   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8741     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8742     if (Subtarget->hasInt256()) {
8743       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8744       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8745       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8746                                 ShufMask);
8747       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8748                          DAG.getIntPtrConstant(0));
8749     }
8750
8751     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8752     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8753                                DAG.getIntPtrConstant(0));
8754     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8755                                DAG.getIntPtrConstant(2));
8756
8757     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8758     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8759
8760     // The PSHUFD mask:
8761     static const int ShufMask1[] = {0, 2, 0, 0};
8762     SDValue Undef = DAG.getUNDEF(VT);
8763     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8764     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8765
8766     // The MOVLHPS mask:
8767     static const int ShufMask2[] = {0, 1, 4, 5};
8768     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8769   }
8770
8771   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8772     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8773     if (Subtarget->hasInt256()) {
8774       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8775
8776       SmallVector<SDValue,32> pshufbMask;
8777       for (unsigned i = 0; i < 2; ++i) {
8778         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8779         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8780         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8781         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8782         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8783         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8784         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8785         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8786         for (unsigned j = 0; j < 8; ++j)
8787           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8788       }
8789       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8790                                &pshufbMask[0], 32);
8791       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8792       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8793
8794       static const int ShufMask[] = {0,  2,  -1,  -1};
8795       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8796                                 &ShufMask[0]);
8797       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8798                        DAG.getIntPtrConstant(0));
8799       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8800     }
8801
8802     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8803                                DAG.getIntPtrConstant(0));
8804
8805     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8806                                DAG.getIntPtrConstant(4));
8807
8808     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8809     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8810
8811     // The PSHUFB mask:
8812     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8813                                    -1, -1, -1, -1, -1, -1, -1, -1};
8814
8815     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8816     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8817     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8818
8819     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8820     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8821
8822     // The MOVLHPS Mask:
8823     static const int ShufMask2[] = {0, 1, 4, 5};
8824     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8825     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8826   }
8827
8828   // Handle truncation of V256 to V128 using shuffles.
8829   if (!VT.is128BitVector() || !SVT.is256BitVector())
8830     return SDValue();
8831
8832   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8833          "Invalid op");
8834   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8835
8836   unsigned NumElems = VT.getVectorNumElements();
8837   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8838                              NumElems * 2);
8839
8840   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8841   // Prepare truncation shuffle mask
8842   for (unsigned i = 0; i != NumElems; ++i)
8843     MaskVec[i] = i * 2;
8844   SDValue V = DAG.getVectorShuffle(NVT, DL,
8845                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8846                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8847   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8848                      DAG.getIntPtrConstant(0));
8849 }
8850
8851 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8852                                            SelectionDAG &DAG) const {
8853   MVT VT = Op.getValueType().getSimpleVT();
8854   if (VT.isVector()) {
8855     if (VT == MVT::v8i16)
8856       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8857                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8858                                      MVT::v8i32, Op.getOperand(0)));
8859     return SDValue();
8860   }
8861
8862   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8863     /*IsSigned=*/ true, /*IsReplace=*/ false);
8864   SDValue FIST = Vals.first, StackSlot = Vals.second;
8865   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8866   if (FIST.getNode() == 0) return Op;
8867
8868   if (StackSlot.getNode())
8869     // Load the result.
8870     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8871                        FIST, StackSlot, MachinePointerInfo(),
8872                        false, false, false, 0);
8873
8874   // The node is the result.
8875   return FIST;
8876 }
8877
8878 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8879                                            SelectionDAG &DAG) const {
8880   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8881     /*IsSigned=*/ false, /*IsReplace=*/ false);
8882   SDValue FIST = Vals.first, StackSlot = Vals.second;
8883   assert(FIST.getNode() && "Unexpected failure");
8884
8885   if (StackSlot.getNode())
8886     // Load the result.
8887     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8888                        FIST, StackSlot, MachinePointerInfo(),
8889                        false, false, false, 0);
8890
8891   // The node is the result.
8892   return FIST;
8893 }
8894
8895 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8896   SDLoc DL(Op);
8897   MVT VT = Op.getValueType().getSimpleVT();
8898   SDValue In = Op.getOperand(0);
8899   MVT SVT = In.getValueType().getSimpleVT();
8900
8901   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8902
8903   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8904                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8905                                  In, DAG.getUNDEF(SVT)));
8906 }
8907
8908 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8909   LLVMContext *Context = DAG.getContext();
8910   SDLoc dl(Op);
8911   MVT VT = Op.getValueType().getSimpleVT();
8912   MVT EltVT = VT;
8913   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8914   if (VT.isVector()) {
8915     EltVT = VT.getVectorElementType();
8916     NumElts = VT.getVectorNumElements();
8917   }
8918   Constant *C;
8919   if (EltVT == MVT::f64)
8920     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8921                                           APInt(64, ~(1ULL << 63))));
8922   else
8923     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8924                                           APInt(32, ~(1U << 31))));
8925   C = ConstantVector::getSplat(NumElts, C);
8926   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8927   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8928   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8929                              MachinePointerInfo::getConstantPool(),
8930                              false, false, false, Alignment);
8931   if (VT.isVector()) {
8932     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8933     return DAG.getNode(ISD::BITCAST, dl, VT,
8934                        DAG.getNode(ISD::AND, dl, ANDVT,
8935                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8936                                                Op.getOperand(0)),
8937                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8938   }
8939   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8940 }
8941
8942 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8943   LLVMContext *Context = DAG.getContext();
8944   SDLoc dl(Op);
8945   MVT VT = Op.getValueType().getSimpleVT();
8946   MVT EltVT = VT;
8947   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8948   if (VT.isVector()) {
8949     EltVT = VT.getVectorElementType();
8950     NumElts = VT.getVectorNumElements();
8951   }
8952   Constant *C;
8953   if (EltVT == MVT::f64)
8954     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8955                                           APInt(64, 1ULL << 63)));
8956   else
8957     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8958                                           APInt(32, 1U << 31)));
8959   C = ConstantVector::getSplat(NumElts, C);
8960   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8961   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8962   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8963                              MachinePointerInfo::getConstantPool(),
8964                              false, false, false, Alignment);
8965   if (VT.isVector()) {
8966     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8967     return DAG.getNode(ISD::BITCAST, dl, VT,
8968                        DAG.getNode(ISD::XOR, dl, XORVT,
8969                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8970                                                Op.getOperand(0)),
8971                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8972   }
8973
8974   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8975 }
8976
8977 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8978   LLVMContext *Context = DAG.getContext();
8979   SDValue Op0 = Op.getOperand(0);
8980   SDValue Op1 = Op.getOperand(1);
8981   SDLoc dl(Op);
8982   MVT VT = Op.getValueType().getSimpleVT();
8983   MVT SrcVT = Op1.getValueType().getSimpleVT();
8984
8985   // If second operand is smaller, extend it first.
8986   if (SrcVT.bitsLT(VT)) {
8987     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8988     SrcVT = VT;
8989   }
8990   // And if it is bigger, shrink it first.
8991   if (SrcVT.bitsGT(VT)) {
8992     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8993     SrcVT = VT;
8994   }
8995
8996   // At this point the operands and the result should have the same
8997   // type, and that won't be f80 since that is not custom lowered.
8998
8999   // First get the sign bit of second operand.
9000   SmallVector<Constant*,4> CV;
9001   if (SrcVT == MVT::f64) {
9002     const fltSemantics &Sem = APFloat::IEEEdouble;
9003     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9004     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9005   } else {
9006     const fltSemantics &Sem = APFloat::IEEEsingle;
9007     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9008     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9009     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9010     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9011   }
9012   Constant *C = ConstantVector::get(CV);
9013   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9014   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9015                               MachinePointerInfo::getConstantPool(),
9016                               false, false, false, 16);
9017   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9018
9019   // Shift sign bit right or left if the two operands have different types.
9020   if (SrcVT.bitsGT(VT)) {
9021     // Op0 is MVT::f32, Op1 is MVT::f64.
9022     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9023     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9024                           DAG.getConstant(32, MVT::i32));
9025     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9026     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9027                           DAG.getIntPtrConstant(0));
9028   }
9029
9030   // Clear first operand sign bit.
9031   CV.clear();
9032   if (VT == MVT::f64) {
9033     const fltSemantics &Sem = APFloat::IEEEdouble;
9034     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9035                                                    APInt(64, ~(1ULL << 63)))));
9036     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9037   } else {
9038     const fltSemantics &Sem = APFloat::IEEEsingle;
9039     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9040                                                    APInt(32, ~(1U << 31)))));
9041     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9042     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9043     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9044   }
9045   C = ConstantVector::get(CV);
9046   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9047   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9048                               MachinePointerInfo::getConstantPool(),
9049                               false, false, false, 16);
9050   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9051
9052   // Or the value with the sign bit.
9053   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9054 }
9055
9056 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9057   SDValue N0 = Op.getOperand(0);
9058   SDLoc dl(Op);
9059   MVT VT = Op.getValueType().getSimpleVT();
9060
9061   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9062   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9063                                   DAG.getConstant(1, VT));
9064   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9065 }
9066
9067 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9068 //
9069 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9070                                                   SelectionDAG &DAG) const {
9071   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9072
9073   if (!Subtarget->hasSSE41())
9074     return SDValue();
9075
9076   if (!Op->hasOneUse())
9077     return SDValue();
9078
9079   SDNode *N = Op.getNode();
9080   SDLoc DL(N);
9081
9082   SmallVector<SDValue, 8> Opnds;
9083   DenseMap<SDValue, unsigned> VecInMap;
9084   EVT VT = MVT::Other;
9085
9086   // Recognize a special case where a vector is casted into wide integer to
9087   // test all 0s.
9088   Opnds.push_back(N->getOperand(0));
9089   Opnds.push_back(N->getOperand(1));
9090
9091   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9092     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9093     // BFS traverse all OR'd operands.
9094     if (I->getOpcode() == ISD::OR) {
9095       Opnds.push_back(I->getOperand(0));
9096       Opnds.push_back(I->getOperand(1));
9097       // Re-evaluate the number of nodes to be traversed.
9098       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9099       continue;
9100     }
9101
9102     // Quit if a non-EXTRACT_VECTOR_ELT
9103     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9104       return SDValue();
9105
9106     // Quit if without a constant index.
9107     SDValue Idx = I->getOperand(1);
9108     if (!isa<ConstantSDNode>(Idx))
9109       return SDValue();
9110
9111     SDValue ExtractedFromVec = I->getOperand(0);
9112     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9113     if (M == VecInMap.end()) {
9114       VT = ExtractedFromVec.getValueType();
9115       // Quit if not 128/256-bit vector.
9116       if (!VT.is128BitVector() && !VT.is256BitVector())
9117         return SDValue();
9118       // Quit if not the same type.
9119       if (VecInMap.begin() != VecInMap.end() &&
9120           VT != VecInMap.begin()->first.getValueType())
9121         return SDValue();
9122       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9123     }
9124     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9125   }
9126
9127   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9128          "Not extracted from 128-/256-bit vector.");
9129
9130   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9131   SmallVector<SDValue, 8> VecIns;
9132
9133   for (DenseMap<SDValue, unsigned>::const_iterator
9134         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9135     // Quit if not all elements are used.
9136     if (I->second != FullMask)
9137       return SDValue();
9138     VecIns.push_back(I->first);
9139   }
9140
9141   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9142
9143   // Cast all vectors into TestVT for PTEST.
9144   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9145     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9146
9147   // If more than one full vectors are evaluated, OR them first before PTEST.
9148   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9149     // Each iteration will OR 2 nodes and append the result until there is only
9150     // 1 node left, i.e. the final OR'd value of all vectors.
9151     SDValue LHS = VecIns[Slot];
9152     SDValue RHS = VecIns[Slot + 1];
9153     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9154   }
9155
9156   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9157                      VecIns.back(), VecIns.back());
9158 }
9159
9160 /// Emit nodes that will be selected as "test Op0,Op0", or something
9161 /// equivalent.
9162 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9163                                     SelectionDAG &DAG) const {
9164   SDLoc dl(Op);
9165
9166   // CF and OF aren't always set the way we want. Determine which
9167   // of these we need.
9168   bool NeedCF = false;
9169   bool NeedOF = false;
9170   switch (X86CC) {
9171   default: break;
9172   case X86::COND_A: case X86::COND_AE:
9173   case X86::COND_B: case X86::COND_BE:
9174     NeedCF = true;
9175     break;
9176   case X86::COND_G: case X86::COND_GE:
9177   case X86::COND_L: case X86::COND_LE:
9178   case X86::COND_O: case X86::COND_NO:
9179     NeedOF = true;
9180     break;
9181   }
9182
9183   // See if we can use the EFLAGS value from the operand instead of
9184   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9185   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9186   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9187     // Emit a CMP with 0, which is the TEST pattern.
9188     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9189                        DAG.getConstant(0, Op.getValueType()));
9190
9191   unsigned Opcode = 0;
9192   unsigned NumOperands = 0;
9193
9194   // Truncate operations may prevent the merge of the SETCC instruction
9195   // and the arithmetic intruction before it. Attempt to truncate the operands
9196   // of the arithmetic instruction and use a reduced bit-width instruction.
9197   bool NeedTruncation = false;
9198   SDValue ArithOp = Op;
9199   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9200     SDValue Arith = Op->getOperand(0);
9201     // Both the trunc and the arithmetic op need to have one user each.
9202     if (Arith->hasOneUse())
9203       switch (Arith.getOpcode()) {
9204         default: break;
9205         case ISD::ADD:
9206         case ISD::SUB:
9207         case ISD::AND:
9208         case ISD::OR:
9209         case ISD::XOR: {
9210           NeedTruncation = true;
9211           ArithOp = Arith;
9212         }
9213       }
9214   }
9215
9216   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9217   // which may be the result of a CAST.  We use the variable 'Op', which is the
9218   // non-casted variable when we check for possible users.
9219   switch (ArithOp.getOpcode()) {
9220   case ISD::ADD:
9221     // Due to an isel shortcoming, be conservative if this add is likely to be
9222     // selected as part of a load-modify-store instruction. When the root node
9223     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9224     // uses of other nodes in the match, such as the ADD in this case. This
9225     // leads to the ADD being left around and reselected, with the result being
9226     // two adds in the output.  Alas, even if none our users are stores, that
9227     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9228     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9229     // climbing the DAG back to the root, and it doesn't seem to be worth the
9230     // effort.
9231     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9232          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9233       if (UI->getOpcode() != ISD::CopyToReg &&
9234           UI->getOpcode() != ISD::SETCC &&
9235           UI->getOpcode() != ISD::STORE)
9236         goto default_case;
9237
9238     if (ConstantSDNode *C =
9239         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9240       // An add of one will be selected as an INC.
9241       if (C->getAPIntValue() == 1) {
9242         Opcode = X86ISD::INC;
9243         NumOperands = 1;
9244         break;
9245       }
9246
9247       // An add of negative one (subtract of one) will be selected as a DEC.
9248       if (C->getAPIntValue().isAllOnesValue()) {
9249         Opcode = X86ISD::DEC;
9250         NumOperands = 1;
9251         break;
9252       }
9253     }
9254
9255     // Otherwise use a regular EFLAGS-setting add.
9256     Opcode = X86ISD::ADD;
9257     NumOperands = 2;
9258     break;
9259   case ISD::AND: {
9260     // If the primary and result isn't used, don't bother using X86ISD::AND,
9261     // because a TEST instruction will be better.
9262     bool NonFlagUse = false;
9263     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9264            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9265       SDNode *User = *UI;
9266       unsigned UOpNo = UI.getOperandNo();
9267       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9268         // Look pass truncate.
9269         UOpNo = User->use_begin().getOperandNo();
9270         User = *User->use_begin();
9271       }
9272
9273       if (User->getOpcode() != ISD::BRCOND &&
9274           User->getOpcode() != ISD::SETCC &&
9275           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9276         NonFlagUse = true;
9277         break;
9278       }
9279     }
9280
9281     if (!NonFlagUse)
9282       break;
9283   }
9284     // FALL THROUGH
9285   case ISD::SUB:
9286   case ISD::OR:
9287   case ISD::XOR:
9288     // Due to the ISEL shortcoming noted above, be conservative if this op is
9289     // likely to be selected as part of a load-modify-store instruction.
9290     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9291            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9292       if (UI->getOpcode() == ISD::STORE)
9293         goto default_case;
9294
9295     // Otherwise use a regular EFLAGS-setting instruction.
9296     switch (ArithOp.getOpcode()) {
9297     default: llvm_unreachable("unexpected operator!");
9298     case ISD::SUB: Opcode = X86ISD::SUB; break;
9299     case ISD::XOR: Opcode = X86ISD::XOR; break;
9300     case ISD::AND: Opcode = X86ISD::AND; break;
9301     case ISD::OR: {
9302       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9303         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9304         if (EFLAGS.getNode())
9305           return EFLAGS;
9306       }
9307       Opcode = X86ISD::OR;
9308       break;
9309     }
9310     }
9311
9312     NumOperands = 2;
9313     break;
9314   case X86ISD::ADD:
9315   case X86ISD::SUB:
9316   case X86ISD::INC:
9317   case X86ISD::DEC:
9318   case X86ISD::OR:
9319   case X86ISD::XOR:
9320   case X86ISD::AND:
9321     return SDValue(Op.getNode(), 1);
9322   default:
9323   default_case:
9324     break;
9325   }
9326
9327   // If we found that truncation is beneficial, perform the truncation and
9328   // update 'Op'.
9329   if (NeedTruncation) {
9330     EVT VT = Op.getValueType();
9331     SDValue WideVal = Op->getOperand(0);
9332     EVT WideVT = WideVal.getValueType();
9333     unsigned ConvertedOp = 0;
9334     // Use a target machine opcode to prevent further DAGCombine
9335     // optimizations that may separate the arithmetic operations
9336     // from the setcc node.
9337     switch (WideVal.getOpcode()) {
9338       default: break;
9339       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9340       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9341       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9342       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9343       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9344     }
9345
9346     if (ConvertedOp) {
9347       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9348       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9349         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9350         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9351         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9352       }
9353     }
9354   }
9355
9356   if (Opcode == 0)
9357     // Emit a CMP with 0, which is the TEST pattern.
9358     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9359                        DAG.getConstant(0, Op.getValueType()));
9360
9361   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9362   SmallVector<SDValue, 4> Ops;
9363   for (unsigned i = 0; i != NumOperands; ++i)
9364     Ops.push_back(Op.getOperand(i));
9365
9366   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9367   DAG.ReplaceAllUsesWith(Op, New);
9368   return SDValue(New.getNode(), 1);
9369 }
9370
9371 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9372 /// equivalent.
9373 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9374                                    SelectionDAG &DAG) const {
9375   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9376     if (C->getAPIntValue() == 0)
9377       return EmitTest(Op0, X86CC, DAG);
9378
9379   SDLoc dl(Op0);
9380   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9381        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9382     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9383     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9384     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9385                               Op0, Op1);
9386     return SDValue(Sub.getNode(), 1);
9387   }
9388   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9389 }
9390
9391 /// Convert a comparison if required by the subtarget.
9392 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9393                                                  SelectionDAG &DAG) const {
9394   // If the subtarget does not support the FUCOMI instruction, floating-point
9395   // comparisons have to be converted.
9396   if (Subtarget->hasCMov() ||
9397       Cmp.getOpcode() != X86ISD::CMP ||
9398       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9399       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9400     return Cmp;
9401
9402   // The instruction selector will select an FUCOM instruction instead of
9403   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9404   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9405   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9406   SDLoc dl(Cmp);
9407   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9408   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9409   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9410                             DAG.getConstant(8, MVT::i8));
9411   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9412   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9413 }
9414
9415 static bool isAllOnes(SDValue V) {
9416   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9417   return C && C->isAllOnesValue();
9418 }
9419
9420 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9421 /// if it's possible.
9422 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9423                                      SDLoc dl, SelectionDAG &DAG) const {
9424   SDValue Op0 = And.getOperand(0);
9425   SDValue Op1 = And.getOperand(1);
9426   if (Op0.getOpcode() == ISD::TRUNCATE)
9427     Op0 = Op0.getOperand(0);
9428   if (Op1.getOpcode() == ISD::TRUNCATE)
9429     Op1 = Op1.getOperand(0);
9430
9431   SDValue LHS, RHS;
9432   if (Op1.getOpcode() == ISD::SHL)
9433     std::swap(Op0, Op1);
9434   if (Op0.getOpcode() == ISD::SHL) {
9435     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9436       if (And00C->getZExtValue() == 1) {
9437         // If we looked past a truncate, check that it's only truncating away
9438         // known zeros.
9439         unsigned BitWidth = Op0.getValueSizeInBits();
9440         unsigned AndBitWidth = And.getValueSizeInBits();
9441         if (BitWidth > AndBitWidth) {
9442           APInt Zeros, Ones;
9443           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9444           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9445             return SDValue();
9446         }
9447         LHS = Op1;
9448         RHS = Op0.getOperand(1);
9449       }
9450   } else if (Op1.getOpcode() == ISD::Constant) {
9451     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9452     uint64_t AndRHSVal = AndRHS->getZExtValue();
9453     SDValue AndLHS = Op0;
9454
9455     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9456       LHS = AndLHS.getOperand(0);
9457       RHS = AndLHS.getOperand(1);
9458     }
9459
9460     // Use BT if the immediate can't be encoded in a TEST instruction.
9461     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9462       LHS = AndLHS;
9463       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9464     }
9465   }
9466
9467   if (LHS.getNode()) {
9468     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9469     // instruction.  Since the shift amount is in-range-or-undefined, we know
9470     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9471     // the encoding for the i16 version is larger than the i32 version.
9472     // Also promote i16 to i32 for performance / code size reason.
9473     if (LHS.getValueType() == MVT::i8 ||
9474         LHS.getValueType() == MVT::i16)
9475       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9476
9477     // If the operand types disagree, extend the shift amount to match.  Since
9478     // BT ignores high bits (like shifts) we can use anyextend.
9479     if (LHS.getValueType() != RHS.getValueType())
9480       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9481
9482     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9483     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9484     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9485                        DAG.getConstant(Cond, MVT::i8), BT);
9486   }
9487
9488   return SDValue();
9489 }
9490
9491 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9492 // ones, and then concatenate the result back.
9493 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9494   MVT VT = Op.getValueType().getSimpleVT();
9495
9496   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9497          "Unsupported value type for operation");
9498
9499   unsigned NumElems = VT.getVectorNumElements();
9500   SDLoc dl(Op);
9501   SDValue CC = Op.getOperand(2);
9502
9503   // Extract the LHS vectors
9504   SDValue LHS = Op.getOperand(0);
9505   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9506   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9507
9508   // Extract the RHS vectors
9509   SDValue RHS = Op.getOperand(1);
9510   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9511   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9512
9513   // Issue the operation on the smaller types and concatenate the result back
9514   MVT EltVT = VT.getVectorElementType();
9515   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9516   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9517                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9518                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9519 }
9520
9521 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9522                            SelectionDAG &DAG) {
9523   SDValue Cond;
9524   SDValue Op0 = Op.getOperand(0);
9525   SDValue Op1 = Op.getOperand(1);
9526   SDValue CC = Op.getOperand(2);
9527   MVT VT = Op.getValueType().getSimpleVT();
9528   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9529   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9530   SDLoc dl(Op);
9531
9532   if (isFP) {
9533 #ifndef NDEBUG
9534     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9535     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9536 #endif
9537
9538     unsigned SSECC;
9539     bool Swap = false;
9540
9541     // SSE Condition code mapping:
9542     //  0 - EQ
9543     //  1 - LT
9544     //  2 - LE
9545     //  3 - UNORD
9546     //  4 - NEQ
9547     //  5 - NLT
9548     //  6 - NLE
9549     //  7 - ORD
9550     switch (SetCCOpcode) {
9551     default: llvm_unreachable("Unexpected SETCC condition");
9552     case ISD::SETOEQ:
9553     case ISD::SETEQ:  SSECC = 0; break;
9554     case ISD::SETOGT:
9555     case ISD::SETGT: Swap = true; // Fallthrough
9556     case ISD::SETLT:
9557     case ISD::SETOLT: SSECC = 1; break;
9558     case ISD::SETOGE:
9559     case ISD::SETGE: Swap = true; // Fallthrough
9560     case ISD::SETLE:
9561     case ISD::SETOLE: SSECC = 2; break;
9562     case ISD::SETUO:  SSECC = 3; break;
9563     case ISD::SETUNE:
9564     case ISD::SETNE:  SSECC = 4; break;
9565     case ISD::SETULE: Swap = true; // Fallthrough
9566     case ISD::SETUGE: SSECC = 5; break;
9567     case ISD::SETULT: Swap = true; // Fallthrough
9568     case ISD::SETUGT: SSECC = 6; break;
9569     case ISD::SETO:   SSECC = 7; break;
9570     case ISD::SETUEQ:
9571     case ISD::SETONE: SSECC = 8; break;
9572     }
9573     if (Swap)
9574       std::swap(Op0, Op1);
9575
9576     // In the two special cases we can't handle, emit two comparisons.
9577     if (SSECC == 8) {
9578       unsigned CC0, CC1;
9579       unsigned CombineOpc;
9580       if (SetCCOpcode == ISD::SETUEQ) {
9581         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9582       } else {
9583         assert(SetCCOpcode == ISD::SETONE);
9584         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9585       }
9586
9587       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9588                                  DAG.getConstant(CC0, MVT::i8));
9589       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9590                                  DAG.getConstant(CC1, MVT::i8));
9591       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9592     }
9593     // Handle all other FP comparisons here.
9594     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9595                        DAG.getConstant(SSECC, MVT::i8));
9596   }
9597
9598   // Break 256-bit integer vector compare into smaller ones.
9599   if (VT.is256BitVector() && !Subtarget->hasInt256())
9600     return Lower256IntVSETCC(Op, DAG);
9601
9602   // We are handling one of the integer comparisons here.  Since SSE only has
9603   // GT and EQ comparisons for integer, swapping operands and multiple
9604   // operations may be required for some comparisons.
9605   unsigned Opc;
9606   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9607   
9608   switch (SetCCOpcode) {
9609   default: llvm_unreachable("Unexpected SETCC condition");
9610   case ISD::SETNE:  Invert = true;
9611   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9612   case ISD::SETLT:  Swap = true;
9613   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9614   case ISD::SETGE:  Swap = true;
9615   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9616   case ISD::SETULT: Swap = true;
9617   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9618   case ISD::SETUGE: Swap = true;
9619   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9620   }
9621   
9622   // Special case: Use min/max operations for SETULE/SETUGE
9623   MVT VET = VT.getVectorElementType();
9624   bool hasMinMax =
9625        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9626     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9627   
9628   if (hasMinMax) {
9629     switch (SetCCOpcode) {
9630     default: break;
9631     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9632     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9633     }
9634     
9635     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9636   }
9637   
9638   if (Swap)
9639     std::swap(Op0, Op1);
9640
9641   // Check that the operation in question is available (most are plain SSE2,
9642   // but PCMPGTQ and PCMPEQQ have different requirements).
9643   if (VT == MVT::v2i64) {
9644     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9645       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9646
9647       // First cast everything to the right type.
9648       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9649       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9650
9651       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9652       // bits of the inputs before performing those operations. The lower
9653       // compare is always unsigned.
9654       SDValue SB;
9655       if (FlipSigns) {
9656         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9657       } else {
9658         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9659         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9660         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9661                          Sign, Zero, Sign, Zero);
9662       }
9663       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9664       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9665
9666       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9667       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9668       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9669
9670       // Create masks for only the low parts/high parts of the 64 bit integers.
9671       static const int MaskHi[] = { 1, 1, 3, 3 };
9672       static const int MaskLo[] = { 0, 0, 2, 2 };
9673       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9674       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9675       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9676
9677       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9678       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9679
9680       if (Invert)
9681         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9682
9683       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9684     }
9685
9686     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9687       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9688       // pcmpeqd + pshufd + pand.
9689       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9690
9691       // First cast everything to the right type.
9692       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9693       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9694
9695       // Do the compare.
9696       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9697
9698       // Make sure the lower and upper halves are both all-ones.
9699       static const int Mask[] = { 1, 0, 3, 2 };
9700       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9701       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9702
9703       if (Invert)
9704         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9705
9706       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9707     }
9708   }
9709
9710   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9711   // bits of the inputs before performing those operations.
9712   if (FlipSigns) {
9713     EVT EltVT = VT.getVectorElementType();
9714     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9715     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9716     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9717   }
9718
9719   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9720
9721   // If the logical-not of the result is required, perform that now.
9722   if (Invert)
9723     Result = DAG.getNOT(dl, Result, VT);
9724   
9725   if (MinMax)
9726     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9727
9728   return Result;
9729 }
9730
9731 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9732
9733   MVT VT = Op.getValueType().getSimpleVT();
9734
9735   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9736
9737   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9738   SDValue Op0 = Op.getOperand(0);
9739   SDValue Op1 = Op.getOperand(1);
9740   SDLoc dl(Op);
9741   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9742
9743   // Optimize to BT if possible.
9744   // Lower (X & (1 << N)) == 0 to BT(X, N).
9745   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9746   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9747   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9748       Op1.getOpcode() == ISD::Constant &&
9749       cast<ConstantSDNode>(Op1)->isNullValue() &&
9750       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9751     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9752     if (NewSetCC.getNode())
9753       return NewSetCC;
9754   }
9755
9756   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9757   // these.
9758   if (Op1.getOpcode() == ISD::Constant &&
9759       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9760        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9761       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9762
9763     // If the input is a setcc, then reuse the input setcc or use a new one with
9764     // the inverted condition.
9765     if (Op0.getOpcode() == X86ISD::SETCC) {
9766       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9767       bool Invert = (CC == ISD::SETNE) ^
9768         cast<ConstantSDNode>(Op1)->isNullValue();
9769       if (!Invert) return Op0;
9770
9771       CCode = X86::GetOppositeBranchCondition(CCode);
9772       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9773                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9774     }
9775   }
9776
9777   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9778   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9779   if (X86CC == X86::COND_INVALID)
9780     return SDValue();
9781
9782   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9783   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9784   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9785                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9786 }
9787
9788 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9789 static bool isX86LogicalCmp(SDValue Op) {
9790   unsigned Opc = Op.getNode()->getOpcode();
9791   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9792       Opc == X86ISD::SAHF)
9793     return true;
9794   if (Op.getResNo() == 1 &&
9795       (Opc == X86ISD::ADD ||
9796        Opc == X86ISD::SUB ||
9797        Opc == X86ISD::ADC ||
9798        Opc == X86ISD::SBB ||
9799        Opc == X86ISD::SMUL ||
9800        Opc == X86ISD::UMUL ||
9801        Opc == X86ISD::INC ||
9802        Opc == X86ISD::DEC ||
9803        Opc == X86ISD::OR ||
9804        Opc == X86ISD::XOR ||
9805        Opc == X86ISD::AND))
9806     return true;
9807
9808   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9809     return true;
9810
9811   return false;
9812 }
9813
9814 static bool isZero(SDValue V) {
9815   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9816   return C && C->isNullValue();
9817 }
9818
9819 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9820   if (V.getOpcode() != ISD::TRUNCATE)
9821     return false;
9822
9823   SDValue VOp0 = V.getOperand(0);
9824   unsigned InBits = VOp0.getValueSizeInBits();
9825   unsigned Bits = V.getValueSizeInBits();
9826   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9827 }
9828
9829 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9830   bool addTest = true;
9831   SDValue Cond  = Op.getOperand(0);
9832   SDValue Op1 = Op.getOperand(1);
9833   SDValue Op2 = Op.getOperand(2);
9834   SDLoc DL(Op);
9835   SDValue CC;
9836
9837   if (Cond.getOpcode() == ISD::SETCC) {
9838     SDValue NewCond = LowerSETCC(Cond, DAG);
9839     if (NewCond.getNode())
9840       Cond = NewCond;
9841   }
9842
9843   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9844   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9845   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9846   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9847   if (Cond.getOpcode() == X86ISD::SETCC &&
9848       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9849       isZero(Cond.getOperand(1).getOperand(1))) {
9850     SDValue Cmp = Cond.getOperand(1);
9851
9852     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9853
9854     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9855         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9856       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9857
9858       SDValue CmpOp0 = Cmp.getOperand(0);
9859       // Apply further optimizations for special cases
9860       // (select (x != 0), -1, 0) -> neg & sbb
9861       // (select (x == 0), 0, -1) -> neg & sbb
9862       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9863         if (YC->isNullValue() &&
9864             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9865           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9866           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9867                                     DAG.getConstant(0, CmpOp0.getValueType()),
9868                                     CmpOp0);
9869           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9870                                     DAG.getConstant(X86::COND_B, MVT::i8),
9871                                     SDValue(Neg.getNode(), 1));
9872           return Res;
9873         }
9874
9875       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9876                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9877       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9878
9879       SDValue Res =   // Res = 0 or -1.
9880         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9881                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9882
9883       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9884         Res = DAG.getNOT(DL, Res, Res.getValueType());
9885
9886       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9887       if (N2C == 0 || !N2C->isNullValue())
9888         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9889       return Res;
9890     }
9891   }
9892
9893   // Look past (and (setcc_carry (cmp ...)), 1).
9894   if (Cond.getOpcode() == ISD::AND &&
9895       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9896     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9897     if (C && C->getAPIntValue() == 1)
9898       Cond = Cond.getOperand(0);
9899   }
9900
9901   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9902   // setting operand in place of the X86ISD::SETCC.
9903   unsigned CondOpcode = Cond.getOpcode();
9904   if (CondOpcode == X86ISD::SETCC ||
9905       CondOpcode == X86ISD::SETCC_CARRY) {
9906     CC = Cond.getOperand(0);
9907
9908     SDValue Cmp = Cond.getOperand(1);
9909     unsigned Opc = Cmp.getOpcode();
9910     MVT VT = Op.getValueType().getSimpleVT();
9911
9912     bool IllegalFPCMov = false;
9913     if (VT.isFloatingPoint() && !VT.isVector() &&
9914         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9915       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9916
9917     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9918         Opc == X86ISD::BT) { // FIXME
9919       Cond = Cmp;
9920       addTest = false;
9921     }
9922   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9923              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9924              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9925               Cond.getOperand(0).getValueType() != MVT::i8)) {
9926     SDValue LHS = Cond.getOperand(0);
9927     SDValue RHS = Cond.getOperand(1);
9928     unsigned X86Opcode;
9929     unsigned X86Cond;
9930     SDVTList VTs;
9931     switch (CondOpcode) {
9932     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9933     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9934     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9935     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9936     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9937     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9938     default: llvm_unreachable("unexpected overflowing operator");
9939     }
9940     if (CondOpcode == ISD::UMULO)
9941       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9942                           MVT::i32);
9943     else
9944       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9945
9946     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9947
9948     if (CondOpcode == ISD::UMULO)
9949       Cond = X86Op.getValue(2);
9950     else
9951       Cond = X86Op.getValue(1);
9952
9953     CC = DAG.getConstant(X86Cond, MVT::i8);
9954     addTest = false;
9955   }
9956
9957   if (addTest) {
9958     // Look pass the truncate if the high bits are known zero.
9959     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9960         Cond = Cond.getOperand(0);
9961
9962     // We know the result of AND is compared against zero. Try to match
9963     // it to BT.
9964     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9965       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9966       if (NewSetCC.getNode()) {
9967         CC = NewSetCC.getOperand(0);
9968         Cond = NewSetCC.getOperand(1);
9969         addTest = false;
9970       }
9971     }
9972   }
9973
9974   if (addTest) {
9975     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9976     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9977   }
9978
9979   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9980   // a <  b ?  0 : -1 -> RES = setcc_carry
9981   // a >= b ? -1 :  0 -> RES = setcc_carry
9982   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9983   if (Cond.getOpcode() == X86ISD::SUB) {
9984     Cond = ConvertCmpIfNecessary(Cond, DAG);
9985     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9986
9987     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9988         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9989       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9990                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9991       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9992         return DAG.getNOT(DL, Res, Res.getValueType());
9993       return Res;
9994     }
9995   }
9996
9997   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9998   // widen the cmov and push the truncate through. This avoids introducing a new
9999   // branch during isel and doesn't add any extensions.
10000   if (Op.getValueType() == MVT::i8 &&
10001       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10002     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10003     if (T1.getValueType() == T2.getValueType() &&
10004         // Blacklist CopyFromReg to avoid partial register stalls.
10005         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10006       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10007       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10008       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10009     }
10010   }
10011
10012   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10013   // condition is true.
10014   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10015   SDValue Ops[] = { Op2, Op1, CC, Cond };
10016   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10017 }
10018
10019 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10020                                             SelectionDAG &DAG) const {
10021   MVT VT = Op->getValueType(0).getSimpleVT();
10022   SDValue In = Op->getOperand(0);
10023   MVT InVT = In.getValueType().getSimpleVT();
10024   SDLoc dl(Op);
10025
10026   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10027       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10028     return SDValue();
10029
10030   if (Subtarget->hasInt256())
10031     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10032
10033   // Optimize vectors in AVX mode
10034   // Sign extend  v8i16 to v8i32 and
10035   //              v4i32 to v4i64
10036   //
10037   // Divide input vector into two parts
10038   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10039   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10040   // concat the vectors to original VT
10041
10042   unsigned NumElems = InVT.getVectorNumElements();
10043   SDValue Undef = DAG.getUNDEF(InVT);
10044
10045   SmallVector<int,8> ShufMask1(NumElems, -1);
10046   for (unsigned i = 0; i != NumElems/2; ++i)
10047     ShufMask1[i] = i;
10048
10049   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10050
10051   SmallVector<int,8> ShufMask2(NumElems, -1);
10052   for (unsigned i = 0; i != NumElems/2; ++i)
10053     ShufMask2[i] = i + NumElems/2;
10054
10055   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10056
10057   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10058                                 VT.getVectorNumElements()/2);
10059
10060   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10061   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10062
10063   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10064 }
10065
10066 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10067 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10068 // from the AND / OR.
10069 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10070   Opc = Op.getOpcode();
10071   if (Opc != ISD::OR && Opc != ISD::AND)
10072     return false;
10073   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10074           Op.getOperand(0).hasOneUse() &&
10075           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10076           Op.getOperand(1).hasOneUse());
10077 }
10078
10079 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10080 // 1 and that the SETCC node has a single use.
10081 static bool isXor1OfSetCC(SDValue Op) {
10082   if (Op.getOpcode() != ISD::XOR)
10083     return false;
10084   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10085   if (N1C && N1C->getAPIntValue() == 1) {
10086     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10087       Op.getOperand(0).hasOneUse();
10088   }
10089   return false;
10090 }
10091
10092 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10093   bool addTest = true;
10094   SDValue Chain = Op.getOperand(0);
10095   SDValue Cond  = Op.getOperand(1);
10096   SDValue Dest  = Op.getOperand(2);
10097   SDLoc dl(Op);
10098   SDValue CC;
10099   bool Inverted = false;
10100
10101   if (Cond.getOpcode() == ISD::SETCC) {
10102     // Check for setcc([su]{add,sub,mul}o == 0).
10103     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10104         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10105         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10106         Cond.getOperand(0).getResNo() == 1 &&
10107         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10108          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10109          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10110          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10111          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10112          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10113       Inverted = true;
10114       Cond = Cond.getOperand(0);
10115     } else {
10116       SDValue NewCond = LowerSETCC(Cond, DAG);
10117       if (NewCond.getNode())
10118         Cond = NewCond;
10119     }
10120   }
10121 #if 0
10122   // FIXME: LowerXALUO doesn't handle these!!
10123   else if (Cond.getOpcode() == X86ISD::ADD  ||
10124            Cond.getOpcode() == X86ISD::SUB  ||
10125            Cond.getOpcode() == X86ISD::SMUL ||
10126            Cond.getOpcode() == X86ISD::UMUL)
10127     Cond = LowerXALUO(Cond, DAG);
10128 #endif
10129
10130   // Look pass (and (setcc_carry (cmp ...)), 1).
10131   if (Cond.getOpcode() == ISD::AND &&
10132       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10133     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10134     if (C && C->getAPIntValue() == 1)
10135       Cond = Cond.getOperand(0);
10136   }
10137
10138   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10139   // setting operand in place of the X86ISD::SETCC.
10140   unsigned CondOpcode = Cond.getOpcode();
10141   if (CondOpcode == X86ISD::SETCC ||
10142       CondOpcode == X86ISD::SETCC_CARRY) {
10143     CC = Cond.getOperand(0);
10144
10145     SDValue Cmp = Cond.getOperand(1);
10146     unsigned Opc = Cmp.getOpcode();
10147     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10148     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10149       Cond = Cmp;
10150       addTest = false;
10151     } else {
10152       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10153       default: break;
10154       case X86::COND_O:
10155       case X86::COND_B:
10156         // These can only come from an arithmetic instruction with overflow,
10157         // e.g. SADDO, UADDO.
10158         Cond = Cond.getNode()->getOperand(1);
10159         addTest = false;
10160         break;
10161       }
10162     }
10163   }
10164   CondOpcode = Cond.getOpcode();
10165   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10166       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10167       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10168        Cond.getOperand(0).getValueType() != MVT::i8)) {
10169     SDValue LHS = Cond.getOperand(0);
10170     SDValue RHS = Cond.getOperand(1);
10171     unsigned X86Opcode;
10172     unsigned X86Cond;
10173     SDVTList VTs;
10174     switch (CondOpcode) {
10175     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10176     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10177     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10178     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10179     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10180     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10181     default: llvm_unreachable("unexpected overflowing operator");
10182     }
10183     if (Inverted)
10184       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10185     if (CondOpcode == ISD::UMULO)
10186       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10187                           MVT::i32);
10188     else
10189       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10190
10191     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10192
10193     if (CondOpcode == ISD::UMULO)
10194       Cond = X86Op.getValue(2);
10195     else
10196       Cond = X86Op.getValue(1);
10197
10198     CC = DAG.getConstant(X86Cond, MVT::i8);
10199     addTest = false;
10200   } else {
10201     unsigned CondOpc;
10202     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10203       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10204       if (CondOpc == ISD::OR) {
10205         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10206         // two branches instead of an explicit OR instruction with a
10207         // separate test.
10208         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10209             isX86LogicalCmp(Cmp)) {
10210           CC = Cond.getOperand(0).getOperand(0);
10211           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10212                               Chain, Dest, CC, Cmp);
10213           CC = Cond.getOperand(1).getOperand(0);
10214           Cond = Cmp;
10215           addTest = false;
10216         }
10217       } else { // ISD::AND
10218         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10219         // two branches instead of an explicit AND instruction with a
10220         // separate test. However, we only do this if this block doesn't
10221         // have a fall-through edge, because this requires an explicit
10222         // jmp when the condition is false.
10223         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10224             isX86LogicalCmp(Cmp) &&
10225             Op.getNode()->hasOneUse()) {
10226           X86::CondCode CCode =
10227             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10228           CCode = X86::GetOppositeBranchCondition(CCode);
10229           CC = DAG.getConstant(CCode, MVT::i8);
10230           SDNode *User = *Op.getNode()->use_begin();
10231           // Look for an unconditional branch following this conditional branch.
10232           // We need this because we need to reverse the successors in order
10233           // to implement FCMP_OEQ.
10234           if (User->getOpcode() == ISD::BR) {
10235             SDValue FalseBB = User->getOperand(1);
10236             SDNode *NewBR =
10237               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10238             assert(NewBR == User);
10239             (void)NewBR;
10240             Dest = FalseBB;
10241
10242             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10243                                 Chain, Dest, CC, Cmp);
10244             X86::CondCode CCode =
10245               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10246             CCode = X86::GetOppositeBranchCondition(CCode);
10247             CC = DAG.getConstant(CCode, MVT::i8);
10248             Cond = Cmp;
10249             addTest = false;
10250           }
10251         }
10252       }
10253     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10254       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10255       // It should be transformed during dag combiner except when the condition
10256       // is set by a arithmetics with overflow node.
10257       X86::CondCode CCode =
10258         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10259       CCode = X86::GetOppositeBranchCondition(CCode);
10260       CC = DAG.getConstant(CCode, MVT::i8);
10261       Cond = Cond.getOperand(0).getOperand(1);
10262       addTest = false;
10263     } else if (Cond.getOpcode() == ISD::SETCC &&
10264                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10265       // For FCMP_OEQ, we can emit
10266       // two branches instead of an explicit AND instruction with a
10267       // separate test. However, we only do this if this block doesn't
10268       // have a fall-through edge, because this requires an explicit
10269       // jmp when the condition is false.
10270       if (Op.getNode()->hasOneUse()) {
10271         SDNode *User = *Op.getNode()->use_begin();
10272         // Look for an unconditional branch following this conditional branch.
10273         // We need this because we need to reverse the successors in order
10274         // to implement FCMP_OEQ.
10275         if (User->getOpcode() == ISD::BR) {
10276           SDValue FalseBB = User->getOperand(1);
10277           SDNode *NewBR =
10278             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10279           assert(NewBR == User);
10280           (void)NewBR;
10281           Dest = FalseBB;
10282
10283           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10284                                     Cond.getOperand(0), Cond.getOperand(1));
10285           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10286           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10287           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10288                               Chain, Dest, CC, Cmp);
10289           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10290           Cond = Cmp;
10291           addTest = false;
10292         }
10293       }
10294     } else if (Cond.getOpcode() == ISD::SETCC &&
10295                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10296       // For FCMP_UNE, we can emit
10297       // two branches instead of an explicit AND instruction with a
10298       // separate test. However, we only do this if this block doesn't
10299       // have a fall-through edge, because this requires an explicit
10300       // jmp when the condition is false.
10301       if (Op.getNode()->hasOneUse()) {
10302         SDNode *User = *Op.getNode()->use_begin();
10303         // Look for an unconditional branch following this conditional branch.
10304         // We need this because we need to reverse the successors in order
10305         // to implement FCMP_UNE.
10306         if (User->getOpcode() == ISD::BR) {
10307           SDValue FalseBB = User->getOperand(1);
10308           SDNode *NewBR =
10309             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10310           assert(NewBR == User);
10311           (void)NewBR;
10312
10313           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10314                                     Cond.getOperand(0), Cond.getOperand(1));
10315           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10316           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10317           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10318                               Chain, Dest, CC, Cmp);
10319           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10320           Cond = Cmp;
10321           addTest = false;
10322           Dest = FalseBB;
10323         }
10324       }
10325     }
10326   }
10327
10328   if (addTest) {
10329     // Look pass the truncate if the high bits are known zero.
10330     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10331         Cond = Cond.getOperand(0);
10332
10333     // We know the result of AND is compared against zero. Try to match
10334     // it to BT.
10335     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10336       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10337       if (NewSetCC.getNode()) {
10338         CC = NewSetCC.getOperand(0);
10339         Cond = NewSetCC.getOperand(1);
10340         addTest = false;
10341       }
10342     }
10343   }
10344
10345   if (addTest) {
10346     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10347     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10348   }
10349   Cond = ConvertCmpIfNecessary(Cond, DAG);
10350   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10351                      Chain, Dest, CC, Cond);
10352 }
10353
10354 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10355 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10356 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10357 // that the guard pages used by the OS virtual memory manager are allocated in
10358 // correct sequence.
10359 SDValue
10360 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10361                                            SelectionDAG &DAG) const {
10362   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10363           getTargetMachine().Options.EnableSegmentedStacks) &&
10364          "This should be used only on Windows targets or when segmented stacks "
10365          "are being used");
10366   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10367   SDLoc dl(Op);
10368
10369   // Get the inputs.
10370   SDValue Chain = Op.getOperand(0);
10371   SDValue Size  = Op.getOperand(1);
10372   // FIXME: Ensure alignment here
10373
10374   bool Is64Bit = Subtarget->is64Bit();
10375   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10376
10377   if (getTargetMachine().Options.EnableSegmentedStacks) {
10378     MachineFunction &MF = DAG.getMachineFunction();
10379     MachineRegisterInfo &MRI = MF.getRegInfo();
10380
10381     if (Is64Bit) {
10382       // The 64 bit implementation of segmented stacks needs to clobber both r10
10383       // r11. This makes it impossible to use it along with nested parameters.
10384       const Function *F = MF.getFunction();
10385
10386       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10387            I != E; ++I)
10388         if (I->hasNestAttr())
10389           report_fatal_error("Cannot use segmented stacks with functions that "
10390                              "have nested arguments.");
10391     }
10392
10393     const TargetRegisterClass *AddrRegClass =
10394       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10395     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10396     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10397     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10398                                 DAG.getRegister(Vreg, SPTy));
10399     SDValue Ops1[2] = { Value, Chain };
10400     return DAG.getMergeValues(Ops1, 2, dl);
10401   } else {
10402     SDValue Flag;
10403     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10404
10405     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10406     Flag = Chain.getValue(1);
10407     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10408
10409     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10410     Flag = Chain.getValue(1);
10411
10412     const X86RegisterInfo *RegInfo =
10413       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10414     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10415                                SPTy).getValue(1);
10416
10417     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10418     return DAG.getMergeValues(Ops1, 2, dl);
10419   }
10420 }
10421
10422 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10423   MachineFunction &MF = DAG.getMachineFunction();
10424   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10425
10426   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10427   SDLoc DL(Op);
10428
10429   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10430     // vastart just stores the address of the VarArgsFrameIndex slot into the
10431     // memory location argument.
10432     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10433                                    getPointerTy());
10434     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10435                         MachinePointerInfo(SV), false, false, 0);
10436   }
10437
10438   // __va_list_tag:
10439   //   gp_offset         (0 - 6 * 8)
10440   //   fp_offset         (48 - 48 + 8 * 16)
10441   //   overflow_arg_area (point to parameters coming in memory).
10442   //   reg_save_area
10443   SmallVector<SDValue, 8> MemOps;
10444   SDValue FIN = Op.getOperand(1);
10445   // Store gp_offset
10446   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10447                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10448                                                MVT::i32),
10449                                FIN, MachinePointerInfo(SV), false, false, 0);
10450   MemOps.push_back(Store);
10451
10452   // Store fp_offset
10453   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10454                     FIN, DAG.getIntPtrConstant(4));
10455   Store = DAG.getStore(Op.getOperand(0), DL,
10456                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10457                                        MVT::i32),
10458                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10459   MemOps.push_back(Store);
10460
10461   // Store ptr to overflow_arg_area
10462   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10463                     FIN, DAG.getIntPtrConstant(4));
10464   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10465                                     getPointerTy());
10466   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10467                        MachinePointerInfo(SV, 8),
10468                        false, false, 0);
10469   MemOps.push_back(Store);
10470
10471   // Store ptr to reg_save_area.
10472   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10473                     FIN, DAG.getIntPtrConstant(8));
10474   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10475                                     getPointerTy());
10476   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10477                        MachinePointerInfo(SV, 16), false, false, 0);
10478   MemOps.push_back(Store);
10479   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10480                      &MemOps[0], MemOps.size());
10481 }
10482
10483 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10484   assert(Subtarget->is64Bit() &&
10485          "LowerVAARG only handles 64-bit va_arg!");
10486   assert((Subtarget->isTargetLinux() ||
10487           Subtarget->isTargetDarwin()) &&
10488           "Unhandled target in LowerVAARG");
10489   assert(Op.getNode()->getNumOperands() == 4);
10490   SDValue Chain = Op.getOperand(0);
10491   SDValue SrcPtr = Op.getOperand(1);
10492   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10493   unsigned Align = Op.getConstantOperandVal(3);
10494   SDLoc dl(Op);
10495
10496   EVT ArgVT = Op.getNode()->getValueType(0);
10497   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10498   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10499   uint8_t ArgMode;
10500
10501   // Decide which area this value should be read from.
10502   // TODO: Implement the AMD64 ABI in its entirety. This simple
10503   // selection mechanism works only for the basic types.
10504   if (ArgVT == MVT::f80) {
10505     llvm_unreachable("va_arg for f80 not yet implemented");
10506   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10507     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10508   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10509     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10510   } else {
10511     llvm_unreachable("Unhandled argument type in LowerVAARG");
10512   }
10513
10514   if (ArgMode == 2) {
10515     // Sanity Check: Make sure using fp_offset makes sense.
10516     assert(!getTargetMachine().Options.UseSoftFloat &&
10517            !(DAG.getMachineFunction()
10518                 .getFunction()->getAttributes()
10519                 .hasAttribute(AttributeSet::FunctionIndex,
10520                               Attribute::NoImplicitFloat)) &&
10521            Subtarget->hasSSE1());
10522   }
10523
10524   // Insert VAARG_64 node into the DAG
10525   // VAARG_64 returns two values: Variable Argument Address, Chain
10526   SmallVector<SDValue, 11> InstOps;
10527   InstOps.push_back(Chain);
10528   InstOps.push_back(SrcPtr);
10529   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10530   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10531   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10532   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10533   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10534                                           VTs, &InstOps[0], InstOps.size(),
10535                                           MVT::i64,
10536                                           MachinePointerInfo(SV),
10537                                           /*Align=*/0,
10538                                           /*Volatile=*/false,
10539                                           /*ReadMem=*/true,
10540                                           /*WriteMem=*/true);
10541   Chain = VAARG.getValue(1);
10542
10543   // Load the next argument and return it
10544   return DAG.getLoad(ArgVT, dl,
10545                      Chain,
10546                      VAARG,
10547                      MachinePointerInfo(),
10548                      false, false, false, 0);
10549 }
10550
10551 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10552                            SelectionDAG &DAG) {
10553   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10554   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10555   SDValue Chain = Op.getOperand(0);
10556   SDValue DstPtr = Op.getOperand(1);
10557   SDValue SrcPtr = Op.getOperand(2);
10558   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10559   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10560   SDLoc DL(Op);
10561
10562   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10563                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10564                        false,
10565                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10566 }
10567
10568 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10569 // may or may not be a constant. Takes immediate version of shift as input.
10570 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10571                                    SDValue SrcOp, SDValue ShAmt,
10572                                    SelectionDAG &DAG) {
10573   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10574
10575   if (isa<ConstantSDNode>(ShAmt)) {
10576     // Constant may be a TargetConstant. Use a regular constant.
10577     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10578     switch (Opc) {
10579       default: llvm_unreachable("Unknown target vector shift node");
10580       case X86ISD::VSHLI:
10581       case X86ISD::VSRLI:
10582       case X86ISD::VSRAI:
10583         return DAG.getNode(Opc, dl, VT, SrcOp,
10584                            DAG.getConstant(ShiftAmt, MVT::i32));
10585     }
10586   }
10587
10588   // Change opcode to non-immediate version
10589   switch (Opc) {
10590     default: llvm_unreachable("Unknown target vector shift node");
10591     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10592     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10593     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10594   }
10595
10596   // Need to build a vector containing shift amount
10597   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10598   SDValue ShOps[4];
10599   ShOps[0] = ShAmt;
10600   ShOps[1] = DAG.getConstant(0, MVT::i32);
10601   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10602   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10603
10604   // The return type has to be a 128-bit type with the same element
10605   // type as the input type.
10606   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10607   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10608
10609   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10610   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10611 }
10612
10613 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10614   SDLoc dl(Op);
10615   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10616   switch (IntNo) {
10617   default: return SDValue();    // Don't custom lower most intrinsics.
10618   // Comparison intrinsics.
10619   case Intrinsic::x86_sse_comieq_ss:
10620   case Intrinsic::x86_sse_comilt_ss:
10621   case Intrinsic::x86_sse_comile_ss:
10622   case Intrinsic::x86_sse_comigt_ss:
10623   case Intrinsic::x86_sse_comige_ss:
10624   case Intrinsic::x86_sse_comineq_ss:
10625   case Intrinsic::x86_sse_ucomieq_ss:
10626   case Intrinsic::x86_sse_ucomilt_ss:
10627   case Intrinsic::x86_sse_ucomile_ss:
10628   case Intrinsic::x86_sse_ucomigt_ss:
10629   case Intrinsic::x86_sse_ucomige_ss:
10630   case Intrinsic::x86_sse_ucomineq_ss:
10631   case Intrinsic::x86_sse2_comieq_sd:
10632   case Intrinsic::x86_sse2_comilt_sd:
10633   case Intrinsic::x86_sse2_comile_sd:
10634   case Intrinsic::x86_sse2_comigt_sd:
10635   case Intrinsic::x86_sse2_comige_sd:
10636   case Intrinsic::x86_sse2_comineq_sd:
10637   case Intrinsic::x86_sse2_ucomieq_sd:
10638   case Intrinsic::x86_sse2_ucomilt_sd:
10639   case Intrinsic::x86_sse2_ucomile_sd:
10640   case Intrinsic::x86_sse2_ucomigt_sd:
10641   case Intrinsic::x86_sse2_ucomige_sd:
10642   case Intrinsic::x86_sse2_ucomineq_sd: {
10643     unsigned Opc;
10644     ISD::CondCode CC;
10645     switch (IntNo) {
10646     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10647     case Intrinsic::x86_sse_comieq_ss:
10648     case Intrinsic::x86_sse2_comieq_sd:
10649       Opc = X86ISD::COMI;
10650       CC = ISD::SETEQ;
10651       break;
10652     case Intrinsic::x86_sse_comilt_ss:
10653     case Intrinsic::x86_sse2_comilt_sd:
10654       Opc = X86ISD::COMI;
10655       CC = ISD::SETLT;
10656       break;
10657     case Intrinsic::x86_sse_comile_ss:
10658     case Intrinsic::x86_sse2_comile_sd:
10659       Opc = X86ISD::COMI;
10660       CC = ISD::SETLE;
10661       break;
10662     case Intrinsic::x86_sse_comigt_ss:
10663     case Intrinsic::x86_sse2_comigt_sd:
10664       Opc = X86ISD::COMI;
10665       CC = ISD::SETGT;
10666       break;
10667     case Intrinsic::x86_sse_comige_ss:
10668     case Intrinsic::x86_sse2_comige_sd:
10669       Opc = X86ISD::COMI;
10670       CC = ISD::SETGE;
10671       break;
10672     case Intrinsic::x86_sse_comineq_ss:
10673     case Intrinsic::x86_sse2_comineq_sd:
10674       Opc = X86ISD::COMI;
10675       CC = ISD::SETNE;
10676       break;
10677     case Intrinsic::x86_sse_ucomieq_ss:
10678     case Intrinsic::x86_sse2_ucomieq_sd:
10679       Opc = X86ISD::UCOMI;
10680       CC = ISD::SETEQ;
10681       break;
10682     case Intrinsic::x86_sse_ucomilt_ss:
10683     case Intrinsic::x86_sse2_ucomilt_sd:
10684       Opc = X86ISD::UCOMI;
10685       CC = ISD::SETLT;
10686       break;
10687     case Intrinsic::x86_sse_ucomile_ss:
10688     case Intrinsic::x86_sse2_ucomile_sd:
10689       Opc = X86ISD::UCOMI;
10690       CC = ISD::SETLE;
10691       break;
10692     case Intrinsic::x86_sse_ucomigt_ss:
10693     case Intrinsic::x86_sse2_ucomigt_sd:
10694       Opc = X86ISD::UCOMI;
10695       CC = ISD::SETGT;
10696       break;
10697     case Intrinsic::x86_sse_ucomige_ss:
10698     case Intrinsic::x86_sse2_ucomige_sd:
10699       Opc = X86ISD::UCOMI;
10700       CC = ISD::SETGE;
10701       break;
10702     case Intrinsic::x86_sse_ucomineq_ss:
10703     case Intrinsic::x86_sse2_ucomineq_sd:
10704       Opc = X86ISD::UCOMI;
10705       CC = ISD::SETNE;
10706       break;
10707     }
10708
10709     SDValue LHS = Op.getOperand(1);
10710     SDValue RHS = Op.getOperand(2);
10711     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10712     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10713     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10714     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10715                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10716     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10717   }
10718
10719   // Arithmetic intrinsics.
10720   case Intrinsic::x86_sse2_pmulu_dq:
10721   case Intrinsic::x86_avx2_pmulu_dq:
10722     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10723                        Op.getOperand(1), Op.getOperand(2));
10724
10725   // SSE2/AVX2 sub with unsigned saturation intrinsics
10726   case Intrinsic::x86_sse2_psubus_b:
10727   case Intrinsic::x86_sse2_psubus_w:
10728   case Intrinsic::x86_avx2_psubus_b:
10729   case Intrinsic::x86_avx2_psubus_w:
10730     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10731                        Op.getOperand(1), Op.getOperand(2));
10732
10733   // SSE3/AVX horizontal add/sub intrinsics
10734   case Intrinsic::x86_sse3_hadd_ps:
10735   case Intrinsic::x86_sse3_hadd_pd:
10736   case Intrinsic::x86_avx_hadd_ps_256:
10737   case Intrinsic::x86_avx_hadd_pd_256:
10738   case Intrinsic::x86_sse3_hsub_ps:
10739   case Intrinsic::x86_sse3_hsub_pd:
10740   case Intrinsic::x86_avx_hsub_ps_256:
10741   case Intrinsic::x86_avx_hsub_pd_256:
10742   case Intrinsic::x86_ssse3_phadd_w_128:
10743   case Intrinsic::x86_ssse3_phadd_d_128:
10744   case Intrinsic::x86_avx2_phadd_w:
10745   case Intrinsic::x86_avx2_phadd_d:
10746   case Intrinsic::x86_ssse3_phsub_w_128:
10747   case Intrinsic::x86_ssse3_phsub_d_128:
10748   case Intrinsic::x86_avx2_phsub_w:
10749   case Intrinsic::x86_avx2_phsub_d: {
10750     unsigned Opcode;
10751     switch (IntNo) {
10752     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10753     case Intrinsic::x86_sse3_hadd_ps:
10754     case Intrinsic::x86_sse3_hadd_pd:
10755     case Intrinsic::x86_avx_hadd_ps_256:
10756     case Intrinsic::x86_avx_hadd_pd_256:
10757       Opcode = X86ISD::FHADD;
10758       break;
10759     case Intrinsic::x86_sse3_hsub_ps:
10760     case Intrinsic::x86_sse3_hsub_pd:
10761     case Intrinsic::x86_avx_hsub_ps_256:
10762     case Intrinsic::x86_avx_hsub_pd_256:
10763       Opcode = X86ISD::FHSUB;
10764       break;
10765     case Intrinsic::x86_ssse3_phadd_w_128:
10766     case Intrinsic::x86_ssse3_phadd_d_128:
10767     case Intrinsic::x86_avx2_phadd_w:
10768     case Intrinsic::x86_avx2_phadd_d:
10769       Opcode = X86ISD::HADD;
10770       break;
10771     case Intrinsic::x86_ssse3_phsub_w_128:
10772     case Intrinsic::x86_ssse3_phsub_d_128:
10773     case Intrinsic::x86_avx2_phsub_w:
10774     case Intrinsic::x86_avx2_phsub_d:
10775       Opcode = X86ISD::HSUB;
10776       break;
10777     }
10778     return DAG.getNode(Opcode, dl, Op.getValueType(),
10779                        Op.getOperand(1), Op.getOperand(2));
10780   }
10781
10782   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10783   case Intrinsic::x86_sse2_pmaxu_b:
10784   case Intrinsic::x86_sse41_pmaxuw:
10785   case Intrinsic::x86_sse41_pmaxud:
10786   case Intrinsic::x86_avx2_pmaxu_b:
10787   case Intrinsic::x86_avx2_pmaxu_w:
10788   case Intrinsic::x86_avx2_pmaxu_d:
10789   case Intrinsic::x86_sse2_pminu_b:
10790   case Intrinsic::x86_sse41_pminuw:
10791   case Intrinsic::x86_sse41_pminud:
10792   case Intrinsic::x86_avx2_pminu_b:
10793   case Intrinsic::x86_avx2_pminu_w:
10794   case Intrinsic::x86_avx2_pminu_d:
10795   case Intrinsic::x86_sse41_pmaxsb:
10796   case Intrinsic::x86_sse2_pmaxs_w:
10797   case Intrinsic::x86_sse41_pmaxsd:
10798   case Intrinsic::x86_avx2_pmaxs_b:
10799   case Intrinsic::x86_avx2_pmaxs_w:
10800   case Intrinsic::x86_avx2_pmaxs_d:
10801   case Intrinsic::x86_sse41_pminsb:
10802   case Intrinsic::x86_sse2_pmins_w:
10803   case Intrinsic::x86_sse41_pminsd:
10804   case Intrinsic::x86_avx2_pmins_b:
10805   case Intrinsic::x86_avx2_pmins_w:
10806   case Intrinsic::x86_avx2_pmins_d: {
10807     unsigned Opcode;
10808     switch (IntNo) {
10809     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10810     case Intrinsic::x86_sse2_pmaxu_b:
10811     case Intrinsic::x86_sse41_pmaxuw:
10812     case Intrinsic::x86_sse41_pmaxud:
10813     case Intrinsic::x86_avx2_pmaxu_b:
10814     case Intrinsic::x86_avx2_pmaxu_w:
10815     case Intrinsic::x86_avx2_pmaxu_d:
10816       Opcode = X86ISD::UMAX;
10817       break;
10818     case Intrinsic::x86_sse2_pminu_b:
10819     case Intrinsic::x86_sse41_pminuw:
10820     case Intrinsic::x86_sse41_pminud:
10821     case Intrinsic::x86_avx2_pminu_b:
10822     case Intrinsic::x86_avx2_pminu_w:
10823     case Intrinsic::x86_avx2_pminu_d:
10824       Opcode = X86ISD::UMIN;
10825       break;
10826     case Intrinsic::x86_sse41_pmaxsb:
10827     case Intrinsic::x86_sse2_pmaxs_w:
10828     case Intrinsic::x86_sse41_pmaxsd:
10829     case Intrinsic::x86_avx2_pmaxs_b:
10830     case Intrinsic::x86_avx2_pmaxs_w:
10831     case Intrinsic::x86_avx2_pmaxs_d:
10832       Opcode = X86ISD::SMAX;
10833       break;
10834     case Intrinsic::x86_sse41_pminsb:
10835     case Intrinsic::x86_sse2_pmins_w:
10836     case Intrinsic::x86_sse41_pminsd:
10837     case Intrinsic::x86_avx2_pmins_b:
10838     case Intrinsic::x86_avx2_pmins_w:
10839     case Intrinsic::x86_avx2_pmins_d:
10840       Opcode = X86ISD::SMIN;
10841       break;
10842     }
10843     return DAG.getNode(Opcode, dl, Op.getValueType(),
10844                        Op.getOperand(1), Op.getOperand(2));
10845   }
10846
10847   // SSE/SSE2/AVX floating point max/min intrinsics.
10848   case Intrinsic::x86_sse_max_ps:
10849   case Intrinsic::x86_sse2_max_pd:
10850   case Intrinsic::x86_avx_max_ps_256:
10851   case Intrinsic::x86_avx_max_pd_256:
10852   case Intrinsic::x86_sse_min_ps:
10853   case Intrinsic::x86_sse2_min_pd:
10854   case Intrinsic::x86_avx_min_ps_256:
10855   case Intrinsic::x86_avx_min_pd_256: {
10856     unsigned Opcode;
10857     switch (IntNo) {
10858     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10859     case Intrinsic::x86_sse_max_ps:
10860     case Intrinsic::x86_sse2_max_pd:
10861     case Intrinsic::x86_avx_max_ps_256:
10862     case Intrinsic::x86_avx_max_pd_256:
10863       Opcode = X86ISD::FMAX;
10864       break;
10865     case Intrinsic::x86_sse_min_ps:
10866     case Intrinsic::x86_sse2_min_pd:
10867     case Intrinsic::x86_avx_min_ps_256:
10868     case Intrinsic::x86_avx_min_pd_256:
10869       Opcode = X86ISD::FMIN;
10870       break;
10871     }
10872     return DAG.getNode(Opcode, dl, Op.getValueType(),
10873                        Op.getOperand(1), Op.getOperand(2));
10874   }
10875
10876   // AVX2 variable shift intrinsics
10877   case Intrinsic::x86_avx2_psllv_d:
10878   case Intrinsic::x86_avx2_psllv_q:
10879   case Intrinsic::x86_avx2_psllv_d_256:
10880   case Intrinsic::x86_avx2_psllv_q_256:
10881   case Intrinsic::x86_avx2_psrlv_d:
10882   case Intrinsic::x86_avx2_psrlv_q:
10883   case Intrinsic::x86_avx2_psrlv_d_256:
10884   case Intrinsic::x86_avx2_psrlv_q_256:
10885   case Intrinsic::x86_avx2_psrav_d:
10886   case Intrinsic::x86_avx2_psrav_d_256: {
10887     unsigned Opcode;
10888     switch (IntNo) {
10889     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10890     case Intrinsic::x86_avx2_psllv_d:
10891     case Intrinsic::x86_avx2_psllv_q:
10892     case Intrinsic::x86_avx2_psllv_d_256:
10893     case Intrinsic::x86_avx2_psllv_q_256:
10894       Opcode = ISD::SHL;
10895       break;
10896     case Intrinsic::x86_avx2_psrlv_d:
10897     case Intrinsic::x86_avx2_psrlv_q:
10898     case Intrinsic::x86_avx2_psrlv_d_256:
10899     case Intrinsic::x86_avx2_psrlv_q_256:
10900       Opcode = ISD::SRL;
10901       break;
10902     case Intrinsic::x86_avx2_psrav_d:
10903     case Intrinsic::x86_avx2_psrav_d_256:
10904       Opcode = ISD::SRA;
10905       break;
10906     }
10907     return DAG.getNode(Opcode, dl, Op.getValueType(),
10908                        Op.getOperand(1), Op.getOperand(2));
10909   }
10910
10911   case Intrinsic::x86_ssse3_pshuf_b_128:
10912   case Intrinsic::x86_avx2_pshuf_b:
10913     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10914                        Op.getOperand(1), Op.getOperand(2));
10915
10916   case Intrinsic::x86_ssse3_psign_b_128:
10917   case Intrinsic::x86_ssse3_psign_w_128:
10918   case Intrinsic::x86_ssse3_psign_d_128:
10919   case Intrinsic::x86_avx2_psign_b:
10920   case Intrinsic::x86_avx2_psign_w:
10921   case Intrinsic::x86_avx2_psign_d:
10922     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10923                        Op.getOperand(1), Op.getOperand(2));
10924
10925   case Intrinsic::x86_sse41_insertps:
10926     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10927                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10928
10929   case Intrinsic::x86_avx_vperm2f128_ps_256:
10930   case Intrinsic::x86_avx_vperm2f128_pd_256:
10931   case Intrinsic::x86_avx_vperm2f128_si_256:
10932   case Intrinsic::x86_avx2_vperm2i128:
10933     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10934                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10935
10936   case Intrinsic::x86_avx2_permd:
10937   case Intrinsic::x86_avx2_permps:
10938     // Operands intentionally swapped. Mask is last operand to intrinsic,
10939     // but second operand for node/intruction.
10940     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10941                        Op.getOperand(2), Op.getOperand(1));
10942
10943   case Intrinsic::x86_sse_sqrt_ps:
10944   case Intrinsic::x86_sse2_sqrt_pd:
10945   case Intrinsic::x86_avx_sqrt_ps_256:
10946   case Intrinsic::x86_avx_sqrt_pd_256:
10947     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10948
10949   // ptest and testp intrinsics. The intrinsic these come from are designed to
10950   // return an integer value, not just an instruction so lower it to the ptest
10951   // or testp pattern and a setcc for the result.
10952   case Intrinsic::x86_sse41_ptestz:
10953   case Intrinsic::x86_sse41_ptestc:
10954   case Intrinsic::x86_sse41_ptestnzc:
10955   case Intrinsic::x86_avx_ptestz_256:
10956   case Intrinsic::x86_avx_ptestc_256:
10957   case Intrinsic::x86_avx_ptestnzc_256:
10958   case Intrinsic::x86_avx_vtestz_ps:
10959   case Intrinsic::x86_avx_vtestc_ps:
10960   case Intrinsic::x86_avx_vtestnzc_ps:
10961   case Intrinsic::x86_avx_vtestz_pd:
10962   case Intrinsic::x86_avx_vtestc_pd:
10963   case Intrinsic::x86_avx_vtestnzc_pd:
10964   case Intrinsic::x86_avx_vtestz_ps_256:
10965   case Intrinsic::x86_avx_vtestc_ps_256:
10966   case Intrinsic::x86_avx_vtestnzc_ps_256:
10967   case Intrinsic::x86_avx_vtestz_pd_256:
10968   case Intrinsic::x86_avx_vtestc_pd_256:
10969   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10970     bool IsTestPacked = false;
10971     unsigned X86CC;
10972     switch (IntNo) {
10973     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10974     case Intrinsic::x86_avx_vtestz_ps:
10975     case Intrinsic::x86_avx_vtestz_pd:
10976     case Intrinsic::x86_avx_vtestz_ps_256:
10977     case Intrinsic::x86_avx_vtestz_pd_256:
10978       IsTestPacked = true; // Fallthrough
10979     case Intrinsic::x86_sse41_ptestz:
10980     case Intrinsic::x86_avx_ptestz_256:
10981       // ZF = 1
10982       X86CC = X86::COND_E;
10983       break;
10984     case Intrinsic::x86_avx_vtestc_ps:
10985     case Intrinsic::x86_avx_vtestc_pd:
10986     case Intrinsic::x86_avx_vtestc_ps_256:
10987     case Intrinsic::x86_avx_vtestc_pd_256:
10988       IsTestPacked = true; // Fallthrough
10989     case Intrinsic::x86_sse41_ptestc:
10990     case Intrinsic::x86_avx_ptestc_256:
10991       // CF = 1
10992       X86CC = X86::COND_B;
10993       break;
10994     case Intrinsic::x86_avx_vtestnzc_ps:
10995     case Intrinsic::x86_avx_vtestnzc_pd:
10996     case Intrinsic::x86_avx_vtestnzc_ps_256:
10997     case Intrinsic::x86_avx_vtestnzc_pd_256:
10998       IsTestPacked = true; // Fallthrough
10999     case Intrinsic::x86_sse41_ptestnzc:
11000     case Intrinsic::x86_avx_ptestnzc_256:
11001       // ZF and CF = 0
11002       X86CC = X86::COND_A;
11003       break;
11004     }
11005
11006     SDValue LHS = Op.getOperand(1);
11007     SDValue RHS = Op.getOperand(2);
11008     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11009     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11010     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11011     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11012     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11013   }
11014
11015   // SSE/AVX shift intrinsics
11016   case Intrinsic::x86_sse2_psll_w:
11017   case Intrinsic::x86_sse2_psll_d:
11018   case Intrinsic::x86_sse2_psll_q:
11019   case Intrinsic::x86_avx2_psll_w:
11020   case Intrinsic::x86_avx2_psll_d:
11021   case Intrinsic::x86_avx2_psll_q:
11022   case Intrinsic::x86_sse2_psrl_w:
11023   case Intrinsic::x86_sse2_psrl_d:
11024   case Intrinsic::x86_sse2_psrl_q:
11025   case Intrinsic::x86_avx2_psrl_w:
11026   case Intrinsic::x86_avx2_psrl_d:
11027   case Intrinsic::x86_avx2_psrl_q:
11028   case Intrinsic::x86_sse2_psra_w:
11029   case Intrinsic::x86_sse2_psra_d:
11030   case Intrinsic::x86_avx2_psra_w:
11031   case Intrinsic::x86_avx2_psra_d: {
11032     unsigned Opcode;
11033     switch (IntNo) {
11034     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11035     case Intrinsic::x86_sse2_psll_w:
11036     case Intrinsic::x86_sse2_psll_d:
11037     case Intrinsic::x86_sse2_psll_q:
11038     case Intrinsic::x86_avx2_psll_w:
11039     case Intrinsic::x86_avx2_psll_d:
11040     case Intrinsic::x86_avx2_psll_q:
11041       Opcode = X86ISD::VSHL;
11042       break;
11043     case Intrinsic::x86_sse2_psrl_w:
11044     case Intrinsic::x86_sse2_psrl_d:
11045     case Intrinsic::x86_sse2_psrl_q:
11046     case Intrinsic::x86_avx2_psrl_w:
11047     case Intrinsic::x86_avx2_psrl_d:
11048     case Intrinsic::x86_avx2_psrl_q:
11049       Opcode = X86ISD::VSRL;
11050       break;
11051     case Intrinsic::x86_sse2_psra_w:
11052     case Intrinsic::x86_sse2_psra_d:
11053     case Intrinsic::x86_avx2_psra_w:
11054     case Intrinsic::x86_avx2_psra_d:
11055       Opcode = X86ISD::VSRA;
11056       break;
11057     }
11058     return DAG.getNode(Opcode, dl, Op.getValueType(),
11059                        Op.getOperand(1), Op.getOperand(2));
11060   }
11061
11062   // SSE/AVX immediate shift intrinsics
11063   case Intrinsic::x86_sse2_pslli_w:
11064   case Intrinsic::x86_sse2_pslli_d:
11065   case Intrinsic::x86_sse2_pslli_q:
11066   case Intrinsic::x86_avx2_pslli_w:
11067   case Intrinsic::x86_avx2_pslli_d:
11068   case Intrinsic::x86_avx2_pslli_q:
11069   case Intrinsic::x86_sse2_psrli_w:
11070   case Intrinsic::x86_sse2_psrli_d:
11071   case Intrinsic::x86_sse2_psrli_q:
11072   case Intrinsic::x86_avx2_psrli_w:
11073   case Intrinsic::x86_avx2_psrli_d:
11074   case Intrinsic::x86_avx2_psrli_q:
11075   case Intrinsic::x86_sse2_psrai_w:
11076   case Intrinsic::x86_sse2_psrai_d:
11077   case Intrinsic::x86_avx2_psrai_w:
11078   case Intrinsic::x86_avx2_psrai_d: {
11079     unsigned Opcode;
11080     switch (IntNo) {
11081     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11082     case Intrinsic::x86_sse2_pslli_w:
11083     case Intrinsic::x86_sse2_pslli_d:
11084     case Intrinsic::x86_sse2_pslli_q:
11085     case Intrinsic::x86_avx2_pslli_w:
11086     case Intrinsic::x86_avx2_pslli_d:
11087     case Intrinsic::x86_avx2_pslli_q:
11088       Opcode = X86ISD::VSHLI;
11089       break;
11090     case Intrinsic::x86_sse2_psrli_w:
11091     case Intrinsic::x86_sse2_psrli_d:
11092     case Intrinsic::x86_sse2_psrli_q:
11093     case Intrinsic::x86_avx2_psrli_w:
11094     case Intrinsic::x86_avx2_psrli_d:
11095     case Intrinsic::x86_avx2_psrli_q:
11096       Opcode = X86ISD::VSRLI;
11097       break;
11098     case Intrinsic::x86_sse2_psrai_w:
11099     case Intrinsic::x86_sse2_psrai_d:
11100     case Intrinsic::x86_avx2_psrai_w:
11101     case Intrinsic::x86_avx2_psrai_d:
11102       Opcode = X86ISD::VSRAI;
11103       break;
11104     }
11105     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11106                                Op.getOperand(1), Op.getOperand(2), DAG);
11107   }
11108
11109   case Intrinsic::x86_sse42_pcmpistria128:
11110   case Intrinsic::x86_sse42_pcmpestria128:
11111   case Intrinsic::x86_sse42_pcmpistric128:
11112   case Intrinsic::x86_sse42_pcmpestric128:
11113   case Intrinsic::x86_sse42_pcmpistrio128:
11114   case Intrinsic::x86_sse42_pcmpestrio128:
11115   case Intrinsic::x86_sse42_pcmpistris128:
11116   case Intrinsic::x86_sse42_pcmpestris128:
11117   case Intrinsic::x86_sse42_pcmpistriz128:
11118   case Intrinsic::x86_sse42_pcmpestriz128: {
11119     unsigned Opcode;
11120     unsigned X86CC;
11121     switch (IntNo) {
11122     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11123     case Intrinsic::x86_sse42_pcmpistria128:
11124       Opcode = X86ISD::PCMPISTRI;
11125       X86CC = X86::COND_A;
11126       break;
11127     case Intrinsic::x86_sse42_pcmpestria128:
11128       Opcode = X86ISD::PCMPESTRI;
11129       X86CC = X86::COND_A;
11130       break;
11131     case Intrinsic::x86_sse42_pcmpistric128:
11132       Opcode = X86ISD::PCMPISTRI;
11133       X86CC = X86::COND_B;
11134       break;
11135     case Intrinsic::x86_sse42_pcmpestric128:
11136       Opcode = X86ISD::PCMPESTRI;
11137       X86CC = X86::COND_B;
11138       break;
11139     case Intrinsic::x86_sse42_pcmpistrio128:
11140       Opcode = X86ISD::PCMPISTRI;
11141       X86CC = X86::COND_O;
11142       break;
11143     case Intrinsic::x86_sse42_pcmpestrio128:
11144       Opcode = X86ISD::PCMPESTRI;
11145       X86CC = X86::COND_O;
11146       break;
11147     case Intrinsic::x86_sse42_pcmpistris128:
11148       Opcode = X86ISD::PCMPISTRI;
11149       X86CC = X86::COND_S;
11150       break;
11151     case Intrinsic::x86_sse42_pcmpestris128:
11152       Opcode = X86ISD::PCMPESTRI;
11153       X86CC = X86::COND_S;
11154       break;
11155     case Intrinsic::x86_sse42_pcmpistriz128:
11156       Opcode = X86ISD::PCMPISTRI;
11157       X86CC = X86::COND_E;
11158       break;
11159     case Intrinsic::x86_sse42_pcmpestriz128:
11160       Opcode = X86ISD::PCMPESTRI;
11161       X86CC = X86::COND_E;
11162       break;
11163     }
11164     SmallVector<SDValue, 5> NewOps;
11165     NewOps.append(Op->op_begin()+1, Op->op_end());
11166     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11167     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11168     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11169                                 DAG.getConstant(X86CC, MVT::i8),
11170                                 SDValue(PCMP.getNode(), 1));
11171     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11172   }
11173
11174   case Intrinsic::x86_sse42_pcmpistri128:
11175   case Intrinsic::x86_sse42_pcmpestri128: {
11176     unsigned Opcode;
11177     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11178       Opcode = X86ISD::PCMPISTRI;
11179     else
11180       Opcode = X86ISD::PCMPESTRI;
11181
11182     SmallVector<SDValue, 5> NewOps;
11183     NewOps.append(Op->op_begin()+1, Op->op_end());
11184     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11185     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11186   }
11187   case Intrinsic::x86_fma_vfmadd_ps:
11188   case Intrinsic::x86_fma_vfmadd_pd:
11189   case Intrinsic::x86_fma_vfmsub_ps:
11190   case Intrinsic::x86_fma_vfmsub_pd:
11191   case Intrinsic::x86_fma_vfnmadd_ps:
11192   case Intrinsic::x86_fma_vfnmadd_pd:
11193   case Intrinsic::x86_fma_vfnmsub_ps:
11194   case Intrinsic::x86_fma_vfnmsub_pd:
11195   case Intrinsic::x86_fma_vfmaddsub_ps:
11196   case Intrinsic::x86_fma_vfmaddsub_pd:
11197   case Intrinsic::x86_fma_vfmsubadd_ps:
11198   case Intrinsic::x86_fma_vfmsubadd_pd:
11199   case Intrinsic::x86_fma_vfmadd_ps_256:
11200   case Intrinsic::x86_fma_vfmadd_pd_256:
11201   case Intrinsic::x86_fma_vfmsub_ps_256:
11202   case Intrinsic::x86_fma_vfmsub_pd_256:
11203   case Intrinsic::x86_fma_vfnmadd_ps_256:
11204   case Intrinsic::x86_fma_vfnmadd_pd_256:
11205   case Intrinsic::x86_fma_vfnmsub_ps_256:
11206   case Intrinsic::x86_fma_vfnmsub_pd_256:
11207   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11208   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11209   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11210   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11211     unsigned Opc;
11212     switch (IntNo) {
11213     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11214     case Intrinsic::x86_fma_vfmadd_ps:
11215     case Intrinsic::x86_fma_vfmadd_pd:
11216     case Intrinsic::x86_fma_vfmadd_ps_256:
11217     case Intrinsic::x86_fma_vfmadd_pd_256:
11218       Opc = X86ISD::FMADD;
11219       break;
11220     case Intrinsic::x86_fma_vfmsub_ps:
11221     case Intrinsic::x86_fma_vfmsub_pd:
11222     case Intrinsic::x86_fma_vfmsub_ps_256:
11223     case Intrinsic::x86_fma_vfmsub_pd_256:
11224       Opc = X86ISD::FMSUB;
11225       break;
11226     case Intrinsic::x86_fma_vfnmadd_ps:
11227     case Intrinsic::x86_fma_vfnmadd_pd:
11228     case Intrinsic::x86_fma_vfnmadd_ps_256:
11229     case Intrinsic::x86_fma_vfnmadd_pd_256:
11230       Opc = X86ISD::FNMADD;
11231       break;
11232     case Intrinsic::x86_fma_vfnmsub_ps:
11233     case Intrinsic::x86_fma_vfnmsub_pd:
11234     case Intrinsic::x86_fma_vfnmsub_ps_256:
11235     case Intrinsic::x86_fma_vfnmsub_pd_256:
11236       Opc = X86ISD::FNMSUB;
11237       break;
11238     case Intrinsic::x86_fma_vfmaddsub_ps:
11239     case Intrinsic::x86_fma_vfmaddsub_pd:
11240     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11241     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11242       Opc = X86ISD::FMADDSUB;
11243       break;
11244     case Intrinsic::x86_fma_vfmsubadd_ps:
11245     case Intrinsic::x86_fma_vfmsubadd_pd:
11246     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11247     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11248       Opc = X86ISD::FMSUBADD;
11249       break;
11250     }
11251
11252     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11253                        Op.getOperand(2), Op.getOperand(3));
11254   }
11255   }
11256 }
11257
11258 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11259   SDLoc dl(Op);
11260   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11261   switch (IntNo) {
11262   default: return SDValue();    // Don't custom lower most intrinsics.
11263
11264   // RDRAND/RDSEED intrinsics.
11265   case Intrinsic::x86_rdrand_16:
11266   case Intrinsic::x86_rdrand_32:
11267   case Intrinsic::x86_rdrand_64:
11268   case Intrinsic::x86_rdseed_16:
11269   case Intrinsic::x86_rdseed_32:
11270   case Intrinsic::x86_rdseed_64: {
11271     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11272                        IntNo == Intrinsic::x86_rdseed_32 ||
11273                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11274                                                             X86ISD::RDRAND;
11275     // Emit the node with the right value type.
11276     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11277     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11278
11279     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11280     // Otherwise return the value from Rand, which is always 0, casted to i32.
11281     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11282                       DAG.getConstant(1, Op->getValueType(1)),
11283                       DAG.getConstant(X86::COND_B, MVT::i32),
11284                       SDValue(Result.getNode(), 1) };
11285     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11286                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11287                                   Ops, array_lengthof(Ops));
11288
11289     // Return { result, isValid, chain }.
11290     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11291                        SDValue(Result.getNode(), 2));
11292   }
11293
11294   // XTEST intrinsics.
11295   case Intrinsic::x86_xtest: {
11296     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11297     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11298     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11299                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11300                                 InTrans);
11301     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11302     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11303                        Ret, SDValue(InTrans.getNode(), 1));
11304   }
11305   }
11306 }
11307
11308 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11309                                            SelectionDAG &DAG) const {
11310   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11311   MFI->setReturnAddressIsTaken(true);
11312
11313   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11314   SDLoc dl(Op);
11315   EVT PtrVT = getPointerTy();
11316
11317   if (Depth > 0) {
11318     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11319     const X86RegisterInfo *RegInfo =
11320       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11321     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11322     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11323                        DAG.getNode(ISD::ADD, dl, PtrVT,
11324                                    FrameAddr, Offset),
11325                        MachinePointerInfo(), false, false, false, 0);
11326   }
11327
11328   // Just load the return address.
11329   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11330   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11331                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11332 }
11333
11334 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11335   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11336   MFI->setFrameAddressIsTaken(true);
11337
11338   EVT VT = Op.getValueType();
11339   SDLoc dl(Op);  // FIXME probably not meaningful
11340   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11341   const X86RegisterInfo *RegInfo =
11342     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11343   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11344   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11345           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11346          "Invalid Frame Register!");
11347   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11348   while (Depth--)
11349     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11350                             MachinePointerInfo(),
11351                             false, false, false, 0);
11352   return FrameAddr;
11353 }
11354
11355 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11356                                                      SelectionDAG &DAG) const {
11357   const X86RegisterInfo *RegInfo =
11358     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11359   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11360 }
11361
11362 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11363   SDValue Chain     = Op.getOperand(0);
11364   SDValue Offset    = Op.getOperand(1);
11365   SDValue Handler   = Op.getOperand(2);
11366   SDLoc dl      (Op);
11367
11368   EVT PtrVT = getPointerTy();
11369   const X86RegisterInfo *RegInfo =
11370     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11371   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11372   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11373           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11374          "Invalid Frame Register!");
11375   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11376   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11377
11378   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11379                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11380   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11381   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11382                        false, false, 0);
11383   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11384
11385   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11386                      DAG.getRegister(StoreAddrReg, PtrVT));
11387 }
11388
11389 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11390                                                SelectionDAG &DAG) const {
11391   SDLoc DL(Op);
11392   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11393                      DAG.getVTList(MVT::i32, MVT::Other),
11394                      Op.getOperand(0), Op.getOperand(1));
11395 }
11396
11397 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11398                                                 SelectionDAG &DAG) const {
11399   SDLoc DL(Op);
11400   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11401                      Op.getOperand(0), Op.getOperand(1));
11402 }
11403
11404 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11405   return Op.getOperand(0);
11406 }
11407
11408 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11409                                                 SelectionDAG &DAG) const {
11410   SDValue Root = Op.getOperand(0);
11411   SDValue Trmp = Op.getOperand(1); // trampoline
11412   SDValue FPtr = Op.getOperand(2); // nested function
11413   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11414   SDLoc dl (Op);
11415
11416   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11417   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11418
11419   if (Subtarget->is64Bit()) {
11420     SDValue OutChains[6];
11421
11422     // Large code-model.
11423     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11424     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11425
11426     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11427     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11428
11429     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11430
11431     // Load the pointer to the nested function into R11.
11432     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11433     SDValue Addr = Trmp;
11434     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11435                                 Addr, MachinePointerInfo(TrmpAddr),
11436                                 false, false, 0);
11437
11438     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11439                        DAG.getConstant(2, MVT::i64));
11440     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11441                                 MachinePointerInfo(TrmpAddr, 2),
11442                                 false, false, 2);
11443
11444     // Load the 'nest' parameter value into R10.
11445     // R10 is specified in X86CallingConv.td
11446     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11447     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11448                        DAG.getConstant(10, MVT::i64));
11449     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11450                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11451                                 false, false, 0);
11452
11453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11454                        DAG.getConstant(12, MVT::i64));
11455     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11456                                 MachinePointerInfo(TrmpAddr, 12),
11457                                 false, false, 2);
11458
11459     // Jump to the nested function.
11460     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11461     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11462                        DAG.getConstant(20, MVT::i64));
11463     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11464                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11465                                 false, false, 0);
11466
11467     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11468     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11469                        DAG.getConstant(22, MVT::i64));
11470     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11471                                 MachinePointerInfo(TrmpAddr, 22),
11472                                 false, false, 0);
11473
11474     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11475   } else {
11476     const Function *Func =
11477       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11478     CallingConv::ID CC = Func->getCallingConv();
11479     unsigned NestReg;
11480
11481     switch (CC) {
11482     default:
11483       llvm_unreachable("Unsupported calling convention");
11484     case CallingConv::C:
11485     case CallingConv::X86_StdCall: {
11486       // Pass 'nest' parameter in ECX.
11487       // Must be kept in sync with X86CallingConv.td
11488       NestReg = X86::ECX;
11489
11490       // Check that ECX wasn't needed by an 'inreg' parameter.
11491       FunctionType *FTy = Func->getFunctionType();
11492       const AttributeSet &Attrs = Func->getAttributes();
11493
11494       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11495         unsigned InRegCount = 0;
11496         unsigned Idx = 1;
11497
11498         for (FunctionType::param_iterator I = FTy->param_begin(),
11499              E = FTy->param_end(); I != E; ++I, ++Idx)
11500           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11501             // FIXME: should only count parameters that are lowered to integers.
11502             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11503
11504         if (InRegCount > 2) {
11505           report_fatal_error("Nest register in use - reduce number of inreg"
11506                              " parameters!");
11507         }
11508       }
11509       break;
11510     }
11511     case CallingConv::X86_FastCall:
11512     case CallingConv::X86_ThisCall:
11513     case CallingConv::Fast:
11514       // Pass 'nest' parameter in EAX.
11515       // Must be kept in sync with X86CallingConv.td
11516       NestReg = X86::EAX;
11517       break;
11518     }
11519
11520     SDValue OutChains[4];
11521     SDValue Addr, Disp;
11522
11523     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11524                        DAG.getConstant(10, MVT::i32));
11525     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11526
11527     // This is storing the opcode for MOV32ri.
11528     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11529     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11530     OutChains[0] = DAG.getStore(Root, dl,
11531                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11532                                 Trmp, MachinePointerInfo(TrmpAddr),
11533                                 false, false, 0);
11534
11535     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11536                        DAG.getConstant(1, MVT::i32));
11537     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11538                                 MachinePointerInfo(TrmpAddr, 1),
11539                                 false, false, 1);
11540
11541     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11542     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11543                        DAG.getConstant(5, MVT::i32));
11544     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11545                                 MachinePointerInfo(TrmpAddr, 5),
11546                                 false, false, 1);
11547
11548     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11549                        DAG.getConstant(6, MVT::i32));
11550     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11551                                 MachinePointerInfo(TrmpAddr, 6),
11552                                 false, false, 1);
11553
11554     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11555   }
11556 }
11557
11558 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11559                                             SelectionDAG &DAG) const {
11560   /*
11561    The rounding mode is in bits 11:10 of FPSR, and has the following
11562    settings:
11563      00 Round to nearest
11564      01 Round to -inf
11565      10 Round to +inf
11566      11 Round to 0
11567
11568   FLT_ROUNDS, on the other hand, expects the following:
11569     -1 Undefined
11570      0 Round to 0
11571      1 Round to nearest
11572      2 Round to +inf
11573      3 Round to -inf
11574
11575   To perform the conversion, we do:
11576     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11577   */
11578
11579   MachineFunction &MF = DAG.getMachineFunction();
11580   const TargetMachine &TM = MF.getTarget();
11581   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11582   unsigned StackAlignment = TFI.getStackAlignment();
11583   EVT VT = Op.getValueType();
11584   SDLoc DL(Op);
11585
11586   // Save FP Control Word to stack slot
11587   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11588   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11589
11590   MachineMemOperand *MMO =
11591    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11592                            MachineMemOperand::MOStore, 2, 2);
11593
11594   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11595   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11596                                           DAG.getVTList(MVT::Other),
11597                                           Ops, array_lengthof(Ops), MVT::i16,
11598                                           MMO);
11599
11600   // Load FP Control Word from stack slot
11601   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11602                             MachinePointerInfo(), false, false, false, 0);
11603
11604   // Transform as necessary
11605   SDValue CWD1 =
11606     DAG.getNode(ISD::SRL, DL, MVT::i16,
11607                 DAG.getNode(ISD::AND, DL, MVT::i16,
11608                             CWD, DAG.getConstant(0x800, MVT::i16)),
11609                 DAG.getConstant(11, MVT::i8));
11610   SDValue CWD2 =
11611     DAG.getNode(ISD::SRL, DL, MVT::i16,
11612                 DAG.getNode(ISD::AND, DL, MVT::i16,
11613                             CWD, DAG.getConstant(0x400, MVT::i16)),
11614                 DAG.getConstant(9, MVT::i8));
11615
11616   SDValue RetVal =
11617     DAG.getNode(ISD::AND, DL, MVT::i16,
11618                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11619                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11620                             DAG.getConstant(1, MVT::i16)),
11621                 DAG.getConstant(3, MVT::i16));
11622
11623   return DAG.getNode((VT.getSizeInBits() < 16 ?
11624                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11625 }
11626
11627 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11628   EVT VT = Op.getValueType();
11629   EVT OpVT = VT;
11630   unsigned NumBits = VT.getSizeInBits();
11631   SDLoc dl(Op);
11632
11633   Op = Op.getOperand(0);
11634   if (VT == MVT::i8) {
11635     // Zero extend to i32 since there is not an i8 bsr.
11636     OpVT = MVT::i32;
11637     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11638   }
11639
11640   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11641   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11642   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11643
11644   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11645   SDValue Ops[] = {
11646     Op,
11647     DAG.getConstant(NumBits+NumBits-1, OpVT),
11648     DAG.getConstant(X86::COND_E, MVT::i8),
11649     Op.getValue(1)
11650   };
11651   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11652
11653   // Finally xor with NumBits-1.
11654   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11655
11656   if (VT == MVT::i8)
11657     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11658   return Op;
11659 }
11660
11661 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11662   EVT VT = Op.getValueType();
11663   EVT OpVT = VT;
11664   unsigned NumBits = VT.getSizeInBits();
11665   SDLoc dl(Op);
11666
11667   Op = Op.getOperand(0);
11668   if (VT == MVT::i8) {
11669     // Zero extend to i32 since there is not an i8 bsr.
11670     OpVT = MVT::i32;
11671     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11672   }
11673
11674   // Issue a bsr (scan bits in reverse).
11675   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11676   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11677
11678   // And xor with NumBits-1.
11679   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11680
11681   if (VT == MVT::i8)
11682     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11683   return Op;
11684 }
11685
11686 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11687   EVT VT = Op.getValueType();
11688   unsigned NumBits = VT.getSizeInBits();
11689   SDLoc dl(Op);
11690   Op = Op.getOperand(0);
11691
11692   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11693   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11694   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11695
11696   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11697   SDValue Ops[] = {
11698     Op,
11699     DAG.getConstant(NumBits, VT),
11700     DAG.getConstant(X86::COND_E, MVT::i8),
11701     Op.getValue(1)
11702   };
11703   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11704 }
11705
11706 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11707 // ones, and then concatenate the result back.
11708 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11709   EVT VT = Op.getValueType();
11710
11711   assert(VT.is256BitVector() && VT.isInteger() &&
11712          "Unsupported value type for operation");
11713
11714   unsigned NumElems = VT.getVectorNumElements();
11715   SDLoc dl(Op);
11716
11717   // Extract the LHS vectors
11718   SDValue LHS = Op.getOperand(0);
11719   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11720   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11721
11722   // Extract the RHS vectors
11723   SDValue RHS = Op.getOperand(1);
11724   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11725   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11726
11727   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11728   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11729
11730   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11731                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11732                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11733 }
11734
11735 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11736   assert(Op.getValueType().is256BitVector() &&
11737          Op.getValueType().isInteger() &&
11738          "Only handle AVX 256-bit vector integer operation");
11739   return Lower256IntArith(Op, DAG);
11740 }
11741
11742 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11743   assert(Op.getValueType().is256BitVector() &&
11744          Op.getValueType().isInteger() &&
11745          "Only handle AVX 256-bit vector integer operation");
11746   return Lower256IntArith(Op, DAG);
11747 }
11748
11749 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11750                         SelectionDAG &DAG) {
11751   SDLoc dl(Op);
11752   EVT VT = Op.getValueType();
11753
11754   // Decompose 256-bit ops into smaller 128-bit ops.
11755   if (VT.is256BitVector() && !Subtarget->hasInt256())
11756     return Lower256IntArith(Op, DAG);
11757
11758   SDValue A = Op.getOperand(0);
11759   SDValue B = Op.getOperand(1);
11760
11761   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11762   if (VT == MVT::v4i32) {
11763     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11764            "Should not custom lower when pmuldq is available!");
11765
11766     // Extract the odd parts.
11767     static const int UnpackMask[] = { 1, -1, 3, -1 };
11768     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11769     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11770
11771     // Multiply the even parts.
11772     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11773     // Now multiply odd parts.
11774     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11775
11776     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11777     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11778
11779     // Merge the two vectors back together with a shuffle. This expands into 2
11780     // shuffles.
11781     static const int ShufMask[] = { 0, 4, 2, 6 };
11782     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11783   }
11784
11785   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11786          "Only know how to lower V2I64/V4I64 multiply");
11787
11788   //  Ahi = psrlqi(a, 32);
11789   //  Bhi = psrlqi(b, 32);
11790   //
11791   //  AloBlo = pmuludq(a, b);
11792   //  AloBhi = pmuludq(a, Bhi);
11793   //  AhiBlo = pmuludq(Ahi, b);
11794
11795   //  AloBhi = psllqi(AloBhi, 32);
11796   //  AhiBlo = psllqi(AhiBlo, 32);
11797   //  return AloBlo + AloBhi + AhiBlo;
11798
11799   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11800
11801   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11802   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11803
11804   // Bit cast to 32-bit vectors for MULUDQ
11805   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11806   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11807   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11808   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11809   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11810
11811   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11812   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11813   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11814
11815   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11816   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11817
11818   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11819   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11820 }
11821
11822 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11823   EVT VT = Op.getValueType();
11824   EVT EltTy = VT.getVectorElementType();
11825   unsigned NumElts = VT.getVectorNumElements();
11826   SDValue N0 = Op.getOperand(0);
11827   SDLoc dl(Op);
11828
11829   // Lower sdiv X, pow2-const.
11830   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11831   if (!C)
11832     return SDValue();
11833
11834   APInt SplatValue, SplatUndef;
11835   unsigned SplatBitSize;
11836   bool HasAnyUndefs;
11837   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11838                           HasAnyUndefs) ||
11839       EltTy.getSizeInBits() < SplatBitSize)
11840     return SDValue();
11841
11842   if ((SplatValue != 0) &&
11843       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11844     unsigned lg2 = SplatValue.countTrailingZeros();
11845     // Splat the sign bit.
11846     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11847     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11848     // Add (N0 < 0) ? abs2 - 1 : 0;
11849     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11850     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11851     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11852     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11853     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11854
11855     // If we're dividing by a positive value, we're done.  Otherwise, we must
11856     // negate the result.
11857     if (SplatValue.isNonNegative())
11858       return SRA;
11859
11860     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11861     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11862     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11863   }
11864   return SDValue();
11865 }
11866
11867 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11868                                          const X86Subtarget *Subtarget) {
11869   EVT VT = Op.getValueType();
11870   SDLoc dl(Op);
11871   SDValue R = Op.getOperand(0);
11872   SDValue Amt = Op.getOperand(1);
11873
11874   // Optimize shl/srl/sra with constant shift amount.
11875   if (isSplatVector(Amt.getNode())) {
11876     SDValue SclrAmt = Amt->getOperand(0);
11877     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11878       uint64_t ShiftAmt = C->getZExtValue();
11879
11880       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11881           (Subtarget->hasInt256() &&
11882            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11883         if (Op.getOpcode() == ISD::SHL)
11884           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11885                              DAG.getConstant(ShiftAmt, MVT::i32));
11886         if (Op.getOpcode() == ISD::SRL)
11887           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11888                              DAG.getConstant(ShiftAmt, MVT::i32));
11889         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11890           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11891                              DAG.getConstant(ShiftAmt, MVT::i32));
11892       }
11893
11894       if (VT == MVT::v16i8) {
11895         if (Op.getOpcode() == ISD::SHL) {
11896           // Make a large shift.
11897           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11898                                     DAG.getConstant(ShiftAmt, MVT::i32));
11899           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11900           // Zero out the rightmost bits.
11901           SmallVector<SDValue, 16> V(16,
11902                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11903                                                      MVT::i8));
11904           return DAG.getNode(ISD::AND, dl, VT, SHL,
11905                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11906         }
11907         if (Op.getOpcode() == ISD::SRL) {
11908           // Make a large shift.
11909           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11910                                     DAG.getConstant(ShiftAmt, MVT::i32));
11911           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11912           // Zero out the leftmost bits.
11913           SmallVector<SDValue, 16> V(16,
11914                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11915                                                      MVT::i8));
11916           return DAG.getNode(ISD::AND, dl, VT, SRL,
11917                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11918         }
11919         if (Op.getOpcode() == ISD::SRA) {
11920           if (ShiftAmt == 7) {
11921             // R s>> 7  ===  R s< 0
11922             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11923             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11924           }
11925
11926           // R s>> a === ((R u>> a) ^ m) - m
11927           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11928           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11929                                                          MVT::i8));
11930           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11931           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11932           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11933           return Res;
11934         }
11935         llvm_unreachable("Unknown shift opcode.");
11936       }
11937
11938       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11939         if (Op.getOpcode() == ISD::SHL) {
11940           // Make a large shift.
11941           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11942                                     DAG.getConstant(ShiftAmt, MVT::i32));
11943           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11944           // Zero out the rightmost bits.
11945           SmallVector<SDValue, 32> V(32,
11946                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11947                                                      MVT::i8));
11948           return DAG.getNode(ISD::AND, dl, VT, SHL,
11949                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11950         }
11951         if (Op.getOpcode() == ISD::SRL) {
11952           // Make a large shift.
11953           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11954                                     DAG.getConstant(ShiftAmt, MVT::i32));
11955           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11956           // Zero out the leftmost bits.
11957           SmallVector<SDValue, 32> V(32,
11958                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11959                                                      MVT::i8));
11960           return DAG.getNode(ISD::AND, dl, VT, SRL,
11961                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11962         }
11963         if (Op.getOpcode() == ISD::SRA) {
11964           if (ShiftAmt == 7) {
11965             // R s>> 7  ===  R s< 0
11966             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11967             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11968           }
11969
11970           // R s>> a === ((R u>> a) ^ m) - m
11971           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11972           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11973                                                          MVT::i8));
11974           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11975           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11976           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11977           return Res;
11978         }
11979         llvm_unreachable("Unknown shift opcode.");
11980       }
11981     }
11982   }
11983
11984   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11985   if (!Subtarget->is64Bit() &&
11986       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11987       Amt.getOpcode() == ISD::BITCAST &&
11988       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11989     Amt = Amt.getOperand(0);
11990     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11991                      VT.getVectorNumElements();
11992     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11993     uint64_t ShiftAmt = 0;
11994     for (unsigned i = 0; i != Ratio; ++i) {
11995       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11996       if (C == 0)
11997         return SDValue();
11998       // 6 == Log2(64)
11999       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12000     }
12001     // Check remaining shift amounts.
12002     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12003       uint64_t ShAmt = 0;
12004       for (unsigned j = 0; j != Ratio; ++j) {
12005         ConstantSDNode *C =
12006           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12007         if (C == 0)
12008           return SDValue();
12009         // 6 == Log2(64)
12010         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12011       }
12012       if (ShAmt != ShiftAmt)
12013         return SDValue();
12014     }
12015     switch (Op.getOpcode()) {
12016     default:
12017       llvm_unreachable("Unknown shift opcode!");
12018     case ISD::SHL:
12019       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12020                          DAG.getConstant(ShiftAmt, MVT::i32));
12021     case ISD::SRL:
12022       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12023                          DAG.getConstant(ShiftAmt, MVT::i32));
12024     case ISD::SRA:
12025       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12026                          DAG.getConstant(ShiftAmt, MVT::i32));
12027     }
12028   }
12029
12030   return SDValue();
12031 }
12032
12033 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12034                                         const X86Subtarget* Subtarget) {
12035   EVT VT = Op.getValueType();
12036   SDLoc dl(Op);
12037   SDValue R = Op.getOperand(0);
12038   SDValue Amt = Op.getOperand(1);
12039
12040   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12041       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12042       (Subtarget->hasInt256() &&
12043        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12044         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12045     SDValue BaseShAmt;
12046     EVT EltVT = VT.getVectorElementType();
12047
12048     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12049       unsigned NumElts = VT.getVectorNumElements();
12050       unsigned i, j;
12051       for (i = 0; i != NumElts; ++i) {
12052         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12053           continue;
12054         break;
12055       }
12056       for (j = i; j != NumElts; ++j) {
12057         SDValue Arg = Amt.getOperand(j);
12058         if (Arg.getOpcode() == ISD::UNDEF) continue;
12059         if (Arg != Amt.getOperand(i))
12060           break;
12061       }
12062       if (i != NumElts && j == NumElts)
12063         BaseShAmt = Amt.getOperand(i);
12064     } else {
12065       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12066         Amt = Amt.getOperand(0);
12067       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12068                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12069         SDValue InVec = Amt.getOperand(0);
12070         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12071           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12072           unsigned i = 0;
12073           for (; i != NumElts; ++i) {
12074             SDValue Arg = InVec.getOperand(i);
12075             if (Arg.getOpcode() == ISD::UNDEF) continue;
12076             BaseShAmt = Arg;
12077             break;
12078           }
12079         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12080            if (ConstantSDNode *C =
12081                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12082              unsigned SplatIdx =
12083                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12084              if (C->getZExtValue() == SplatIdx)
12085                BaseShAmt = InVec.getOperand(1);
12086            }
12087         }
12088         if (BaseShAmt.getNode() == 0)
12089           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12090                                   DAG.getIntPtrConstant(0));
12091       }
12092     }
12093
12094     if (BaseShAmt.getNode()) {
12095       if (EltVT.bitsGT(MVT::i32))
12096         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12097       else if (EltVT.bitsLT(MVT::i32))
12098         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12099
12100       switch (Op.getOpcode()) {
12101       default:
12102         llvm_unreachable("Unknown shift opcode!");
12103       case ISD::SHL:
12104         switch (VT.getSimpleVT().SimpleTy) {
12105         default: return SDValue();
12106         case MVT::v2i64:
12107         case MVT::v4i32:
12108         case MVT::v8i16:
12109         case MVT::v4i64:
12110         case MVT::v8i32:
12111         case MVT::v16i16:
12112           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12113         }
12114       case ISD::SRA:
12115         switch (VT.getSimpleVT().SimpleTy) {
12116         default: return SDValue();
12117         case MVT::v4i32:
12118         case MVT::v8i16:
12119         case MVT::v8i32:
12120         case MVT::v16i16:
12121           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12122         }
12123       case ISD::SRL:
12124         switch (VT.getSimpleVT().SimpleTy) {
12125         default: return SDValue();
12126         case MVT::v2i64:
12127         case MVT::v4i32:
12128         case MVT::v8i16:
12129         case MVT::v4i64:
12130         case MVT::v8i32:
12131         case MVT::v16i16:
12132           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12133         }
12134       }
12135     }
12136   }
12137
12138   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12139   if (!Subtarget->is64Bit() &&
12140       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12141       Amt.getOpcode() == ISD::BITCAST &&
12142       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12143     Amt = Amt.getOperand(0);
12144     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12145                      VT.getVectorNumElements();
12146     std::vector<SDValue> Vals(Ratio);
12147     for (unsigned i = 0; i != Ratio; ++i)
12148       Vals[i] = Amt.getOperand(i);
12149     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12150       for (unsigned j = 0; j != Ratio; ++j)
12151         if (Vals[j] != Amt.getOperand(i + j))
12152           return SDValue();
12153     }
12154     switch (Op.getOpcode()) {
12155     default:
12156       llvm_unreachable("Unknown shift opcode!");
12157     case ISD::SHL:
12158       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12159     case ISD::SRL:
12160       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12161     case ISD::SRA:
12162       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12163     }
12164   }
12165
12166   return SDValue();
12167 }
12168
12169 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12170
12171   EVT VT = Op.getValueType();
12172   SDLoc dl(Op);
12173   SDValue R = Op.getOperand(0);
12174   SDValue Amt = Op.getOperand(1);
12175   SDValue V;
12176
12177   if (!Subtarget->hasSSE2())
12178     return SDValue();
12179
12180   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12181   if (V.getNode())
12182     return V;
12183
12184   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12185   if (V.getNode())
12186       return V;
12187
12188   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12189   if (Subtarget->hasInt256()) {
12190     if (Op.getOpcode() == ISD::SRL &&
12191         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12192          VT == MVT::v4i64 || VT == MVT::v8i32))
12193       return Op;
12194     if (Op.getOpcode() == ISD::SHL &&
12195         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12196          VT == MVT::v4i64 || VT == MVT::v8i32))
12197       return Op;
12198     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12199       return Op;
12200   }
12201
12202   // Lower SHL with variable shift amount.
12203   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12204     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12205
12206     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12207     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12208     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12209     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12210   }
12211   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12212     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12213
12214     // a = a << 5;
12215     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12216     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12217
12218     // Turn 'a' into a mask suitable for VSELECT
12219     SDValue VSelM = DAG.getConstant(0x80, VT);
12220     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12221     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12222
12223     SDValue CM1 = DAG.getConstant(0x0f, VT);
12224     SDValue CM2 = DAG.getConstant(0x3f, VT);
12225
12226     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12227     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12228     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12229                             DAG.getConstant(4, MVT::i32), DAG);
12230     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12231     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12232
12233     // a += a
12234     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12235     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12236     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12237
12238     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12239     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12240     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12241                             DAG.getConstant(2, MVT::i32), DAG);
12242     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12243     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12244
12245     // a += a
12246     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12247     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12248     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12249
12250     // return VSELECT(r, r+r, a);
12251     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12252                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12253     return R;
12254   }
12255
12256   // Decompose 256-bit shifts into smaller 128-bit shifts.
12257   if (VT.is256BitVector()) {
12258     unsigned NumElems = VT.getVectorNumElements();
12259     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12260     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12261
12262     // Extract the two vectors
12263     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12264     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12265
12266     // Recreate the shift amount vectors
12267     SDValue Amt1, Amt2;
12268     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12269       // Constant shift amount
12270       SmallVector<SDValue, 4> Amt1Csts;
12271       SmallVector<SDValue, 4> Amt2Csts;
12272       for (unsigned i = 0; i != NumElems/2; ++i)
12273         Amt1Csts.push_back(Amt->getOperand(i));
12274       for (unsigned i = NumElems/2; i != NumElems; ++i)
12275         Amt2Csts.push_back(Amt->getOperand(i));
12276
12277       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12278                                  &Amt1Csts[0], NumElems/2);
12279       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12280                                  &Amt2Csts[0], NumElems/2);
12281     } else {
12282       // Variable shift amount
12283       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12284       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12285     }
12286
12287     // Issue new vector shifts for the smaller types
12288     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12289     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12290
12291     // Concatenate the result back
12292     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12293   }
12294
12295   return SDValue();
12296 }
12297
12298 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12299   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12300   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12301   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12302   // has only one use.
12303   SDNode *N = Op.getNode();
12304   SDValue LHS = N->getOperand(0);
12305   SDValue RHS = N->getOperand(1);
12306   unsigned BaseOp = 0;
12307   unsigned Cond = 0;
12308   SDLoc DL(Op);
12309   switch (Op.getOpcode()) {
12310   default: llvm_unreachable("Unknown ovf instruction!");
12311   case ISD::SADDO:
12312     // A subtract of one will be selected as a INC. Note that INC doesn't
12313     // set CF, so we can't do this for UADDO.
12314     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12315       if (C->isOne()) {
12316         BaseOp = X86ISD::INC;
12317         Cond = X86::COND_O;
12318         break;
12319       }
12320     BaseOp = X86ISD::ADD;
12321     Cond = X86::COND_O;
12322     break;
12323   case ISD::UADDO:
12324     BaseOp = X86ISD::ADD;
12325     Cond = X86::COND_B;
12326     break;
12327   case ISD::SSUBO:
12328     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12329     // set CF, so we can't do this for USUBO.
12330     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12331       if (C->isOne()) {
12332         BaseOp = X86ISD::DEC;
12333         Cond = X86::COND_O;
12334         break;
12335       }
12336     BaseOp = X86ISD::SUB;
12337     Cond = X86::COND_O;
12338     break;
12339   case ISD::USUBO:
12340     BaseOp = X86ISD::SUB;
12341     Cond = X86::COND_B;
12342     break;
12343   case ISD::SMULO:
12344     BaseOp = X86ISD::SMUL;
12345     Cond = X86::COND_O;
12346     break;
12347   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12348     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12349                                  MVT::i32);
12350     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12351
12352     SDValue SetCC =
12353       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12354                   DAG.getConstant(X86::COND_O, MVT::i32),
12355                   SDValue(Sum.getNode(), 2));
12356
12357     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12358   }
12359   }
12360
12361   // Also sets EFLAGS.
12362   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12363   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12364
12365   SDValue SetCC =
12366     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12367                 DAG.getConstant(Cond, MVT::i32),
12368                 SDValue(Sum.getNode(), 1));
12369
12370   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12371 }
12372
12373 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12374                                                   SelectionDAG &DAG) const {
12375   SDLoc dl(Op);
12376   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12377   EVT VT = Op.getValueType();
12378
12379   if (!Subtarget->hasSSE2() || !VT.isVector())
12380     return SDValue();
12381
12382   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12383                       ExtraVT.getScalarType().getSizeInBits();
12384   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12385
12386   switch (VT.getSimpleVT().SimpleTy) {
12387     default: return SDValue();
12388     case MVT::v8i32:
12389     case MVT::v16i16:
12390       if (!Subtarget->hasFp256())
12391         return SDValue();
12392       if (!Subtarget->hasInt256()) {
12393         // needs to be split
12394         unsigned NumElems = VT.getVectorNumElements();
12395
12396         // Extract the LHS vectors
12397         SDValue LHS = Op.getOperand(0);
12398         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12399         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12400
12401         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12402         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12403
12404         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12405         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12406         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12407                                    ExtraNumElems/2);
12408         SDValue Extra = DAG.getValueType(ExtraVT);
12409
12410         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12411         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12412
12413         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12414       }
12415       // fall through
12416     case MVT::v4i32:
12417     case MVT::v8i16: {
12418       // (sext (vzext x)) -> (vsext x)
12419       SDValue Op0 = Op.getOperand(0);
12420       SDValue Op00 = Op0.getOperand(0);
12421       SDValue Tmp1;
12422       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12423       if (Op0.getOpcode() == ISD::BITCAST &&
12424           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12425         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12426       if (Tmp1.getNode()) {
12427         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12428         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12429                "This optimization is invalid without a VZEXT.");
12430         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12431       }
12432
12433       // If the above didn't work, then just use Shift-Left + Shift-Right.
12434       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12435       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12436     }
12437   }
12438 }
12439
12440 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12441                                  SelectionDAG &DAG) {
12442   SDLoc dl(Op);
12443   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12444     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12445   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12446     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12447
12448   // The only fence that needs an instruction is a sequentially-consistent
12449   // cross-thread fence.
12450   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12451     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12452     // no-sse2). There isn't any reason to disable it if the target processor
12453     // supports it.
12454     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12455       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12456
12457     SDValue Chain = Op.getOperand(0);
12458     SDValue Zero = DAG.getConstant(0, MVT::i32);
12459     SDValue Ops[] = {
12460       DAG.getRegister(X86::ESP, MVT::i32), // Base
12461       DAG.getTargetConstant(1, MVT::i8),   // Scale
12462       DAG.getRegister(0, MVT::i32),        // Index
12463       DAG.getTargetConstant(0, MVT::i32),  // Disp
12464       DAG.getRegister(0, MVT::i32),        // Segment.
12465       Zero,
12466       Chain
12467     };
12468     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12469     return SDValue(Res, 0);
12470   }
12471
12472   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12473   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12474 }
12475
12476 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12477                              SelectionDAG &DAG) {
12478   EVT T = Op.getValueType();
12479   SDLoc DL(Op);
12480   unsigned Reg = 0;
12481   unsigned size = 0;
12482   switch(T.getSimpleVT().SimpleTy) {
12483   default: llvm_unreachable("Invalid value type!");
12484   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12485   case MVT::i16: Reg = X86::AX;  size = 2; break;
12486   case MVT::i32: Reg = X86::EAX; size = 4; break;
12487   case MVT::i64:
12488     assert(Subtarget->is64Bit() && "Node not type legal!");
12489     Reg = X86::RAX; size = 8;
12490     break;
12491   }
12492   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12493                                     Op.getOperand(2), SDValue());
12494   SDValue Ops[] = { cpIn.getValue(0),
12495                     Op.getOperand(1),
12496                     Op.getOperand(3),
12497                     DAG.getTargetConstant(size, MVT::i8),
12498                     cpIn.getValue(1) };
12499   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12500   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12501   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12502                                            Ops, array_lengthof(Ops), T, MMO);
12503   SDValue cpOut =
12504     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12505   return cpOut;
12506 }
12507
12508 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12509                                      SelectionDAG &DAG) {
12510   assert(Subtarget->is64Bit() && "Result not type legalized?");
12511   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12512   SDValue TheChain = Op.getOperand(0);
12513   SDLoc dl(Op);
12514   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12515   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12516   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12517                                    rax.getValue(2));
12518   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12519                             DAG.getConstant(32, MVT::i8));
12520   SDValue Ops[] = {
12521     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12522     rdx.getValue(1)
12523   };
12524   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12525 }
12526
12527 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12528   EVT SrcVT = Op.getOperand(0).getValueType();
12529   EVT DstVT = Op.getValueType();
12530   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12531          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12532   assert((DstVT == MVT::i64 ||
12533           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12534          "Unexpected custom BITCAST");
12535   // i64 <=> MMX conversions are Legal.
12536   if (SrcVT==MVT::i64 && DstVT.isVector())
12537     return Op;
12538   if (DstVT==MVT::i64 && SrcVT.isVector())
12539     return Op;
12540   // MMX <=> MMX conversions are Legal.
12541   if (SrcVT.isVector() && DstVT.isVector())
12542     return Op;
12543   // All other conversions need to be expanded.
12544   return SDValue();
12545 }
12546
12547 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12548   SDNode *Node = Op.getNode();
12549   SDLoc dl(Node);
12550   EVT T = Node->getValueType(0);
12551   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12552                               DAG.getConstant(0, T), Node->getOperand(2));
12553   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12554                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12555                        Node->getOperand(0),
12556                        Node->getOperand(1), negOp,
12557                        cast<AtomicSDNode>(Node)->getSrcValue(),
12558                        cast<AtomicSDNode>(Node)->getAlignment(),
12559                        cast<AtomicSDNode>(Node)->getOrdering(),
12560                        cast<AtomicSDNode>(Node)->getSynchScope());
12561 }
12562
12563 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12564   SDNode *Node = Op.getNode();
12565   SDLoc dl(Node);
12566   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12567
12568   // Convert seq_cst store -> xchg
12569   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12570   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12571   //        (The only way to get a 16-byte store is cmpxchg16b)
12572   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12573   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12574       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12575     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12576                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12577                                  Node->getOperand(0),
12578                                  Node->getOperand(1), Node->getOperand(2),
12579                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12580                                  cast<AtomicSDNode>(Node)->getOrdering(),
12581                                  cast<AtomicSDNode>(Node)->getSynchScope());
12582     return Swap.getValue(1);
12583   }
12584   // Other atomic stores have a simple pattern.
12585   return Op;
12586 }
12587
12588 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12589   EVT VT = Op.getNode()->getValueType(0);
12590
12591   // Let legalize expand this if it isn't a legal type yet.
12592   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12593     return SDValue();
12594
12595   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12596
12597   unsigned Opc;
12598   bool ExtraOp = false;
12599   switch (Op.getOpcode()) {
12600   default: llvm_unreachable("Invalid code");
12601   case ISD::ADDC: Opc = X86ISD::ADD; break;
12602   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12603   case ISD::SUBC: Opc = X86ISD::SUB; break;
12604   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12605   }
12606
12607   if (!ExtraOp)
12608     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12609                        Op.getOperand(1));
12610   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12611                      Op.getOperand(1), Op.getOperand(2));
12612 }
12613
12614 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12615   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12616
12617   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12618   // which returns the values as { float, float } (in XMM0) or
12619   // { double, double } (which is returned in XMM0, XMM1).
12620   SDLoc dl(Op);
12621   SDValue Arg = Op.getOperand(0);
12622   EVT ArgVT = Arg.getValueType();
12623   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12624
12625   ArgListTy Args;
12626   ArgListEntry Entry;
12627
12628   Entry.Node = Arg;
12629   Entry.Ty = ArgTy;
12630   Entry.isSExt = false;
12631   Entry.isZExt = false;
12632   Args.push_back(Entry);
12633
12634   bool isF64 = ArgVT == MVT::f64;
12635   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12636   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12637   // the results are returned via SRet in memory.
12638   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12639   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12640
12641   Type *RetTy = isF64
12642     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12643     : (Type*)VectorType::get(ArgTy, 4);
12644   TargetLowering::
12645     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12646                          false, false, false, false, 0,
12647                          CallingConv::C, /*isTaillCall=*/false,
12648                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12649                          Callee, Args, DAG, dl);
12650   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12651
12652   if (isF64)
12653     // Returned in xmm0 and xmm1.
12654     return CallResult.first;
12655
12656   // Returned in bits 0:31 and 32:64 xmm0.
12657   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12658                                CallResult.first, DAG.getIntPtrConstant(0));
12659   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12660                                CallResult.first, DAG.getIntPtrConstant(1));
12661   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12662   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12663 }
12664
12665 /// LowerOperation - Provide custom lowering hooks for some operations.
12666 ///
12667 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12668   switch (Op.getOpcode()) {
12669   default: llvm_unreachable("Should not custom lower this!");
12670   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12671   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12672   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12673   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12674   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12675   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12676   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12677   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12678   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12679   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12680   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12681   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12682   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12683   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12684   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12685   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12686   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12687   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12688   case ISD::SHL_PARTS:
12689   case ISD::SRA_PARTS:
12690   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12691   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12692   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12693   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12694   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12695   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12696   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12697   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12698   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12699   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12700   case ISD::FABS:               return LowerFABS(Op, DAG);
12701   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12702   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12703   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12704   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12705   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12706   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12707   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12708   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12709   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12710   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12711   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12712   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12713   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12714   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12715   case ISD::FRAME_TO_ARGS_OFFSET:
12716                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12717   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12718   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12719   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12720   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12721   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12722   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12723   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12724   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12725   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12726   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12727   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12728   case ISD::SRA:
12729   case ISD::SRL:
12730   case ISD::SHL:                return LowerShift(Op, DAG);
12731   case ISD::SADDO:
12732   case ISD::UADDO:
12733   case ISD::SSUBO:
12734   case ISD::USUBO:
12735   case ISD::SMULO:
12736   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12737   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12738   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12739   case ISD::ADDC:
12740   case ISD::ADDE:
12741   case ISD::SUBC:
12742   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12743   case ISD::ADD:                return LowerADD(Op, DAG);
12744   case ISD::SUB:                return LowerSUB(Op, DAG);
12745   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12746   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12747   }
12748 }
12749
12750 static void ReplaceATOMIC_LOAD(SDNode *Node,
12751                                   SmallVectorImpl<SDValue> &Results,
12752                                   SelectionDAG &DAG) {
12753   SDLoc dl(Node);
12754   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12755
12756   // Convert wide load -> cmpxchg8b/cmpxchg16b
12757   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12758   //        (The only way to get a 16-byte load is cmpxchg16b)
12759   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12760   SDValue Zero = DAG.getConstant(0, VT);
12761   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12762                                Node->getOperand(0),
12763                                Node->getOperand(1), Zero, Zero,
12764                                cast<AtomicSDNode>(Node)->getMemOperand(),
12765                                cast<AtomicSDNode>(Node)->getOrdering(),
12766                                cast<AtomicSDNode>(Node)->getSynchScope());
12767   Results.push_back(Swap.getValue(0));
12768   Results.push_back(Swap.getValue(1));
12769 }
12770
12771 static void
12772 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12773                         SelectionDAG &DAG, unsigned NewOp) {
12774   SDLoc dl(Node);
12775   assert (Node->getValueType(0) == MVT::i64 &&
12776           "Only know how to expand i64 atomics");
12777
12778   SDValue Chain = Node->getOperand(0);
12779   SDValue In1 = Node->getOperand(1);
12780   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12781                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12782   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12783                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12784   SDValue Ops[] = { Chain, In1, In2L, In2H };
12785   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12786   SDValue Result =
12787     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12788                             cast<MemSDNode>(Node)->getMemOperand());
12789   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12790   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12791   Results.push_back(Result.getValue(2));
12792 }
12793
12794 /// ReplaceNodeResults - Replace a node with an illegal result type
12795 /// with a new node built out of custom code.
12796 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12797                                            SmallVectorImpl<SDValue>&Results,
12798                                            SelectionDAG &DAG) const {
12799   SDLoc dl(N);
12800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12801   switch (N->getOpcode()) {
12802   default:
12803     llvm_unreachable("Do not know how to custom type legalize this operation!");
12804   case ISD::SIGN_EXTEND_INREG:
12805   case ISD::ADDC:
12806   case ISD::ADDE:
12807   case ISD::SUBC:
12808   case ISD::SUBE:
12809     // We don't want to expand or promote these.
12810     return;
12811   case ISD::FP_TO_SINT:
12812   case ISD::FP_TO_UINT: {
12813     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12814
12815     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12816       return;
12817
12818     std::pair<SDValue,SDValue> Vals =
12819         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12820     SDValue FIST = Vals.first, StackSlot = Vals.second;
12821     if (FIST.getNode() != 0) {
12822       EVT VT = N->getValueType(0);
12823       // Return a load from the stack slot.
12824       if (StackSlot.getNode() != 0)
12825         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12826                                       MachinePointerInfo(),
12827                                       false, false, false, 0));
12828       else
12829         Results.push_back(FIST);
12830     }
12831     return;
12832   }
12833   case ISD::UINT_TO_FP: {
12834     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12835     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12836         N->getValueType(0) != MVT::v2f32)
12837       return;
12838     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12839                                  N->getOperand(0));
12840     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12841                                      MVT::f64);
12842     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12843     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12844                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12845     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12846     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12847     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12848     return;
12849   }
12850   case ISD::FP_ROUND: {
12851     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12852         return;
12853     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12854     Results.push_back(V);
12855     return;
12856   }
12857   case ISD::READCYCLECOUNTER: {
12858     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12859     SDValue TheChain = N->getOperand(0);
12860     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12861     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12862                                      rd.getValue(1));
12863     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12864                                      eax.getValue(2));
12865     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12866     SDValue Ops[] = { eax, edx };
12867     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12868                                   array_lengthof(Ops)));
12869     Results.push_back(edx.getValue(1));
12870     return;
12871   }
12872   case ISD::ATOMIC_CMP_SWAP: {
12873     EVT T = N->getValueType(0);
12874     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12875     bool Regs64bit = T == MVT::i128;
12876     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12877     SDValue cpInL, cpInH;
12878     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12879                         DAG.getConstant(0, HalfT));
12880     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12881                         DAG.getConstant(1, HalfT));
12882     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12883                              Regs64bit ? X86::RAX : X86::EAX,
12884                              cpInL, SDValue());
12885     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12886                              Regs64bit ? X86::RDX : X86::EDX,
12887                              cpInH, cpInL.getValue(1));
12888     SDValue swapInL, swapInH;
12889     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12890                           DAG.getConstant(0, HalfT));
12891     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12892                           DAG.getConstant(1, HalfT));
12893     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12894                                Regs64bit ? X86::RBX : X86::EBX,
12895                                swapInL, cpInH.getValue(1));
12896     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12897                                Regs64bit ? X86::RCX : X86::ECX,
12898                                swapInH, swapInL.getValue(1));
12899     SDValue Ops[] = { swapInH.getValue(0),
12900                       N->getOperand(1),
12901                       swapInH.getValue(1) };
12902     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12903     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12904     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12905                                   X86ISD::LCMPXCHG8_DAG;
12906     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12907                                              Ops, array_lengthof(Ops), T, MMO);
12908     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12909                                         Regs64bit ? X86::RAX : X86::EAX,
12910                                         HalfT, Result.getValue(1));
12911     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12912                                         Regs64bit ? X86::RDX : X86::EDX,
12913                                         HalfT, cpOutL.getValue(2));
12914     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12915     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12916     Results.push_back(cpOutH.getValue(1));
12917     return;
12918   }
12919   case ISD::ATOMIC_LOAD_ADD:
12920   case ISD::ATOMIC_LOAD_AND:
12921   case ISD::ATOMIC_LOAD_NAND:
12922   case ISD::ATOMIC_LOAD_OR:
12923   case ISD::ATOMIC_LOAD_SUB:
12924   case ISD::ATOMIC_LOAD_XOR:
12925   case ISD::ATOMIC_LOAD_MAX:
12926   case ISD::ATOMIC_LOAD_MIN:
12927   case ISD::ATOMIC_LOAD_UMAX:
12928   case ISD::ATOMIC_LOAD_UMIN:
12929   case ISD::ATOMIC_SWAP: {
12930     unsigned Opc;
12931     switch (N->getOpcode()) {
12932     default: llvm_unreachable("Unexpected opcode");
12933     case ISD::ATOMIC_LOAD_ADD:
12934       Opc = X86ISD::ATOMADD64_DAG;
12935       break;
12936     case ISD::ATOMIC_LOAD_AND:
12937       Opc = X86ISD::ATOMAND64_DAG;
12938       break;
12939     case ISD::ATOMIC_LOAD_NAND:
12940       Opc = X86ISD::ATOMNAND64_DAG;
12941       break;
12942     case ISD::ATOMIC_LOAD_OR:
12943       Opc = X86ISD::ATOMOR64_DAG;
12944       break;
12945     case ISD::ATOMIC_LOAD_SUB:
12946       Opc = X86ISD::ATOMSUB64_DAG;
12947       break;
12948     case ISD::ATOMIC_LOAD_XOR:
12949       Opc = X86ISD::ATOMXOR64_DAG;
12950       break;
12951     case ISD::ATOMIC_LOAD_MAX:
12952       Opc = X86ISD::ATOMMAX64_DAG;
12953       break;
12954     case ISD::ATOMIC_LOAD_MIN:
12955       Opc = X86ISD::ATOMMIN64_DAG;
12956       break;
12957     case ISD::ATOMIC_LOAD_UMAX:
12958       Opc = X86ISD::ATOMUMAX64_DAG;
12959       break;
12960     case ISD::ATOMIC_LOAD_UMIN:
12961       Opc = X86ISD::ATOMUMIN64_DAG;
12962       break;
12963     case ISD::ATOMIC_SWAP:
12964       Opc = X86ISD::ATOMSWAP64_DAG;
12965       break;
12966     }
12967     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12968     return;
12969   }
12970   case ISD::ATOMIC_LOAD:
12971     ReplaceATOMIC_LOAD(N, Results, DAG);
12972   }
12973 }
12974
12975 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12976   switch (Opcode) {
12977   default: return NULL;
12978   case X86ISD::BSF:                return "X86ISD::BSF";
12979   case X86ISD::BSR:                return "X86ISD::BSR";
12980   case X86ISD::SHLD:               return "X86ISD::SHLD";
12981   case X86ISD::SHRD:               return "X86ISD::SHRD";
12982   case X86ISD::FAND:               return "X86ISD::FAND";
12983   case X86ISD::FOR:                return "X86ISD::FOR";
12984   case X86ISD::FXOR:               return "X86ISD::FXOR";
12985   case X86ISD::FSRL:               return "X86ISD::FSRL";
12986   case X86ISD::FILD:               return "X86ISD::FILD";
12987   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12988   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12989   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12990   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12991   case X86ISD::FLD:                return "X86ISD::FLD";
12992   case X86ISD::FST:                return "X86ISD::FST";
12993   case X86ISD::CALL:               return "X86ISD::CALL";
12994   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12995   case X86ISD::BT:                 return "X86ISD::BT";
12996   case X86ISD::CMP:                return "X86ISD::CMP";
12997   case X86ISD::COMI:               return "X86ISD::COMI";
12998   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12999   case X86ISD::SETCC:              return "X86ISD::SETCC";
13000   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13001   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13002   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13003   case X86ISD::CMOV:               return "X86ISD::CMOV";
13004   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13005   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13006   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13007   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13008   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13009   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13010   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13011   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13012   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13013   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13014   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13015   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13016   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13017   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13018   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13019   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13020   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13021   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13022   case X86ISD::HADD:               return "X86ISD::HADD";
13023   case X86ISD::HSUB:               return "X86ISD::HSUB";
13024   case X86ISD::FHADD:              return "X86ISD::FHADD";
13025   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13026   case X86ISD::UMAX:               return "X86ISD::UMAX";
13027   case X86ISD::UMIN:               return "X86ISD::UMIN";
13028   case X86ISD::SMAX:               return "X86ISD::SMAX";
13029   case X86ISD::SMIN:               return "X86ISD::SMIN";
13030   case X86ISD::FMAX:               return "X86ISD::FMAX";
13031   case X86ISD::FMIN:               return "X86ISD::FMIN";
13032   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13033   case X86ISD::FMINC:              return "X86ISD::FMINC";
13034   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13035   case X86ISD::FRCP:               return "X86ISD::FRCP";
13036   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13037   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13038   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13039   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13040   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13041   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13042   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13043   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13044   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13045   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13046   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13047   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13048   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13049   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13050   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13051   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13052   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13053   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13054   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13055   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13056   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13057   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13058   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13059   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13060   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13061   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13062   case X86ISD::VSHL:               return "X86ISD::VSHL";
13063   case X86ISD::VSRL:               return "X86ISD::VSRL";
13064   case X86ISD::VSRA:               return "X86ISD::VSRA";
13065   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13066   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13067   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13068   case X86ISD::CMPP:               return "X86ISD::CMPP";
13069   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13070   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13071   case X86ISD::ADD:                return "X86ISD::ADD";
13072   case X86ISD::SUB:                return "X86ISD::SUB";
13073   case X86ISD::ADC:                return "X86ISD::ADC";
13074   case X86ISD::SBB:                return "X86ISD::SBB";
13075   case X86ISD::SMUL:               return "X86ISD::SMUL";
13076   case X86ISD::UMUL:               return "X86ISD::UMUL";
13077   case X86ISD::INC:                return "X86ISD::INC";
13078   case X86ISD::DEC:                return "X86ISD::DEC";
13079   case X86ISD::OR:                 return "X86ISD::OR";
13080   case X86ISD::XOR:                return "X86ISD::XOR";
13081   case X86ISD::AND:                return "X86ISD::AND";
13082   case X86ISD::BLSI:               return "X86ISD::BLSI";
13083   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13084   case X86ISD::BLSR:               return "X86ISD::BLSR";
13085   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13086   case X86ISD::PTEST:              return "X86ISD::PTEST";
13087   case X86ISD::TESTP:              return "X86ISD::TESTP";
13088   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13089   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13090   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13091   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13092   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13093   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13094   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13095   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13096   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13097   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13098   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13099   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13100   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13101   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13102   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13103   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13104   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13105   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13106   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13107   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13108   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13109   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13110   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13111   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13112   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13113   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13114   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13115   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13116   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13117   case X86ISD::SAHF:               return "X86ISD::SAHF";
13118   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13119   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13120   case X86ISD::FMADD:              return "X86ISD::FMADD";
13121   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13122   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13123   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13124   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13125   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13126   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13127   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13128   case X86ISD::XTEST:              return "X86ISD::XTEST";
13129   }
13130 }
13131
13132 // isLegalAddressingMode - Return true if the addressing mode represented
13133 // by AM is legal for this target, for a load/store of the specified type.
13134 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13135                                               Type *Ty) const {
13136   // X86 supports extremely general addressing modes.
13137   CodeModel::Model M = getTargetMachine().getCodeModel();
13138   Reloc::Model R = getTargetMachine().getRelocationModel();
13139
13140   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13141   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13142     return false;
13143
13144   if (AM.BaseGV) {
13145     unsigned GVFlags =
13146       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13147
13148     // If a reference to this global requires an extra load, we can't fold it.
13149     if (isGlobalStubReference(GVFlags))
13150       return false;
13151
13152     // If BaseGV requires a register for the PIC base, we cannot also have a
13153     // BaseReg specified.
13154     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13155       return false;
13156
13157     // If lower 4G is not available, then we must use rip-relative addressing.
13158     if ((M != CodeModel::Small || R != Reloc::Static) &&
13159         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13160       return false;
13161   }
13162
13163   switch (AM.Scale) {
13164   case 0:
13165   case 1:
13166   case 2:
13167   case 4:
13168   case 8:
13169     // These scales always work.
13170     break;
13171   case 3:
13172   case 5:
13173   case 9:
13174     // These scales are formed with basereg+scalereg.  Only accept if there is
13175     // no basereg yet.
13176     if (AM.HasBaseReg)
13177       return false;
13178     break;
13179   default:  // Other stuff never works.
13180     return false;
13181   }
13182
13183   return true;
13184 }
13185
13186 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13187   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13188     return false;
13189   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13190   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13191   return NumBits1 > NumBits2;
13192 }
13193
13194 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13195   return isInt<32>(Imm);
13196 }
13197
13198 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13199   // Can also use sub to handle negated immediates.
13200   return isInt<32>(Imm);
13201 }
13202
13203 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13204   if (!VT1.isInteger() || !VT2.isInteger())
13205     return false;
13206   unsigned NumBits1 = VT1.getSizeInBits();
13207   unsigned NumBits2 = VT2.getSizeInBits();
13208   return NumBits1 > NumBits2;
13209 }
13210
13211 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13212   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13213   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13214 }
13215
13216 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13217   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13218   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13219 }
13220
13221 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13222   EVT VT1 = Val.getValueType();
13223   if (isZExtFree(VT1, VT2))
13224     return true;
13225
13226   if (Val.getOpcode() != ISD::LOAD)
13227     return false;
13228
13229   if (!VT1.isSimple() || !VT1.isInteger() ||
13230       !VT2.isSimple() || !VT2.isInteger())
13231     return false;
13232
13233   switch (VT1.getSimpleVT().SimpleTy) {
13234   default: break;
13235   case MVT::i8:
13236   case MVT::i16:
13237   case MVT::i32:
13238     // X86 has 8, 16, and 32-bit zero-extending loads.
13239     return true;
13240   }
13241
13242   return false;
13243 }
13244
13245 bool
13246 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13247   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13248     return false;
13249
13250   VT = VT.getScalarType();
13251
13252   if (!VT.isSimple())
13253     return false;
13254
13255   switch (VT.getSimpleVT().SimpleTy) {
13256   case MVT::f32:
13257   case MVT::f64:
13258     return true;
13259   default:
13260     break;
13261   }
13262
13263   return false;
13264 }
13265
13266 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13267   // i16 instructions are longer (0x66 prefix) and potentially slower.
13268   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13269 }
13270
13271 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13272 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13273 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13274 /// are assumed to be legal.
13275 bool
13276 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13277                                       EVT VT) const {
13278   // Very little shuffling can be done for 64-bit vectors right now.
13279   if (VT.getSizeInBits() == 64)
13280     return false;
13281
13282   // FIXME: pshufb, blends, shifts.
13283   return (VT.getVectorNumElements() == 2 ||
13284           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13285           isMOVLMask(M, VT) ||
13286           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13287           isPSHUFDMask(M, VT) ||
13288           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13289           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13290           isPALIGNRMask(M, VT, Subtarget) ||
13291           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13292           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13293           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13294           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13295 }
13296
13297 bool
13298 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13299                                           EVT VT) const {
13300   unsigned NumElts = VT.getVectorNumElements();
13301   // FIXME: This collection of masks seems suspect.
13302   if (NumElts == 2)
13303     return true;
13304   if (NumElts == 4 && VT.is128BitVector()) {
13305     return (isMOVLMask(Mask, VT)  ||
13306             isCommutedMOVLMask(Mask, VT, true) ||
13307             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13308             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13309   }
13310   return false;
13311 }
13312
13313 //===----------------------------------------------------------------------===//
13314 //                           X86 Scheduler Hooks
13315 //===----------------------------------------------------------------------===//
13316
13317 /// Utility function to emit xbegin specifying the start of an RTM region.
13318 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13319                                      const TargetInstrInfo *TII) {
13320   DebugLoc DL = MI->getDebugLoc();
13321
13322   const BasicBlock *BB = MBB->getBasicBlock();
13323   MachineFunction::iterator I = MBB;
13324   ++I;
13325
13326   // For the v = xbegin(), we generate
13327   //
13328   // thisMBB:
13329   //  xbegin sinkMBB
13330   //
13331   // mainMBB:
13332   //  eax = -1
13333   //
13334   // sinkMBB:
13335   //  v = eax
13336
13337   MachineBasicBlock *thisMBB = MBB;
13338   MachineFunction *MF = MBB->getParent();
13339   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13340   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13341   MF->insert(I, mainMBB);
13342   MF->insert(I, sinkMBB);
13343
13344   // Transfer the remainder of BB and its successor edges to sinkMBB.
13345   sinkMBB->splice(sinkMBB->begin(), MBB,
13346                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13347   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13348
13349   // thisMBB:
13350   //  xbegin sinkMBB
13351   //  # fallthrough to mainMBB
13352   //  # abortion to sinkMBB
13353   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13354   thisMBB->addSuccessor(mainMBB);
13355   thisMBB->addSuccessor(sinkMBB);
13356
13357   // mainMBB:
13358   //  EAX = -1
13359   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13360   mainMBB->addSuccessor(sinkMBB);
13361
13362   // sinkMBB:
13363   // EAX is live into the sinkMBB
13364   sinkMBB->addLiveIn(X86::EAX);
13365   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13366           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13367     .addReg(X86::EAX);
13368
13369   MI->eraseFromParent();
13370   return sinkMBB;
13371 }
13372
13373 // Get CMPXCHG opcode for the specified data type.
13374 static unsigned getCmpXChgOpcode(EVT VT) {
13375   switch (VT.getSimpleVT().SimpleTy) {
13376   case MVT::i8:  return X86::LCMPXCHG8;
13377   case MVT::i16: return X86::LCMPXCHG16;
13378   case MVT::i32: return X86::LCMPXCHG32;
13379   case MVT::i64: return X86::LCMPXCHG64;
13380   default:
13381     break;
13382   }
13383   llvm_unreachable("Invalid operand size!");
13384 }
13385
13386 // Get LOAD opcode for the specified data type.
13387 static unsigned getLoadOpcode(EVT VT) {
13388   switch (VT.getSimpleVT().SimpleTy) {
13389   case MVT::i8:  return X86::MOV8rm;
13390   case MVT::i16: return X86::MOV16rm;
13391   case MVT::i32: return X86::MOV32rm;
13392   case MVT::i64: return X86::MOV64rm;
13393   default:
13394     break;
13395   }
13396   llvm_unreachable("Invalid operand size!");
13397 }
13398
13399 // Get opcode of the non-atomic one from the specified atomic instruction.
13400 static unsigned getNonAtomicOpcode(unsigned Opc) {
13401   switch (Opc) {
13402   case X86::ATOMAND8:  return X86::AND8rr;
13403   case X86::ATOMAND16: return X86::AND16rr;
13404   case X86::ATOMAND32: return X86::AND32rr;
13405   case X86::ATOMAND64: return X86::AND64rr;
13406   case X86::ATOMOR8:   return X86::OR8rr;
13407   case X86::ATOMOR16:  return X86::OR16rr;
13408   case X86::ATOMOR32:  return X86::OR32rr;
13409   case X86::ATOMOR64:  return X86::OR64rr;
13410   case X86::ATOMXOR8:  return X86::XOR8rr;
13411   case X86::ATOMXOR16: return X86::XOR16rr;
13412   case X86::ATOMXOR32: return X86::XOR32rr;
13413   case X86::ATOMXOR64: return X86::XOR64rr;
13414   }
13415   llvm_unreachable("Unhandled atomic-load-op opcode!");
13416 }
13417
13418 // Get opcode of the non-atomic one from the specified atomic instruction with
13419 // extra opcode.
13420 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13421                                                unsigned &ExtraOpc) {
13422   switch (Opc) {
13423   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13424   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13425   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13426   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13427   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13428   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13429   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13430   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13431   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13432   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13433   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13434   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13435   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13436   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13437   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13438   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13439   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13440   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13441   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13442   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13443   }
13444   llvm_unreachable("Unhandled atomic-load-op opcode!");
13445 }
13446
13447 // Get opcode of the non-atomic one from the specified atomic instruction for
13448 // 64-bit data type on 32-bit target.
13449 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13450   switch (Opc) {
13451   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13452   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13453   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13454   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13455   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13456   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13457   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13458   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13459   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13460   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13461   }
13462   llvm_unreachable("Unhandled atomic-load-op opcode!");
13463 }
13464
13465 // Get opcode of the non-atomic one from the specified atomic instruction for
13466 // 64-bit data type on 32-bit target with extra opcode.
13467 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13468                                                    unsigned &HiOpc,
13469                                                    unsigned &ExtraOpc) {
13470   switch (Opc) {
13471   case X86::ATOMNAND6432:
13472     ExtraOpc = X86::NOT32r;
13473     HiOpc = X86::AND32rr;
13474     return X86::AND32rr;
13475   }
13476   llvm_unreachable("Unhandled atomic-load-op opcode!");
13477 }
13478
13479 // Get pseudo CMOV opcode from the specified data type.
13480 static unsigned getPseudoCMOVOpc(EVT VT) {
13481   switch (VT.getSimpleVT().SimpleTy) {
13482   case MVT::i8:  return X86::CMOV_GR8;
13483   case MVT::i16: return X86::CMOV_GR16;
13484   case MVT::i32: return X86::CMOV_GR32;
13485   default:
13486     break;
13487   }
13488   llvm_unreachable("Unknown CMOV opcode!");
13489 }
13490
13491 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13492 // They will be translated into a spin-loop or compare-exchange loop from
13493 //
13494 //    ...
13495 //    dst = atomic-fetch-op MI.addr, MI.val
13496 //    ...
13497 //
13498 // to
13499 //
13500 //    ...
13501 //    t1 = LOAD MI.addr
13502 // loop:
13503 //    t4 = phi(t1, t3 / loop)
13504 //    t2 = OP MI.val, t4
13505 //    EAX = t4
13506 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13507 //    t3 = EAX
13508 //    JNE loop
13509 // sink:
13510 //    dst = t3
13511 //    ...
13512 MachineBasicBlock *
13513 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13514                                        MachineBasicBlock *MBB) const {
13515   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13516   DebugLoc DL = MI->getDebugLoc();
13517
13518   MachineFunction *MF = MBB->getParent();
13519   MachineRegisterInfo &MRI = MF->getRegInfo();
13520
13521   const BasicBlock *BB = MBB->getBasicBlock();
13522   MachineFunction::iterator I = MBB;
13523   ++I;
13524
13525   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13526          "Unexpected number of operands");
13527
13528   assert(MI->hasOneMemOperand() &&
13529          "Expected atomic-load-op to have one memoperand");
13530
13531   // Memory Reference
13532   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13533   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13534
13535   unsigned DstReg, SrcReg;
13536   unsigned MemOpndSlot;
13537
13538   unsigned CurOp = 0;
13539
13540   DstReg = MI->getOperand(CurOp++).getReg();
13541   MemOpndSlot = CurOp;
13542   CurOp += X86::AddrNumOperands;
13543   SrcReg = MI->getOperand(CurOp++).getReg();
13544
13545   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13546   MVT::SimpleValueType VT = *RC->vt_begin();
13547   unsigned t1 = MRI.createVirtualRegister(RC);
13548   unsigned t2 = MRI.createVirtualRegister(RC);
13549   unsigned t3 = MRI.createVirtualRegister(RC);
13550   unsigned t4 = MRI.createVirtualRegister(RC);
13551   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13552
13553   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13554   unsigned LOADOpc = getLoadOpcode(VT);
13555
13556   // For the atomic load-arith operator, we generate
13557   //
13558   //  thisMBB:
13559   //    t1 = LOAD [MI.addr]
13560   //  mainMBB:
13561   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13562   //    t1 = OP MI.val, EAX
13563   //    EAX = t4
13564   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13565   //    t3 = EAX
13566   //    JNE mainMBB
13567   //  sinkMBB:
13568   //    dst = t3
13569
13570   MachineBasicBlock *thisMBB = MBB;
13571   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13572   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13573   MF->insert(I, mainMBB);
13574   MF->insert(I, sinkMBB);
13575
13576   MachineInstrBuilder MIB;
13577
13578   // Transfer the remainder of BB and its successor edges to sinkMBB.
13579   sinkMBB->splice(sinkMBB->begin(), MBB,
13580                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13581   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13582
13583   // thisMBB:
13584   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13585   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13586     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13587     if (NewMO.isReg())
13588       NewMO.setIsKill(false);
13589     MIB.addOperand(NewMO);
13590   }
13591   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13592     unsigned flags = (*MMOI)->getFlags();
13593     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13594     MachineMemOperand *MMO =
13595       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13596                                (*MMOI)->getSize(),
13597                                (*MMOI)->getBaseAlignment(),
13598                                (*MMOI)->getTBAAInfo(),
13599                                (*MMOI)->getRanges());
13600     MIB.addMemOperand(MMO);
13601   }
13602
13603   thisMBB->addSuccessor(mainMBB);
13604
13605   // mainMBB:
13606   MachineBasicBlock *origMainMBB = mainMBB;
13607
13608   // Add a PHI.
13609   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13610                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13611
13612   unsigned Opc = MI->getOpcode();
13613   switch (Opc) {
13614   default:
13615     llvm_unreachable("Unhandled atomic-load-op opcode!");
13616   case X86::ATOMAND8:
13617   case X86::ATOMAND16:
13618   case X86::ATOMAND32:
13619   case X86::ATOMAND64:
13620   case X86::ATOMOR8:
13621   case X86::ATOMOR16:
13622   case X86::ATOMOR32:
13623   case X86::ATOMOR64:
13624   case X86::ATOMXOR8:
13625   case X86::ATOMXOR16:
13626   case X86::ATOMXOR32:
13627   case X86::ATOMXOR64: {
13628     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13629     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13630       .addReg(t4);
13631     break;
13632   }
13633   case X86::ATOMNAND8:
13634   case X86::ATOMNAND16:
13635   case X86::ATOMNAND32:
13636   case X86::ATOMNAND64: {
13637     unsigned Tmp = MRI.createVirtualRegister(RC);
13638     unsigned NOTOpc;
13639     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13640     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13641       .addReg(t4);
13642     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13643     break;
13644   }
13645   case X86::ATOMMAX8:
13646   case X86::ATOMMAX16:
13647   case X86::ATOMMAX32:
13648   case X86::ATOMMAX64:
13649   case X86::ATOMMIN8:
13650   case X86::ATOMMIN16:
13651   case X86::ATOMMIN32:
13652   case X86::ATOMMIN64:
13653   case X86::ATOMUMAX8:
13654   case X86::ATOMUMAX16:
13655   case X86::ATOMUMAX32:
13656   case X86::ATOMUMAX64:
13657   case X86::ATOMUMIN8:
13658   case X86::ATOMUMIN16:
13659   case X86::ATOMUMIN32:
13660   case X86::ATOMUMIN64: {
13661     unsigned CMPOpc;
13662     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13663
13664     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13665       .addReg(SrcReg)
13666       .addReg(t4);
13667
13668     if (Subtarget->hasCMov()) {
13669       if (VT != MVT::i8) {
13670         // Native support
13671         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13672           .addReg(SrcReg)
13673           .addReg(t4);
13674       } else {
13675         // Promote i8 to i32 to use CMOV32
13676         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13677         const TargetRegisterClass *RC32 =
13678           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13679         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13680         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13681         unsigned Tmp = MRI.createVirtualRegister(RC32);
13682
13683         unsigned Undef = MRI.createVirtualRegister(RC32);
13684         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13685
13686         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13687           .addReg(Undef)
13688           .addReg(SrcReg)
13689           .addImm(X86::sub_8bit);
13690         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13691           .addReg(Undef)
13692           .addReg(t4)
13693           .addImm(X86::sub_8bit);
13694
13695         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13696           .addReg(SrcReg32)
13697           .addReg(AccReg32);
13698
13699         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13700           .addReg(Tmp, 0, X86::sub_8bit);
13701       }
13702     } else {
13703       // Use pseudo select and lower them.
13704       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13705              "Invalid atomic-load-op transformation!");
13706       unsigned SelOpc = getPseudoCMOVOpc(VT);
13707       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13708       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13709       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13710               .addReg(SrcReg).addReg(t4)
13711               .addImm(CC);
13712       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13713       // Replace the original PHI node as mainMBB is changed after CMOV
13714       // lowering.
13715       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13716         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13717       Phi->eraseFromParent();
13718     }
13719     break;
13720   }
13721   }
13722
13723   // Copy PhyReg back from virtual register.
13724   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13725     .addReg(t4);
13726
13727   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13728   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13729     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13730     if (NewMO.isReg())
13731       NewMO.setIsKill(false);
13732     MIB.addOperand(NewMO);
13733   }
13734   MIB.addReg(t2);
13735   MIB.setMemRefs(MMOBegin, MMOEnd);
13736
13737   // Copy PhyReg back to virtual register.
13738   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13739     .addReg(PhyReg);
13740
13741   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13742
13743   mainMBB->addSuccessor(origMainMBB);
13744   mainMBB->addSuccessor(sinkMBB);
13745
13746   // sinkMBB:
13747   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13748           TII->get(TargetOpcode::COPY), DstReg)
13749     .addReg(t3);
13750
13751   MI->eraseFromParent();
13752   return sinkMBB;
13753 }
13754
13755 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13756 // instructions. They will be translated into a spin-loop or compare-exchange
13757 // loop from
13758 //
13759 //    ...
13760 //    dst = atomic-fetch-op MI.addr, MI.val
13761 //    ...
13762 //
13763 // to
13764 //
13765 //    ...
13766 //    t1L = LOAD [MI.addr + 0]
13767 //    t1H = LOAD [MI.addr + 4]
13768 // loop:
13769 //    t4L = phi(t1L, t3L / loop)
13770 //    t4H = phi(t1H, t3H / loop)
13771 //    t2L = OP MI.val.lo, t4L
13772 //    t2H = OP MI.val.hi, t4H
13773 //    EAX = t4L
13774 //    EDX = t4H
13775 //    EBX = t2L
13776 //    ECX = t2H
13777 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13778 //    t3L = EAX
13779 //    t3H = EDX
13780 //    JNE loop
13781 // sink:
13782 //    dstL = t3L
13783 //    dstH = t3H
13784 //    ...
13785 MachineBasicBlock *
13786 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13787                                            MachineBasicBlock *MBB) const {
13788   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13789   DebugLoc DL = MI->getDebugLoc();
13790
13791   MachineFunction *MF = MBB->getParent();
13792   MachineRegisterInfo &MRI = MF->getRegInfo();
13793
13794   const BasicBlock *BB = MBB->getBasicBlock();
13795   MachineFunction::iterator I = MBB;
13796   ++I;
13797
13798   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13799          "Unexpected number of operands");
13800
13801   assert(MI->hasOneMemOperand() &&
13802          "Expected atomic-load-op32 to have one memoperand");
13803
13804   // Memory Reference
13805   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13806   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13807
13808   unsigned DstLoReg, DstHiReg;
13809   unsigned SrcLoReg, SrcHiReg;
13810   unsigned MemOpndSlot;
13811
13812   unsigned CurOp = 0;
13813
13814   DstLoReg = MI->getOperand(CurOp++).getReg();
13815   DstHiReg = MI->getOperand(CurOp++).getReg();
13816   MemOpndSlot = CurOp;
13817   CurOp += X86::AddrNumOperands;
13818   SrcLoReg = MI->getOperand(CurOp++).getReg();
13819   SrcHiReg = MI->getOperand(CurOp++).getReg();
13820
13821   const TargetRegisterClass *RC = &X86::GR32RegClass;
13822   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13823
13824   unsigned t1L = MRI.createVirtualRegister(RC);
13825   unsigned t1H = MRI.createVirtualRegister(RC);
13826   unsigned t2L = MRI.createVirtualRegister(RC);
13827   unsigned t2H = MRI.createVirtualRegister(RC);
13828   unsigned t3L = MRI.createVirtualRegister(RC);
13829   unsigned t3H = MRI.createVirtualRegister(RC);
13830   unsigned t4L = MRI.createVirtualRegister(RC);
13831   unsigned t4H = MRI.createVirtualRegister(RC);
13832
13833   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13834   unsigned LOADOpc = X86::MOV32rm;
13835
13836   // For the atomic load-arith operator, we generate
13837   //
13838   //  thisMBB:
13839   //    t1L = LOAD [MI.addr + 0]
13840   //    t1H = LOAD [MI.addr + 4]
13841   //  mainMBB:
13842   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13843   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13844   //    t2L = OP MI.val.lo, t4L
13845   //    t2H = OP MI.val.hi, t4H
13846   //    EBX = t2L
13847   //    ECX = t2H
13848   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13849   //    t3L = EAX
13850   //    t3H = EDX
13851   //    JNE loop
13852   //  sinkMBB:
13853   //    dstL = t3L
13854   //    dstH = t3H
13855
13856   MachineBasicBlock *thisMBB = MBB;
13857   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13858   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13859   MF->insert(I, mainMBB);
13860   MF->insert(I, sinkMBB);
13861
13862   MachineInstrBuilder MIB;
13863
13864   // Transfer the remainder of BB and its successor edges to sinkMBB.
13865   sinkMBB->splice(sinkMBB->begin(), MBB,
13866                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13867   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13868
13869   // thisMBB:
13870   // Lo
13871   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13872   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13873     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13874     if (NewMO.isReg())
13875       NewMO.setIsKill(false);
13876     MIB.addOperand(NewMO);
13877   }
13878   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13879     unsigned flags = (*MMOI)->getFlags();
13880     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13881     MachineMemOperand *MMO =
13882       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13883                                (*MMOI)->getSize(),
13884                                (*MMOI)->getBaseAlignment(),
13885                                (*MMOI)->getTBAAInfo(),
13886                                (*MMOI)->getRanges());
13887     MIB.addMemOperand(MMO);
13888   };
13889   MachineInstr *LowMI = MIB;
13890
13891   // Hi
13892   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13893   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13894     if (i == X86::AddrDisp) {
13895       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13896     } else {
13897       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13898       if (NewMO.isReg())
13899         NewMO.setIsKill(false);
13900       MIB.addOperand(NewMO);
13901     }
13902   }
13903   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13904
13905   thisMBB->addSuccessor(mainMBB);
13906
13907   // mainMBB:
13908   MachineBasicBlock *origMainMBB = mainMBB;
13909
13910   // Add PHIs.
13911   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13912                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13913   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13914                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13915
13916   unsigned Opc = MI->getOpcode();
13917   switch (Opc) {
13918   default:
13919     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13920   case X86::ATOMAND6432:
13921   case X86::ATOMOR6432:
13922   case X86::ATOMXOR6432:
13923   case X86::ATOMADD6432:
13924   case X86::ATOMSUB6432: {
13925     unsigned HiOpc;
13926     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13927     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13928       .addReg(SrcLoReg);
13929     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13930       .addReg(SrcHiReg);
13931     break;
13932   }
13933   case X86::ATOMNAND6432: {
13934     unsigned HiOpc, NOTOpc;
13935     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13936     unsigned TmpL = MRI.createVirtualRegister(RC);
13937     unsigned TmpH = MRI.createVirtualRegister(RC);
13938     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13939       .addReg(t4L);
13940     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13941       .addReg(t4H);
13942     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13943     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13944     break;
13945   }
13946   case X86::ATOMMAX6432:
13947   case X86::ATOMMIN6432:
13948   case X86::ATOMUMAX6432:
13949   case X86::ATOMUMIN6432: {
13950     unsigned HiOpc;
13951     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13952     unsigned cL = MRI.createVirtualRegister(RC8);
13953     unsigned cH = MRI.createVirtualRegister(RC8);
13954     unsigned cL32 = MRI.createVirtualRegister(RC);
13955     unsigned cH32 = MRI.createVirtualRegister(RC);
13956     unsigned cc = MRI.createVirtualRegister(RC);
13957     // cl := cmp src_lo, lo
13958     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13959       .addReg(SrcLoReg).addReg(t4L);
13960     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13961     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13962     // ch := cmp src_hi, hi
13963     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13964       .addReg(SrcHiReg).addReg(t4H);
13965     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13966     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13967     // cc := if (src_hi == hi) ? cl : ch;
13968     if (Subtarget->hasCMov()) {
13969       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13970         .addReg(cH32).addReg(cL32);
13971     } else {
13972       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13973               .addReg(cH32).addReg(cL32)
13974               .addImm(X86::COND_E);
13975       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13976     }
13977     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13978     if (Subtarget->hasCMov()) {
13979       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13980         .addReg(SrcLoReg).addReg(t4L);
13981       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13982         .addReg(SrcHiReg).addReg(t4H);
13983     } else {
13984       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13985               .addReg(SrcLoReg).addReg(t4L)
13986               .addImm(X86::COND_NE);
13987       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13988       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13989       // 2nd CMOV lowering.
13990       mainMBB->addLiveIn(X86::EFLAGS);
13991       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13992               .addReg(SrcHiReg).addReg(t4H)
13993               .addImm(X86::COND_NE);
13994       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13995       // Replace the original PHI node as mainMBB is changed after CMOV
13996       // lowering.
13997       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13998         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13999       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14000         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14001       PhiL->eraseFromParent();
14002       PhiH->eraseFromParent();
14003     }
14004     break;
14005   }
14006   case X86::ATOMSWAP6432: {
14007     unsigned HiOpc;
14008     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14009     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14010     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14011     break;
14012   }
14013   }
14014
14015   // Copy EDX:EAX back from HiReg:LoReg
14016   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14017   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14018   // Copy ECX:EBX from t1H:t1L
14019   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14020   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14021
14022   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14023   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14024     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14025     if (NewMO.isReg())
14026       NewMO.setIsKill(false);
14027     MIB.addOperand(NewMO);
14028   }
14029   MIB.setMemRefs(MMOBegin, MMOEnd);
14030
14031   // Copy EDX:EAX back to t3H:t3L
14032   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14033   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14034
14035   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14036
14037   mainMBB->addSuccessor(origMainMBB);
14038   mainMBB->addSuccessor(sinkMBB);
14039
14040   // sinkMBB:
14041   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14042           TII->get(TargetOpcode::COPY), DstLoReg)
14043     .addReg(t3L);
14044   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14045           TII->get(TargetOpcode::COPY), DstHiReg)
14046     .addReg(t3H);
14047
14048   MI->eraseFromParent();
14049   return sinkMBB;
14050 }
14051
14052 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14053 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14054 // in the .td file.
14055 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14056                                        const TargetInstrInfo *TII) {
14057   unsigned Opc;
14058   switch (MI->getOpcode()) {
14059   default: llvm_unreachable("illegal opcode!");
14060   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14061   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14062   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14063   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14064   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14065   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14066   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14067   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14068   }
14069
14070   DebugLoc dl = MI->getDebugLoc();
14071   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14072
14073   unsigned NumArgs = MI->getNumOperands();
14074   for (unsigned i = 1; i < NumArgs; ++i) {
14075     MachineOperand &Op = MI->getOperand(i);
14076     if (!(Op.isReg() && Op.isImplicit()))
14077       MIB.addOperand(Op);
14078   }
14079   if (MI->hasOneMemOperand())
14080     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14081
14082   BuildMI(*BB, MI, dl,
14083     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14084     .addReg(X86::XMM0);
14085
14086   MI->eraseFromParent();
14087   return BB;
14088 }
14089
14090 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14091 // defs in an instruction pattern
14092 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14093                                        const TargetInstrInfo *TII) {
14094   unsigned Opc;
14095   switch (MI->getOpcode()) {
14096   default: llvm_unreachable("illegal opcode!");
14097   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14098   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14099   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14100   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14101   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14102   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14103   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14104   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14105   }
14106
14107   DebugLoc dl = MI->getDebugLoc();
14108   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14109
14110   unsigned NumArgs = MI->getNumOperands(); // remove the results
14111   for (unsigned i = 1; i < NumArgs; ++i) {
14112     MachineOperand &Op = MI->getOperand(i);
14113     if (!(Op.isReg() && Op.isImplicit()))
14114       MIB.addOperand(Op);
14115   }
14116   if (MI->hasOneMemOperand())
14117     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14118
14119   BuildMI(*BB, MI, dl,
14120     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14121     .addReg(X86::ECX);
14122
14123   MI->eraseFromParent();
14124   return BB;
14125 }
14126
14127 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14128                                        const TargetInstrInfo *TII,
14129                                        const X86Subtarget* Subtarget) {
14130   DebugLoc dl = MI->getDebugLoc();
14131
14132   // Address into RAX/EAX, other two args into ECX, EDX.
14133   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14134   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14135   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14136   for (int i = 0; i < X86::AddrNumOperands; ++i)
14137     MIB.addOperand(MI->getOperand(i));
14138
14139   unsigned ValOps = X86::AddrNumOperands;
14140   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14141     .addReg(MI->getOperand(ValOps).getReg());
14142   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14143     .addReg(MI->getOperand(ValOps+1).getReg());
14144
14145   // The instruction doesn't actually take any operands though.
14146   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14147
14148   MI->eraseFromParent(); // The pseudo is gone now.
14149   return BB;
14150 }
14151
14152 MachineBasicBlock *
14153 X86TargetLowering::EmitVAARG64WithCustomInserter(
14154                    MachineInstr *MI,
14155                    MachineBasicBlock *MBB) const {
14156   // Emit va_arg instruction on X86-64.
14157
14158   // Operands to this pseudo-instruction:
14159   // 0  ) Output        : destination address (reg)
14160   // 1-5) Input         : va_list address (addr, i64mem)
14161   // 6  ) ArgSize       : Size (in bytes) of vararg type
14162   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14163   // 8  ) Align         : Alignment of type
14164   // 9  ) EFLAGS (implicit-def)
14165
14166   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14167   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14168
14169   unsigned DestReg = MI->getOperand(0).getReg();
14170   MachineOperand &Base = MI->getOperand(1);
14171   MachineOperand &Scale = MI->getOperand(2);
14172   MachineOperand &Index = MI->getOperand(3);
14173   MachineOperand &Disp = MI->getOperand(4);
14174   MachineOperand &Segment = MI->getOperand(5);
14175   unsigned ArgSize = MI->getOperand(6).getImm();
14176   unsigned ArgMode = MI->getOperand(7).getImm();
14177   unsigned Align = MI->getOperand(8).getImm();
14178
14179   // Memory Reference
14180   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14181   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14182   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14183
14184   // Machine Information
14185   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14186   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14187   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14188   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14189   DebugLoc DL = MI->getDebugLoc();
14190
14191   // struct va_list {
14192   //   i32   gp_offset
14193   //   i32   fp_offset
14194   //   i64   overflow_area (address)
14195   //   i64   reg_save_area (address)
14196   // }
14197   // sizeof(va_list) = 24
14198   // alignment(va_list) = 8
14199
14200   unsigned TotalNumIntRegs = 6;
14201   unsigned TotalNumXMMRegs = 8;
14202   bool UseGPOffset = (ArgMode == 1);
14203   bool UseFPOffset = (ArgMode == 2);
14204   unsigned MaxOffset = TotalNumIntRegs * 8 +
14205                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14206
14207   /* Align ArgSize to a multiple of 8 */
14208   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14209   bool NeedsAlign = (Align > 8);
14210
14211   MachineBasicBlock *thisMBB = MBB;
14212   MachineBasicBlock *overflowMBB;
14213   MachineBasicBlock *offsetMBB;
14214   MachineBasicBlock *endMBB;
14215
14216   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14217   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14218   unsigned OffsetReg = 0;
14219
14220   if (!UseGPOffset && !UseFPOffset) {
14221     // If we only pull from the overflow region, we don't create a branch.
14222     // We don't need to alter control flow.
14223     OffsetDestReg = 0; // unused
14224     OverflowDestReg = DestReg;
14225
14226     offsetMBB = NULL;
14227     overflowMBB = thisMBB;
14228     endMBB = thisMBB;
14229   } else {
14230     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14231     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14232     // If not, pull from overflow_area. (branch to overflowMBB)
14233     //
14234     //       thisMBB
14235     //         |     .
14236     //         |        .
14237     //     offsetMBB   overflowMBB
14238     //         |        .
14239     //         |     .
14240     //        endMBB
14241
14242     // Registers for the PHI in endMBB
14243     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14244     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14245
14246     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14247     MachineFunction *MF = MBB->getParent();
14248     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14249     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14250     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14251
14252     MachineFunction::iterator MBBIter = MBB;
14253     ++MBBIter;
14254
14255     // Insert the new basic blocks
14256     MF->insert(MBBIter, offsetMBB);
14257     MF->insert(MBBIter, overflowMBB);
14258     MF->insert(MBBIter, endMBB);
14259
14260     // Transfer the remainder of MBB and its successor edges to endMBB.
14261     endMBB->splice(endMBB->begin(), thisMBB,
14262                     llvm::next(MachineBasicBlock::iterator(MI)),
14263                     thisMBB->end());
14264     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14265
14266     // Make offsetMBB and overflowMBB successors of thisMBB
14267     thisMBB->addSuccessor(offsetMBB);
14268     thisMBB->addSuccessor(overflowMBB);
14269
14270     // endMBB is a successor of both offsetMBB and overflowMBB
14271     offsetMBB->addSuccessor(endMBB);
14272     overflowMBB->addSuccessor(endMBB);
14273
14274     // Load the offset value into a register
14275     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14276     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14277       .addOperand(Base)
14278       .addOperand(Scale)
14279       .addOperand(Index)
14280       .addDisp(Disp, UseFPOffset ? 4 : 0)
14281       .addOperand(Segment)
14282       .setMemRefs(MMOBegin, MMOEnd);
14283
14284     // Check if there is enough room left to pull this argument.
14285     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14286       .addReg(OffsetReg)
14287       .addImm(MaxOffset + 8 - ArgSizeA8);
14288
14289     // Branch to "overflowMBB" if offset >= max
14290     // Fall through to "offsetMBB" otherwise
14291     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14292       .addMBB(overflowMBB);
14293   }
14294
14295   // In offsetMBB, emit code to use the reg_save_area.
14296   if (offsetMBB) {
14297     assert(OffsetReg != 0);
14298
14299     // Read the reg_save_area address.
14300     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14301     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14302       .addOperand(Base)
14303       .addOperand(Scale)
14304       .addOperand(Index)
14305       .addDisp(Disp, 16)
14306       .addOperand(Segment)
14307       .setMemRefs(MMOBegin, MMOEnd);
14308
14309     // Zero-extend the offset
14310     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14311       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14312         .addImm(0)
14313         .addReg(OffsetReg)
14314         .addImm(X86::sub_32bit);
14315
14316     // Add the offset to the reg_save_area to get the final address.
14317     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14318       .addReg(OffsetReg64)
14319       .addReg(RegSaveReg);
14320
14321     // Compute the offset for the next argument
14322     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14323     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14324       .addReg(OffsetReg)
14325       .addImm(UseFPOffset ? 16 : 8);
14326
14327     // Store it back into the va_list.
14328     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14329       .addOperand(Base)
14330       .addOperand(Scale)
14331       .addOperand(Index)
14332       .addDisp(Disp, UseFPOffset ? 4 : 0)
14333       .addOperand(Segment)
14334       .addReg(NextOffsetReg)
14335       .setMemRefs(MMOBegin, MMOEnd);
14336
14337     // Jump to endMBB
14338     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14339       .addMBB(endMBB);
14340   }
14341
14342   //
14343   // Emit code to use overflow area
14344   //
14345
14346   // Load the overflow_area address into a register.
14347   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14348   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14349     .addOperand(Base)
14350     .addOperand(Scale)
14351     .addOperand(Index)
14352     .addDisp(Disp, 8)
14353     .addOperand(Segment)
14354     .setMemRefs(MMOBegin, MMOEnd);
14355
14356   // If we need to align it, do so. Otherwise, just copy the address
14357   // to OverflowDestReg.
14358   if (NeedsAlign) {
14359     // Align the overflow address
14360     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14361     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14362
14363     // aligned_addr = (addr + (align-1)) & ~(align-1)
14364     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14365       .addReg(OverflowAddrReg)
14366       .addImm(Align-1);
14367
14368     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14369       .addReg(TmpReg)
14370       .addImm(~(uint64_t)(Align-1));
14371   } else {
14372     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14373       .addReg(OverflowAddrReg);
14374   }
14375
14376   // Compute the next overflow address after this argument.
14377   // (the overflow address should be kept 8-byte aligned)
14378   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14379   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14380     .addReg(OverflowDestReg)
14381     .addImm(ArgSizeA8);
14382
14383   // Store the new overflow address.
14384   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14385     .addOperand(Base)
14386     .addOperand(Scale)
14387     .addOperand(Index)
14388     .addDisp(Disp, 8)
14389     .addOperand(Segment)
14390     .addReg(NextAddrReg)
14391     .setMemRefs(MMOBegin, MMOEnd);
14392
14393   // If we branched, emit the PHI to the front of endMBB.
14394   if (offsetMBB) {
14395     BuildMI(*endMBB, endMBB->begin(), DL,
14396             TII->get(X86::PHI), DestReg)
14397       .addReg(OffsetDestReg).addMBB(offsetMBB)
14398       .addReg(OverflowDestReg).addMBB(overflowMBB);
14399   }
14400
14401   // Erase the pseudo instruction
14402   MI->eraseFromParent();
14403
14404   return endMBB;
14405 }
14406
14407 MachineBasicBlock *
14408 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14409                                                  MachineInstr *MI,
14410                                                  MachineBasicBlock *MBB) const {
14411   // Emit code to save XMM registers to the stack. The ABI says that the
14412   // number of registers to save is given in %al, so it's theoretically
14413   // possible to do an indirect jump trick to avoid saving all of them,
14414   // however this code takes a simpler approach and just executes all
14415   // of the stores if %al is non-zero. It's less code, and it's probably
14416   // easier on the hardware branch predictor, and stores aren't all that
14417   // expensive anyway.
14418
14419   // Create the new basic blocks. One block contains all the XMM stores,
14420   // and one block is the final destination regardless of whether any
14421   // stores were performed.
14422   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14423   MachineFunction *F = MBB->getParent();
14424   MachineFunction::iterator MBBIter = MBB;
14425   ++MBBIter;
14426   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14427   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14428   F->insert(MBBIter, XMMSaveMBB);
14429   F->insert(MBBIter, EndMBB);
14430
14431   // Transfer the remainder of MBB and its successor edges to EndMBB.
14432   EndMBB->splice(EndMBB->begin(), MBB,
14433                  llvm::next(MachineBasicBlock::iterator(MI)),
14434                  MBB->end());
14435   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14436
14437   // The original block will now fall through to the XMM save block.
14438   MBB->addSuccessor(XMMSaveMBB);
14439   // The XMMSaveMBB will fall through to the end block.
14440   XMMSaveMBB->addSuccessor(EndMBB);
14441
14442   // Now add the instructions.
14443   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14444   DebugLoc DL = MI->getDebugLoc();
14445
14446   unsigned CountReg = MI->getOperand(0).getReg();
14447   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14448   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14449
14450   if (!Subtarget->isTargetWin64()) {
14451     // If %al is 0, branch around the XMM save block.
14452     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14453     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14454     MBB->addSuccessor(EndMBB);
14455   }
14456
14457   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14458   // In the XMM save block, save all the XMM argument registers.
14459   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14460     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14461     MachineMemOperand *MMO =
14462       F->getMachineMemOperand(
14463           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14464         MachineMemOperand::MOStore,
14465         /*Size=*/16, /*Align=*/16);
14466     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14467       .addFrameIndex(RegSaveFrameIndex)
14468       .addImm(/*Scale=*/1)
14469       .addReg(/*IndexReg=*/0)
14470       .addImm(/*Disp=*/Offset)
14471       .addReg(/*Segment=*/0)
14472       .addReg(MI->getOperand(i).getReg())
14473       .addMemOperand(MMO);
14474   }
14475
14476   MI->eraseFromParent();   // The pseudo instruction is gone now.
14477
14478   return EndMBB;
14479 }
14480
14481 // The EFLAGS operand of SelectItr might be missing a kill marker
14482 // because there were multiple uses of EFLAGS, and ISel didn't know
14483 // which to mark. Figure out whether SelectItr should have had a
14484 // kill marker, and set it if it should. Returns the correct kill
14485 // marker value.
14486 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14487                                      MachineBasicBlock* BB,
14488                                      const TargetRegisterInfo* TRI) {
14489   // Scan forward through BB for a use/def of EFLAGS.
14490   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14491   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14492     const MachineInstr& mi = *miI;
14493     if (mi.readsRegister(X86::EFLAGS))
14494       return false;
14495     if (mi.definesRegister(X86::EFLAGS))
14496       break; // Should have kill-flag - update below.
14497   }
14498
14499   // If we hit the end of the block, check whether EFLAGS is live into a
14500   // successor.
14501   if (miI == BB->end()) {
14502     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14503                                           sEnd = BB->succ_end();
14504          sItr != sEnd; ++sItr) {
14505       MachineBasicBlock* succ = *sItr;
14506       if (succ->isLiveIn(X86::EFLAGS))
14507         return false;
14508     }
14509   }
14510
14511   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14512   // out. SelectMI should have a kill flag on EFLAGS.
14513   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14514   return true;
14515 }
14516
14517 MachineBasicBlock *
14518 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14519                                      MachineBasicBlock *BB) const {
14520   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14521   DebugLoc DL = MI->getDebugLoc();
14522
14523   // To "insert" a SELECT_CC instruction, we actually have to insert the
14524   // diamond control-flow pattern.  The incoming instruction knows the
14525   // destination vreg to set, the condition code register to branch on, the
14526   // true/false values to select between, and a branch opcode to use.
14527   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14528   MachineFunction::iterator It = BB;
14529   ++It;
14530
14531   //  thisMBB:
14532   //  ...
14533   //   TrueVal = ...
14534   //   cmpTY ccX, r1, r2
14535   //   bCC copy1MBB
14536   //   fallthrough --> copy0MBB
14537   MachineBasicBlock *thisMBB = BB;
14538   MachineFunction *F = BB->getParent();
14539   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14540   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14541   F->insert(It, copy0MBB);
14542   F->insert(It, sinkMBB);
14543
14544   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14545   // live into the sink and copy blocks.
14546   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14547   if (!MI->killsRegister(X86::EFLAGS) &&
14548       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14549     copy0MBB->addLiveIn(X86::EFLAGS);
14550     sinkMBB->addLiveIn(X86::EFLAGS);
14551   }
14552
14553   // Transfer the remainder of BB and its successor edges to sinkMBB.
14554   sinkMBB->splice(sinkMBB->begin(), BB,
14555                   llvm::next(MachineBasicBlock::iterator(MI)),
14556                   BB->end());
14557   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14558
14559   // Add the true and fallthrough blocks as its successors.
14560   BB->addSuccessor(copy0MBB);
14561   BB->addSuccessor(sinkMBB);
14562
14563   // Create the conditional branch instruction.
14564   unsigned Opc =
14565     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14566   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14567
14568   //  copy0MBB:
14569   //   %FalseValue = ...
14570   //   # fallthrough to sinkMBB
14571   copy0MBB->addSuccessor(sinkMBB);
14572
14573   //  sinkMBB:
14574   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14575   //  ...
14576   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14577           TII->get(X86::PHI), MI->getOperand(0).getReg())
14578     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14579     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14580
14581   MI->eraseFromParent();   // The pseudo instruction is gone now.
14582   return sinkMBB;
14583 }
14584
14585 MachineBasicBlock *
14586 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14587                                         bool Is64Bit) const {
14588   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14589   DebugLoc DL = MI->getDebugLoc();
14590   MachineFunction *MF = BB->getParent();
14591   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14592
14593   assert(getTargetMachine().Options.EnableSegmentedStacks);
14594
14595   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14596   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14597
14598   // BB:
14599   //  ... [Till the alloca]
14600   // If stacklet is not large enough, jump to mallocMBB
14601   //
14602   // bumpMBB:
14603   //  Allocate by subtracting from RSP
14604   //  Jump to continueMBB
14605   //
14606   // mallocMBB:
14607   //  Allocate by call to runtime
14608   //
14609   // continueMBB:
14610   //  ...
14611   //  [rest of original BB]
14612   //
14613
14614   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14615   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14616   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14617
14618   MachineRegisterInfo &MRI = MF->getRegInfo();
14619   const TargetRegisterClass *AddrRegClass =
14620     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14621
14622   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14623     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14624     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14625     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14626     sizeVReg = MI->getOperand(1).getReg(),
14627     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14628
14629   MachineFunction::iterator MBBIter = BB;
14630   ++MBBIter;
14631
14632   MF->insert(MBBIter, bumpMBB);
14633   MF->insert(MBBIter, mallocMBB);
14634   MF->insert(MBBIter, continueMBB);
14635
14636   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14637                       (MachineBasicBlock::iterator(MI)), BB->end());
14638   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14639
14640   // Add code to the main basic block to check if the stack limit has been hit,
14641   // and if so, jump to mallocMBB otherwise to bumpMBB.
14642   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14643   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14644     .addReg(tmpSPVReg).addReg(sizeVReg);
14645   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14646     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14647     .addReg(SPLimitVReg);
14648   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14649
14650   // bumpMBB simply decreases the stack pointer, since we know the current
14651   // stacklet has enough space.
14652   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14653     .addReg(SPLimitVReg);
14654   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14655     .addReg(SPLimitVReg);
14656   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14657
14658   // Calls into a routine in libgcc to allocate more space from the heap.
14659   const uint32_t *RegMask =
14660     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14661   if (Is64Bit) {
14662     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14663       .addReg(sizeVReg);
14664     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14665       .addExternalSymbol("__morestack_allocate_stack_space")
14666       .addRegMask(RegMask)
14667       .addReg(X86::RDI, RegState::Implicit)
14668       .addReg(X86::RAX, RegState::ImplicitDefine);
14669   } else {
14670     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14671       .addImm(12);
14672     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14673     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14674       .addExternalSymbol("__morestack_allocate_stack_space")
14675       .addRegMask(RegMask)
14676       .addReg(X86::EAX, RegState::ImplicitDefine);
14677   }
14678
14679   if (!Is64Bit)
14680     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14681       .addImm(16);
14682
14683   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14684     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14685   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14686
14687   // Set up the CFG correctly.
14688   BB->addSuccessor(bumpMBB);
14689   BB->addSuccessor(mallocMBB);
14690   mallocMBB->addSuccessor(continueMBB);
14691   bumpMBB->addSuccessor(continueMBB);
14692
14693   // Take care of the PHI nodes.
14694   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14695           MI->getOperand(0).getReg())
14696     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14697     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14698
14699   // Delete the original pseudo instruction.
14700   MI->eraseFromParent();
14701
14702   // And we're done.
14703   return continueMBB;
14704 }
14705
14706 MachineBasicBlock *
14707 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14708                                           MachineBasicBlock *BB) const {
14709   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14710   DebugLoc DL = MI->getDebugLoc();
14711
14712   assert(!Subtarget->isTargetEnvMacho());
14713
14714   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14715   // non-trivial part is impdef of ESP.
14716
14717   if (Subtarget->isTargetWin64()) {
14718     if (Subtarget->isTargetCygMing()) {
14719       // ___chkstk(Mingw64):
14720       // Clobbers R10, R11, RAX and EFLAGS.
14721       // Updates RSP.
14722       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14723         .addExternalSymbol("___chkstk")
14724         .addReg(X86::RAX, RegState::Implicit)
14725         .addReg(X86::RSP, RegState::Implicit)
14726         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14727         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14728         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14729     } else {
14730       // __chkstk(MSVCRT): does not update stack pointer.
14731       // Clobbers R10, R11 and EFLAGS.
14732       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14733         .addExternalSymbol("__chkstk")
14734         .addReg(X86::RAX, RegState::Implicit)
14735         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14736       // RAX has the offset to be subtracted from RSP.
14737       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14738         .addReg(X86::RSP)
14739         .addReg(X86::RAX);
14740     }
14741   } else {
14742     const char *StackProbeSymbol =
14743       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14744
14745     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14746       .addExternalSymbol(StackProbeSymbol)
14747       .addReg(X86::EAX, RegState::Implicit)
14748       .addReg(X86::ESP, RegState::Implicit)
14749       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14750       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14751       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14752   }
14753
14754   MI->eraseFromParent();   // The pseudo instruction is gone now.
14755   return BB;
14756 }
14757
14758 MachineBasicBlock *
14759 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14760                                       MachineBasicBlock *BB) const {
14761   // This is pretty easy.  We're taking the value that we received from
14762   // our load from the relocation, sticking it in either RDI (x86-64)
14763   // or EAX and doing an indirect call.  The return value will then
14764   // be in the normal return register.
14765   const X86InstrInfo *TII
14766     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14767   DebugLoc DL = MI->getDebugLoc();
14768   MachineFunction *F = BB->getParent();
14769
14770   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14771   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14772
14773   // Get a register mask for the lowered call.
14774   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14775   // proper register mask.
14776   const uint32_t *RegMask =
14777     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14778   if (Subtarget->is64Bit()) {
14779     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14780                                       TII->get(X86::MOV64rm), X86::RDI)
14781     .addReg(X86::RIP)
14782     .addImm(0).addReg(0)
14783     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14784                       MI->getOperand(3).getTargetFlags())
14785     .addReg(0);
14786     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14787     addDirectMem(MIB, X86::RDI);
14788     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14789   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14790     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14791                                       TII->get(X86::MOV32rm), X86::EAX)
14792     .addReg(0)
14793     .addImm(0).addReg(0)
14794     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14795                       MI->getOperand(3).getTargetFlags())
14796     .addReg(0);
14797     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14798     addDirectMem(MIB, X86::EAX);
14799     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14800   } else {
14801     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14802                                       TII->get(X86::MOV32rm), X86::EAX)
14803     .addReg(TII->getGlobalBaseReg(F))
14804     .addImm(0).addReg(0)
14805     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14806                       MI->getOperand(3).getTargetFlags())
14807     .addReg(0);
14808     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14809     addDirectMem(MIB, X86::EAX);
14810     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14811   }
14812
14813   MI->eraseFromParent(); // The pseudo instruction is gone now.
14814   return BB;
14815 }
14816
14817 MachineBasicBlock *
14818 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14819                                     MachineBasicBlock *MBB) const {
14820   DebugLoc DL = MI->getDebugLoc();
14821   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14822
14823   MachineFunction *MF = MBB->getParent();
14824   MachineRegisterInfo &MRI = MF->getRegInfo();
14825
14826   const BasicBlock *BB = MBB->getBasicBlock();
14827   MachineFunction::iterator I = MBB;
14828   ++I;
14829
14830   // Memory Reference
14831   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14832   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14833
14834   unsigned DstReg;
14835   unsigned MemOpndSlot = 0;
14836
14837   unsigned CurOp = 0;
14838
14839   DstReg = MI->getOperand(CurOp++).getReg();
14840   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14841   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14842   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14843   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14844
14845   MemOpndSlot = CurOp;
14846
14847   MVT PVT = getPointerTy();
14848   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14849          "Invalid Pointer Size!");
14850
14851   // For v = setjmp(buf), we generate
14852   //
14853   // thisMBB:
14854   //  buf[LabelOffset] = restoreMBB
14855   //  SjLjSetup restoreMBB
14856   //
14857   // mainMBB:
14858   //  v_main = 0
14859   //
14860   // sinkMBB:
14861   //  v = phi(main, restore)
14862   //
14863   // restoreMBB:
14864   //  v_restore = 1
14865
14866   MachineBasicBlock *thisMBB = MBB;
14867   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14868   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14869   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14870   MF->insert(I, mainMBB);
14871   MF->insert(I, sinkMBB);
14872   MF->push_back(restoreMBB);
14873
14874   MachineInstrBuilder MIB;
14875
14876   // Transfer the remainder of BB and its successor edges to sinkMBB.
14877   sinkMBB->splice(sinkMBB->begin(), MBB,
14878                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14879   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14880
14881   // thisMBB:
14882   unsigned PtrStoreOpc = 0;
14883   unsigned LabelReg = 0;
14884   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14885   Reloc::Model RM = getTargetMachine().getRelocationModel();
14886   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14887                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14888
14889   // Prepare IP either in reg or imm.
14890   if (!UseImmLabel) {
14891     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14892     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14893     LabelReg = MRI.createVirtualRegister(PtrRC);
14894     if (Subtarget->is64Bit()) {
14895       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14896               .addReg(X86::RIP)
14897               .addImm(0)
14898               .addReg(0)
14899               .addMBB(restoreMBB)
14900               .addReg(0);
14901     } else {
14902       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14903       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14904               .addReg(XII->getGlobalBaseReg(MF))
14905               .addImm(0)
14906               .addReg(0)
14907               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14908               .addReg(0);
14909     }
14910   } else
14911     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14912   // Store IP
14913   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14914   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14915     if (i == X86::AddrDisp)
14916       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14917     else
14918       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14919   }
14920   if (!UseImmLabel)
14921     MIB.addReg(LabelReg);
14922   else
14923     MIB.addMBB(restoreMBB);
14924   MIB.setMemRefs(MMOBegin, MMOEnd);
14925   // Setup
14926   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14927           .addMBB(restoreMBB);
14928
14929   const X86RegisterInfo *RegInfo =
14930     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14931   MIB.addRegMask(RegInfo->getNoPreservedMask());
14932   thisMBB->addSuccessor(mainMBB);
14933   thisMBB->addSuccessor(restoreMBB);
14934
14935   // mainMBB:
14936   //  EAX = 0
14937   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14938   mainMBB->addSuccessor(sinkMBB);
14939
14940   // sinkMBB:
14941   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14942           TII->get(X86::PHI), DstReg)
14943     .addReg(mainDstReg).addMBB(mainMBB)
14944     .addReg(restoreDstReg).addMBB(restoreMBB);
14945
14946   // restoreMBB:
14947   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14948   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14949   restoreMBB->addSuccessor(sinkMBB);
14950
14951   MI->eraseFromParent();
14952   return sinkMBB;
14953 }
14954
14955 MachineBasicBlock *
14956 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14957                                      MachineBasicBlock *MBB) const {
14958   DebugLoc DL = MI->getDebugLoc();
14959   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14960
14961   MachineFunction *MF = MBB->getParent();
14962   MachineRegisterInfo &MRI = MF->getRegInfo();
14963
14964   // Memory Reference
14965   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14966   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14967
14968   MVT PVT = getPointerTy();
14969   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14970          "Invalid Pointer Size!");
14971
14972   const TargetRegisterClass *RC =
14973     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14974   unsigned Tmp = MRI.createVirtualRegister(RC);
14975   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14976   const X86RegisterInfo *RegInfo =
14977     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14978   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14979   unsigned SP = RegInfo->getStackRegister();
14980
14981   MachineInstrBuilder MIB;
14982
14983   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14984   const int64_t SPOffset = 2 * PVT.getStoreSize();
14985
14986   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14987   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14988
14989   // Reload FP
14990   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14991   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14992     MIB.addOperand(MI->getOperand(i));
14993   MIB.setMemRefs(MMOBegin, MMOEnd);
14994   // Reload IP
14995   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14996   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14997     if (i == X86::AddrDisp)
14998       MIB.addDisp(MI->getOperand(i), LabelOffset);
14999     else
15000       MIB.addOperand(MI->getOperand(i));
15001   }
15002   MIB.setMemRefs(MMOBegin, MMOEnd);
15003   // Reload SP
15004   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15005   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15006     if (i == X86::AddrDisp)
15007       MIB.addDisp(MI->getOperand(i), SPOffset);
15008     else
15009       MIB.addOperand(MI->getOperand(i));
15010   }
15011   MIB.setMemRefs(MMOBegin, MMOEnd);
15012   // Jump
15013   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15014
15015   MI->eraseFromParent();
15016   return MBB;
15017 }
15018
15019 MachineBasicBlock *
15020 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15021                                                MachineBasicBlock *BB) const {
15022   switch (MI->getOpcode()) {
15023   default: llvm_unreachable("Unexpected instr type to insert");
15024   case X86::TAILJMPd64:
15025   case X86::TAILJMPr64:
15026   case X86::TAILJMPm64:
15027     llvm_unreachable("TAILJMP64 would not be touched here.");
15028   case X86::TCRETURNdi64:
15029   case X86::TCRETURNri64:
15030   case X86::TCRETURNmi64:
15031     return BB;
15032   case X86::WIN_ALLOCA:
15033     return EmitLoweredWinAlloca(MI, BB);
15034   case X86::SEG_ALLOCA_32:
15035     return EmitLoweredSegAlloca(MI, BB, false);
15036   case X86::SEG_ALLOCA_64:
15037     return EmitLoweredSegAlloca(MI, BB, true);
15038   case X86::TLSCall_32:
15039   case X86::TLSCall_64:
15040     return EmitLoweredTLSCall(MI, BB);
15041   case X86::CMOV_GR8:
15042   case X86::CMOV_FR32:
15043   case X86::CMOV_FR64:
15044   case X86::CMOV_V4F32:
15045   case X86::CMOV_V2F64:
15046   case X86::CMOV_V2I64:
15047   case X86::CMOV_V8F32:
15048   case X86::CMOV_V4F64:
15049   case X86::CMOV_V4I64:
15050   case X86::CMOV_GR16:
15051   case X86::CMOV_GR32:
15052   case X86::CMOV_RFP32:
15053   case X86::CMOV_RFP64:
15054   case X86::CMOV_RFP80:
15055     return EmitLoweredSelect(MI, BB);
15056
15057   case X86::FP32_TO_INT16_IN_MEM:
15058   case X86::FP32_TO_INT32_IN_MEM:
15059   case X86::FP32_TO_INT64_IN_MEM:
15060   case X86::FP64_TO_INT16_IN_MEM:
15061   case X86::FP64_TO_INT32_IN_MEM:
15062   case X86::FP64_TO_INT64_IN_MEM:
15063   case X86::FP80_TO_INT16_IN_MEM:
15064   case X86::FP80_TO_INT32_IN_MEM:
15065   case X86::FP80_TO_INT64_IN_MEM: {
15066     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15067     DebugLoc DL = MI->getDebugLoc();
15068
15069     // Change the floating point control register to use "round towards zero"
15070     // mode when truncating to an integer value.
15071     MachineFunction *F = BB->getParent();
15072     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15073     addFrameReference(BuildMI(*BB, MI, DL,
15074                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15075
15076     // Load the old value of the high byte of the control word...
15077     unsigned OldCW =
15078       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15079     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15080                       CWFrameIdx);
15081
15082     // Set the high part to be round to zero...
15083     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15084       .addImm(0xC7F);
15085
15086     // Reload the modified control word now...
15087     addFrameReference(BuildMI(*BB, MI, DL,
15088                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15089
15090     // Restore the memory image of control word to original value
15091     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15092       .addReg(OldCW);
15093
15094     // Get the X86 opcode to use.
15095     unsigned Opc;
15096     switch (MI->getOpcode()) {
15097     default: llvm_unreachable("illegal opcode!");
15098     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15099     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15100     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15101     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15102     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15103     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15104     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15105     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15106     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15107     }
15108
15109     X86AddressMode AM;
15110     MachineOperand &Op = MI->getOperand(0);
15111     if (Op.isReg()) {
15112       AM.BaseType = X86AddressMode::RegBase;
15113       AM.Base.Reg = Op.getReg();
15114     } else {
15115       AM.BaseType = X86AddressMode::FrameIndexBase;
15116       AM.Base.FrameIndex = Op.getIndex();
15117     }
15118     Op = MI->getOperand(1);
15119     if (Op.isImm())
15120       AM.Scale = Op.getImm();
15121     Op = MI->getOperand(2);
15122     if (Op.isImm())
15123       AM.IndexReg = Op.getImm();
15124     Op = MI->getOperand(3);
15125     if (Op.isGlobal()) {
15126       AM.GV = Op.getGlobal();
15127     } else {
15128       AM.Disp = Op.getImm();
15129     }
15130     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15131                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15132
15133     // Reload the original control word now.
15134     addFrameReference(BuildMI(*BB, MI, DL,
15135                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15136
15137     MI->eraseFromParent();   // The pseudo instruction is gone now.
15138     return BB;
15139   }
15140     // String/text processing lowering.
15141   case X86::PCMPISTRM128REG:
15142   case X86::VPCMPISTRM128REG:
15143   case X86::PCMPISTRM128MEM:
15144   case X86::VPCMPISTRM128MEM:
15145   case X86::PCMPESTRM128REG:
15146   case X86::VPCMPESTRM128REG:
15147   case X86::PCMPESTRM128MEM:
15148   case X86::VPCMPESTRM128MEM:
15149     assert(Subtarget->hasSSE42() &&
15150            "Target must have SSE4.2 or AVX features enabled");
15151     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15152
15153   // String/text processing lowering.
15154   case X86::PCMPISTRIREG:
15155   case X86::VPCMPISTRIREG:
15156   case X86::PCMPISTRIMEM:
15157   case X86::VPCMPISTRIMEM:
15158   case X86::PCMPESTRIREG:
15159   case X86::VPCMPESTRIREG:
15160   case X86::PCMPESTRIMEM:
15161   case X86::VPCMPESTRIMEM:
15162     assert(Subtarget->hasSSE42() &&
15163            "Target must have SSE4.2 or AVX features enabled");
15164     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15165
15166   // Thread synchronization.
15167   case X86::MONITOR:
15168     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15169
15170   // xbegin
15171   case X86::XBEGIN:
15172     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15173
15174   // Atomic Lowering.
15175   case X86::ATOMAND8:
15176   case X86::ATOMAND16:
15177   case X86::ATOMAND32:
15178   case X86::ATOMAND64:
15179     // Fall through
15180   case X86::ATOMOR8:
15181   case X86::ATOMOR16:
15182   case X86::ATOMOR32:
15183   case X86::ATOMOR64:
15184     // Fall through
15185   case X86::ATOMXOR16:
15186   case X86::ATOMXOR8:
15187   case X86::ATOMXOR32:
15188   case X86::ATOMXOR64:
15189     // Fall through
15190   case X86::ATOMNAND8:
15191   case X86::ATOMNAND16:
15192   case X86::ATOMNAND32:
15193   case X86::ATOMNAND64:
15194     // Fall through
15195   case X86::ATOMMAX8:
15196   case X86::ATOMMAX16:
15197   case X86::ATOMMAX32:
15198   case X86::ATOMMAX64:
15199     // Fall through
15200   case X86::ATOMMIN8:
15201   case X86::ATOMMIN16:
15202   case X86::ATOMMIN32:
15203   case X86::ATOMMIN64:
15204     // Fall through
15205   case X86::ATOMUMAX8:
15206   case X86::ATOMUMAX16:
15207   case X86::ATOMUMAX32:
15208   case X86::ATOMUMAX64:
15209     // Fall through
15210   case X86::ATOMUMIN8:
15211   case X86::ATOMUMIN16:
15212   case X86::ATOMUMIN32:
15213   case X86::ATOMUMIN64:
15214     return EmitAtomicLoadArith(MI, BB);
15215
15216   // This group does 64-bit operations on a 32-bit host.
15217   case X86::ATOMAND6432:
15218   case X86::ATOMOR6432:
15219   case X86::ATOMXOR6432:
15220   case X86::ATOMNAND6432:
15221   case X86::ATOMADD6432:
15222   case X86::ATOMSUB6432:
15223   case X86::ATOMMAX6432:
15224   case X86::ATOMMIN6432:
15225   case X86::ATOMUMAX6432:
15226   case X86::ATOMUMIN6432:
15227   case X86::ATOMSWAP6432:
15228     return EmitAtomicLoadArith6432(MI, BB);
15229
15230   case X86::VASTART_SAVE_XMM_REGS:
15231     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15232
15233   case X86::VAARG_64:
15234     return EmitVAARG64WithCustomInserter(MI, BB);
15235
15236   case X86::EH_SjLj_SetJmp32:
15237   case X86::EH_SjLj_SetJmp64:
15238     return emitEHSjLjSetJmp(MI, BB);
15239
15240   case X86::EH_SjLj_LongJmp32:
15241   case X86::EH_SjLj_LongJmp64:
15242     return emitEHSjLjLongJmp(MI, BB);
15243   }
15244 }
15245
15246 //===----------------------------------------------------------------------===//
15247 //                           X86 Optimization Hooks
15248 //===----------------------------------------------------------------------===//
15249
15250 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15251                                                        APInt &KnownZero,
15252                                                        APInt &KnownOne,
15253                                                        const SelectionDAG &DAG,
15254                                                        unsigned Depth) const {
15255   unsigned BitWidth = KnownZero.getBitWidth();
15256   unsigned Opc = Op.getOpcode();
15257   assert((Opc >= ISD::BUILTIN_OP_END ||
15258           Opc == ISD::INTRINSIC_WO_CHAIN ||
15259           Opc == ISD::INTRINSIC_W_CHAIN ||
15260           Opc == ISD::INTRINSIC_VOID) &&
15261          "Should use MaskedValueIsZero if you don't know whether Op"
15262          " is a target node!");
15263
15264   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15265   switch (Opc) {
15266   default: break;
15267   case X86ISD::ADD:
15268   case X86ISD::SUB:
15269   case X86ISD::ADC:
15270   case X86ISD::SBB:
15271   case X86ISD::SMUL:
15272   case X86ISD::UMUL:
15273   case X86ISD::INC:
15274   case X86ISD::DEC:
15275   case X86ISD::OR:
15276   case X86ISD::XOR:
15277   case X86ISD::AND:
15278     // These nodes' second result is a boolean.
15279     if (Op.getResNo() == 0)
15280       break;
15281     // Fallthrough
15282   case X86ISD::SETCC:
15283     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15284     break;
15285   case ISD::INTRINSIC_WO_CHAIN: {
15286     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15287     unsigned NumLoBits = 0;
15288     switch (IntId) {
15289     default: break;
15290     case Intrinsic::x86_sse_movmsk_ps:
15291     case Intrinsic::x86_avx_movmsk_ps_256:
15292     case Intrinsic::x86_sse2_movmsk_pd:
15293     case Intrinsic::x86_avx_movmsk_pd_256:
15294     case Intrinsic::x86_mmx_pmovmskb:
15295     case Intrinsic::x86_sse2_pmovmskb_128:
15296     case Intrinsic::x86_avx2_pmovmskb: {
15297       // High bits of movmskp{s|d}, pmovmskb are known zero.
15298       switch (IntId) {
15299         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15300         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15301         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15302         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15303         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15304         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15305         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15306         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15307       }
15308       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15309       break;
15310     }
15311     }
15312     break;
15313   }
15314   }
15315 }
15316
15317 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15318                                                          unsigned Depth) const {
15319   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15320   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15321     return Op.getValueType().getScalarType().getSizeInBits();
15322
15323   // Fallback case.
15324   return 1;
15325 }
15326
15327 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15328 /// node is a GlobalAddress + offset.
15329 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15330                                        const GlobalValue* &GA,
15331                                        int64_t &Offset) const {
15332   if (N->getOpcode() == X86ISD::Wrapper) {
15333     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15334       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15335       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15336       return true;
15337     }
15338   }
15339   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15340 }
15341
15342 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15343 /// same as extracting the high 128-bit part of 256-bit vector and then
15344 /// inserting the result into the low part of a new 256-bit vector
15345 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15346   EVT VT = SVOp->getValueType(0);
15347   unsigned NumElems = VT.getVectorNumElements();
15348
15349   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15350   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15351     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15352         SVOp->getMaskElt(j) >= 0)
15353       return false;
15354
15355   return true;
15356 }
15357
15358 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15359 /// same as extracting the low 128-bit part of 256-bit vector and then
15360 /// inserting the result into the high part of a new 256-bit vector
15361 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15362   EVT VT = SVOp->getValueType(0);
15363   unsigned NumElems = VT.getVectorNumElements();
15364
15365   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15366   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15367     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15368         SVOp->getMaskElt(j) >= 0)
15369       return false;
15370
15371   return true;
15372 }
15373
15374 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15375 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15376                                         TargetLowering::DAGCombinerInfo &DCI,
15377                                         const X86Subtarget* Subtarget) {
15378   SDLoc dl(N);
15379   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15380   SDValue V1 = SVOp->getOperand(0);
15381   SDValue V2 = SVOp->getOperand(1);
15382   EVT VT = SVOp->getValueType(0);
15383   unsigned NumElems = VT.getVectorNumElements();
15384
15385   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15386       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15387     //
15388     //                   0,0,0,...
15389     //                      |
15390     //    V      UNDEF    BUILD_VECTOR    UNDEF
15391     //     \      /           \           /
15392     //  CONCAT_VECTOR         CONCAT_VECTOR
15393     //         \                  /
15394     //          \                /
15395     //          RESULT: V + zero extended
15396     //
15397     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15398         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15399         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15400       return SDValue();
15401
15402     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15403       return SDValue();
15404
15405     // To match the shuffle mask, the first half of the mask should
15406     // be exactly the first vector, and all the rest a splat with the
15407     // first element of the second one.
15408     for (unsigned i = 0; i != NumElems/2; ++i)
15409       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15410           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15411         return SDValue();
15412
15413     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15414     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15415       if (Ld->hasNUsesOfValue(1, 0)) {
15416         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15417         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15418         SDValue ResNode =
15419           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15420                                   array_lengthof(Ops),
15421                                   Ld->getMemoryVT(),
15422                                   Ld->getPointerInfo(),
15423                                   Ld->getAlignment(),
15424                                   false/*isVolatile*/, true/*ReadMem*/,
15425                                   false/*WriteMem*/);
15426
15427         // Make sure the newly-created LOAD is in the same position as Ld in
15428         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15429         // and update uses of Ld's output chain to use the TokenFactor.
15430         if (Ld->hasAnyUseOfValue(1)) {
15431           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15432                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15433           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15434           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15435                                  SDValue(ResNode.getNode(), 1));
15436         }
15437
15438         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15439       }
15440     }
15441
15442     // Emit a zeroed vector and insert the desired subvector on its
15443     // first half.
15444     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15445     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15446     return DCI.CombineTo(N, InsV);
15447   }
15448
15449   //===--------------------------------------------------------------------===//
15450   // Combine some shuffles into subvector extracts and inserts:
15451   //
15452
15453   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15454   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15455     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15456     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15457     return DCI.CombineTo(N, InsV);
15458   }
15459
15460   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15461   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15462     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15463     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15464     return DCI.CombineTo(N, InsV);
15465   }
15466
15467   return SDValue();
15468 }
15469
15470 /// PerformShuffleCombine - Performs several different shuffle combines.
15471 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15472                                      TargetLowering::DAGCombinerInfo &DCI,
15473                                      const X86Subtarget *Subtarget) {
15474   SDLoc dl(N);
15475   EVT VT = N->getValueType(0);
15476
15477   // Don't create instructions with illegal types after legalize types has run.
15478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15479   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15480     return SDValue();
15481
15482   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15483   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15484       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15485     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15486
15487   // Only handle 128 wide vector from here on.
15488   if (!VT.is128BitVector())
15489     return SDValue();
15490
15491   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15492   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15493   // consecutive, non-overlapping, and in the right order.
15494   SmallVector<SDValue, 16> Elts;
15495   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15496     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15497
15498   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15499 }
15500
15501 /// PerformTruncateCombine - Converts truncate operation to
15502 /// a sequence of vector shuffle operations.
15503 /// It is possible when we truncate 256-bit vector to 128-bit vector
15504 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15505                                       TargetLowering::DAGCombinerInfo &DCI,
15506                                       const X86Subtarget *Subtarget)  {
15507   return SDValue();
15508 }
15509
15510 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15511 /// specific shuffle of a load can be folded into a single element load.
15512 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15513 /// shuffles have been customed lowered so we need to handle those here.
15514 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15515                                          TargetLowering::DAGCombinerInfo &DCI) {
15516   if (DCI.isBeforeLegalizeOps())
15517     return SDValue();
15518
15519   SDValue InVec = N->getOperand(0);
15520   SDValue EltNo = N->getOperand(1);
15521
15522   if (!isa<ConstantSDNode>(EltNo))
15523     return SDValue();
15524
15525   EVT VT = InVec.getValueType();
15526
15527   bool HasShuffleIntoBitcast = false;
15528   if (InVec.getOpcode() == ISD::BITCAST) {
15529     // Don't duplicate a load with other uses.
15530     if (!InVec.hasOneUse())
15531       return SDValue();
15532     EVT BCVT = InVec.getOperand(0).getValueType();
15533     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15534       return SDValue();
15535     InVec = InVec.getOperand(0);
15536     HasShuffleIntoBitcast = true;
15537   }
15538
15539   if (!isTargetShuffle(InVec.getOpcode()))
15540     return SDValue();
15541
15542   // Don't duplicate a load with other uses.
15543   if (!InVec.hasOneUse())
15544     return SDValue();
15545
15546   SmallVector<int, 16> ShuffleMask;
15547   bool UnaryShuffle;
15548   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15549                             UnaryShuffle))
15550     return SDValue();
15551
15552   // Select the input vector, guarding against out of range extract vector.
15553   unsigned NumElems = VT.getVectorNumElements();
15554   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15555   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15556   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15557                                          : InVec.getOperand(1);
15558
15559   // If inputs to shuffle are the same for both ops, then allow 2 uses
15560   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15561
15562   if (LdNode.getOpcode() == ISD::BITCAST) {
15563     // Don't duplicate a load with other uses.
15564     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15565       return SDValue();
15566
15567     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15568     LdNode = LdNode.getOperand(0);
15569   }
15570
15571   if (!ISD::isNormalLoad(LdNode.getNode()))
15572     return SDValue();
15573
15574   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15575
15576   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15577     return SDValue();
15578
15579   if (HasShuffleIntoBitcast) {
15580     // If there's a bitcast before the shuffle, check if the load type and
15581     // alignment is valid.
15582     unsigned Align = LN0->getAlignment();
15583     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15584     unsigned NewAlign = TLI.getDataLayout()->
15585       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15586
15587     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15588       return SDValue();
15589   }
15590
15591   // All checks match so transform back to vector_shuffle so that DAG combiner
15592   // can finish the job
15593   SDLoc dl(N);
15594
15595   // Create shuffle node taking into account the case that its a unary shuffle
15596   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15597   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15598                                  InVec.getOperand(0), Shuffle,
15599                                  &ShuffleMask[0]);
15600   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15601   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15602                      EltNo);
15603 }
15604
15605 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15606 /// generation and convert it from being a bunch of shuffles and extracts
15607 /// to a simple store and scalar loads to extract the elements.
15608 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15609                                          TargetLowering::DAGCombinerInfo &DCI) {
15610   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15611   if (NewOp.getNode())
15612     return NewOp;
15613
15614   SDValue InputVector = N->getOperand(0);
15615   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15616   // from mmx to v2i32 has a single usage.
15617   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15618       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15619       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15620     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15621                        N->getValueType(0),
15622                        InputVector.getNode()->getOperand(0));
15623
15624   // Only operate on vectors of 4 elements, where the alternative shuffling
15625   // gets to be more expensive.
15626   if (InputVector.getValueType() != MVT::v4i32)
15627     return SDValue();
15628
15629   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15630   // single use which is a sign-extend or zero-extend, and all elements are
15631   // used.
15632   SmallVector<SDNode *, 4> Uses;
15633   unsigned ExtractedElements = 0;
15634   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15635        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15636     if (UI.getUse().getResNo() != InputVector.getResNo())
15637       return SDValue();
15638
15639     SDNode *Extract = *UI;
15640     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15641       return SDValue();
15642
15643     if (Extract->getValueType(0) != MVT::i32)
15644       return SDValue();
15645     if (!Extract->hasOneUse())
15646       return SDValue();
15647     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15648         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15649       return SDValue();
15650     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15651       return SDValue();
15652
15653     // Record which element was extracted.
15654     ExtractedElements |=
15655       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15656
15657     Uses.push_back(Extract);
15658   }
15659
15660   // If not all the elements were used, this may not be worthwhile.
15661   if (ExtractedElements != 15)
15662     return SDValue();
15663
15664   // Ok, we've now decided to do the transformation.
15665   SDLoc dl(InputVector);
15666
15667   // Store the value to a temporary stack slot.
15668   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15669   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15670                             MachinePointerInfo(), false, false, 0);
15671
15672   // Replace each use (extract) with a load of the appropriate element.
15673   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15674        UE = Uses.end(); UI != UE; ++UI) {
15675     SDNode *Extract = *UI;
15676
15677     // cOMpute the element's address.
15678     SDValue Idx = Extract->getOperand(1);
15679     unsigned EltSize =
15680         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15681     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15682     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15683     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15684
15685     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15686                                      StackPtr, OffsetVal);
15687
15688     // Load the scalar.
15689     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15690                                      ScalarAddr, MachinePointerInfo(),
15691                                      false, false, false, 0);
15692
15693     // Replace the exact with the load.
15694     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15695   }
15696
15697   // The replacement was made in place; don't return anything.
15698   return SDValue();
15699 }
15700
15701 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15702 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15703                                    SDValue RHS, SelectionDAG &DAG,
15704                                    const X86Subtarget *Subtarget) {
15705   if (!VT.isVector())
15706     return 0;
15707
15708   switch (VT.getSimpleVT().SimpleTy) {
15709   default: return 0;
15710   case MVT::v32i8:
15711   case MVT::v16i16:
15712   case MVT::v8i32:
15713     if (!Subtarget->hasAVX2())
15714       return 0;
15715   case MVT::v16i8:
15716   case MVT::v8i16:
15717   case MVT::v4i32:
15718     if (!Subtarget->hasSSE2())
15719       return 0;
15720   }
15721
15722   // SSE2 has only a small subset of the operations.
15723   bool hasUnsigned = Subtarget->hasSSE41() ||
15724                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15725   bool hasSigned = Subtarget->hasSSE41() ||
15726                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15727
15728   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15729
15730   // Check for x CC y ? x : y.
15731   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15732       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15733     switch (CC) {
15734     default: break;
15735     case ISD::SETULT:
15736     case ISD::SETULE:
15737       return hasUnsigned ? X86ISD::UMIN : 0;
15738     case ISD::SETUGT:
15739     case ISD::SETUGE:
15740       return hasUnsigned ? X86ISD::UMAX : 0;
15741     case ISD::SETLT:
15742     case ISD::SETLE:
15743       return hasSigned ? X86ISD::SMIN : 0;
15744     case ISD::SETGT:
15745     case ISD::SETGE:
15746       return hasSigned ? X86ISD::SMAX : 0;
15747     }
15748   // Check for x CC y ? y : x -- a min/max with reversed arms.
15749   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15750              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15751     switch (CC) {
15752     default: break;
15753     case ISD::SETULT:
15754     case ISD::SETULE:
15755       return hasUnsigned ? X86ISD::UMAX : 0;
15756     case ISD::SETUGT:
15757     case ISD::SETUGE:
15758       return hasUnsigned ? X86ISD::UMIN : 0;
15759     case ISD::SETLT:
15760     case ISD::SETLE:
15761       return hasSigned ? X86ISD::SMAX : 0;
15762     case ISD::SETGT:
15763     case ISD::SETGE:
15764       return hasSigned ? X86ISD::SMIN : 0;
15765     }
15766   }
15767
15768   return 0;
15769 }
15770
15771 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15772 /// nodes.
15773 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15774                                     TargetLowering::DAGCombinerInfo &DCI,
15775                                     const X86Subtarget *Subtarget) {
15776   SDLoc DL(N);
15777   SDValue Cond = N->getOperand(0);
15778   // Get the LHS/RHS of the select.
15779   SDValue LHS = N->getOperand(1);
15780   SDValue RHS = N->getOperand(2);
15781   EVT VT = LHS.getValueType();
15782
15783   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15784   // instructions match the semantics of the common C idiom x<y?x:y but not
15785   // x<=y?x:y, because of how they handle negative zero (which can be
15786   // ignored in unsafe-math mode).
15787   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15788       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15789       (Subtarget->hasSSE2() ||
15790        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15791     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15792
15793     unsigned Opcode = 0;
15794     // Check for x CC y ? x : y.
15795     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15796         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15797       switch (CC) {
15798       default: break;
15799       case ISD::SETULT:
15800         // Converting this to a min would handle NaNs incorrectly, and swapping
15801         // the operands would cause it to handle comparisons between positive
15802         // and negative zero incorrectly.
15803         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15804           if (!DAG.getTarget().Options.UnsafeFPMath &&
15805               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15806             break;
15807           std::swap(LHS, RHS);
15808         }
15809         Opcode = X86ISD::FMIN;
15810         break;
15811       case ISD::SETOLE:
15812         // Converting this to a min would handle comparisons between positive
15813         // and negative zero incorrectly.
15814         if (!DAG.getTarget().Options.UnsafeFPMath &&
15815             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15816           break;
15817         Opcode = X86ISD::FMIN;
15818         break;
15819       case ISD::SETULE:
15820         // Converting this to a min would handle both negative zeros and NaNs
15821         // incorrectly, but we can swap the operands to fix both.
15822         std::swap(LHS, RHS);
15823       case ISD::SETOLT:
15824       case ISD::SETLT:
15825       case ISD::SETLE:
15826         Opcode = X86ISD::FMIN;
15827         break;
15828
15829       case ISD::SETOGE:
15830         // Converting this to a max would handle comparisons between positive
15831         // and negative zero incorrectly.
15832         if (!DAG.getTarget().Options.UnsafeFPMath &&
15833             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15834           break;
15835         Opcode = X86ISD::FMAX;
15836         break;
15837       case ISD::SETUGT:
15838         // Converting this to a max would handle NaNs incorrectly, and swapping
15839         // the operands would cause it to handle comparisons between positive
15840         // and negative zero incorrectly.
15841         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15842           if (!DAG.getTarget().Options.UnsafeFPMath &&
15843               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15844             break;
15845           std::swap(LHS, RHS);
15846         }
15847         Opcode = X86ISD::FMAX;
15848         break;
15849       case ISD::SETUGE:
15850         // Converting this to a max would handle both negative zeros and NaNs
15851         // incorrectly, but we can swap the operands to fix both.
15852         std::swap(LHS, RHS);
15853       case ISD::SETOGT:
15854       case ISD::SETGT:
15855       case ISD::SETGE:
15856         Opcode = X86ISD::FMAX;
15857         break;
15858       }
15859     // Check for x CC y ? y : x -- a min/max with reversed arms.
15860     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15861                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15862       switch (CC) {
15863       default: break;
15864       case ISD::SETOGE:
15865         // Converting this to a min would handle comparisons between positive
15866         // and negative zero incorrectly, and swapping the operands would
15867         // cause it to handle NaNs incorrectly.
15868         if (!DAG.getTarget().Options.UnsafeFPMath &&
15869             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15870           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15871             break;
15872           std::swap(LHS, RHS);
15873         }
15874         Opcode = X86ISD::FMIN;
15875         break;
15876       case ISD::SETUGT:
15877         // Converting this to a min would handle NaNs incorrectly.
15878         if (!DAG.getTarget().Options.UnsafeFPMath &&
15879             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15880           break;
15881         Opcode = X86ISD::FMIN;
15882         break;
15883       case ISD::SETUGE:
15884         // Converting this to a min would handle both negative zeros and NaNs
15885         // incorrectly, but we can swap the operands to fix both.
15886         std::swap(LHS, RHS);
15887       case ISD::SETOGT:
15888       case ISD::SETGT:
15889       case ISD::SETGE:
15890         Opcode = X86ISD::FMIN;
15891         break;
15892
15893       case ISD::SETULT:
15894         // Converting this to a max would handle NaNs incorrectly.
15895         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15896           break;
15897         Opcode = X86ISD::FMAX;
15898         break;
15899       case ISD::SETOLE:
15900         // Converting this to a max would handle comparisons between positive
15901         // and negative zero incorrectly, and swapping the operands would
15902         // cause it to handle NaNs incorrectly.
15903         if (!DAG.getTarget().Options.UnsafeFPMath &&
15904             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15905           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15906             break;
15907           std::swap(LHS, RHS);
15908         }
15909         Opcode = X86ISD::FMAX;
15910         break;
15911       case ISD::SETULE:
15912         // Converting this to a max would handle both negative zeros and NaNs
15913         // incorrectly, but we can swap the operands to fix both.
15914         std::swap(LHS, RHS);
15915       case ISD::SETOLT:
15916       case ISD::SETLT:
15917       case ISD::SETLE:
15918         Opcode = X86ISD::FMAX;
15919         break;
15920       }
15921     }
15922
15923     if (Opcode)
15924       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15925   }
15926
15927   // If this is a select between two integer constants, try to do some
15928   // optimizations.
15929   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15930     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15931       // Don't do this for crazy integer types.
15932       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15933         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15934         // so that TrueC (the true value) is larger than FalseC.
15935         bool NeedsCondInvert = false;
15936
15937         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15938             // Efficiently invertible.
15939             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15940              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15941               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15942           NeedsCondInvert = true;
15943           std::swap(TrueC, FalseC);
15944         }
15945
15946         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15947         if (FalseC->getAPIntValue() == 0 &&
15948             TrueC->getAPIntValue().isPowerOf2()) {
15949           if (NeedsCondInvert) // Invert the condition if needed.
15950             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15951                                DAG.getConstant(1, Cond.getValueType()));
15952
15953           // Zero extend the condition if needed.
15954           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15955
15956           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15957           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15958                              DAG.getConstant(ShAmt, MVT::i8));
15959         }
15960
15961         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15962         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15963           if (NeedsCondInvert) // Invert the condition if needed.
15964             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15965                                DAG.getConstant(1, Cond.getValueType()));
15966
15967           // Zero extend the condition if needed.
15968           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15969                              FalseC->getValueType(0), Cond);
15970           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15971                              SDValue(FalseC, 0));
15972         }
15973
15974         // Optimize cases that will turn into an LEA instruction.  This requires
15975         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15976         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15977           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15978           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15979
15980           bool isFastMultiplier = false;
15981           if (Diff < 10) {
15982             switch ((unsigned char)Diff) {
15983               default: break;
15984               case 1:  // result = add base, cond
15985               case 2:  // result = lea base(    , cond*2)
15986               case 3:  // result = lea base(cond, cond*2)
15987               case 4:  // result = lea base(    , cond*4)
15988               case 5:  // result = lea base(cond, cond*4)
15989               case 8:  // result = lea base(    , cond*8)
15990               case 9:  // result = lea base(cond, cond*8)
15991                 isFastMultiplier = true;
15992                 break;
15993             }
15994           }
15995
15996           if (isFastMultiplier) {
15997             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15998             if (NeedsCondInvert) // Invert the condition if needed.
15999               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16000                                  DAG.getConstant(1, Cond.getValueType()));
16001
16002             // Zero extend the condition if needed.
16003             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16004                                Cond);
16005             // Scale the condition by the difference.
16006             if (Diff != 1)
16007               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16008                                  DAG.getConstant(Diff, Cond.getValueType()));
16009
16010             // Add the base if non-zero.
16011             if (FalseC->getAPIntValue() != 0)
16012               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16013                                  SDValue(FalseC, 0));
16014             return Cond;
16015           }
16016         }
16017       }
16018   }
16019
16020   // Canonicalize max and min:
16021   // (x > y) ? x : y -> (x >= y) ? x : y
16022   // (x < y) ? x : y -> (x <= y) ? x : y
16023   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16024   // the need for an extra compare
16025   // against zero. e.g.
16026   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16027   // subl   %esi, %edi
16028   // testl  %edi, %edi
16029   // movl   $0, %eax
16030   // cmovgl %edi, %eax
16031   // =>
16032   // xorl   %eax, %eax
16033   // subl   %esi, $edi
16034   // cmovsl %eax, %edi
16035   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16036       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16037       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16038     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16039     switch (CC) {
16040     default: break;
16041     case ISD::SETLT:
16042     case ISD::SETGT: {
16043       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16044       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16045                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16046       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16047     }
16048     }
16049   }
16050
16051   // Match VSELECTs into subs with unsigned saturation.
16052   if (!DCI.isBeforeLegalize() &&
16053       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16054       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16055       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16056        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16057     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16058
16059     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16060     // left side invert the predicate to simplify logic below.
16061     SDValue Other;
16062     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16063       Other = RHS;
16064       CC = ISD::getSetCCInverse(CC, true);
16065     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16066       Other = LHS;
16067     }
16068
16069     if (Other.getNode() && Other->getNumOperands() == 2 &&
16070         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16071       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16072       SDValue CondRHS = Cond->getOperand(1);
16073
16074       // Look for a general sub with unsigned saturation first.
16075       // x >= y ? x-y : 0 --> subus x, y
16076       // x >  y ? x-y : 0 --> subus x, y
16077       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16078           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16079         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16080
16081       // If the RHS is a constant we have to reverse the const canonicalization.
16082       // x > C-1 ? x+-C : 0 --> subus x, C
16083       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16084           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16085         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16086         if (CondRHS.getConstantOperandVal(0) == -A-1)
16087           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16088                              DAG.getConstant(-A, VT));
16089       }
16090
16091       // Another special case: If C was a sign bit, the sub has been
16092       // canonicalized into a xor.
16093       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16094       //        it's safe to decanonicalize the xor?
16095       // x s< 0 ? x^C : 0 --> subus x, C
16096       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16097           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16098           isSplatVector(OpRHS.getNode())) {
16099         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16100         if (A.isSignBit())
16101           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16102       }
16103     }
16104   }
16105
16106   // Try to match a min/max vector operation.
16107   if (!DCI.isBeforeLegalize() &&
16108       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16109     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16110       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16111
16112   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16113   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16114       Cond.getOpcode() == ISD::SETCC) {
16115
16116     assert(Cond.getValueType().isVector() &&
16117            "vector select expects a vector selector!");
16118
16119     EVT IntVT = Cond.getValueType();
16120     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16121     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16122
16123     if (!TValIsAllOnes && !FValIsAllZeros) {
16124       // Try invert the condition if true value is not all 1s and false value
16125       // is not all 0s.
16126       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16127       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16128
16129       if (TValIsAllZeros || FValIsAllOnes) {
16130         SDValue CC = Cond.getOperand(2);
16131         ISD::CondCode NewCC =
16132           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16133                                Cond.getOperand(0).getValueType().isInteger());
16134         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16135         std::swap(LHS, RHS);
16136         TValIsAllOnes = FValIsAllOnes;
16137         FValIsAllZeros = TValIsAllZeros;
16138       }
16139     }
16140
16141     if (TValIsAllOnes || FValIsAllZeros) {
16142       SDValue Ret;
16143
16144       if (TValIsAllOnes && FValIsAllZeros)
16145         Ret = Cond;
16146       else if (TValIsAllOnes)
16147         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16148                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16149       else if (FValIsAllZeros)
16150         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16151                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16152
16153       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16154     }
16155   }
16156
16157   // If we know that this node is legal then we know that it is going to be
16158   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16159   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16160   // to simplify previous instructions.
16161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16162   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16163       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16164     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16165
16166     // Don't optimize vector selects that map to mask-registers.
16167     if (BitWidth == 1)
16168       return SDValue();
16169
16170     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16171     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16172
16173     APInt KnownZero, KnownOne;
16174     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16175                                           DCI.isBeforeLegalizeOps());
16176     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16177         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16178       DCI.CommitTargetLoweringOpt(TLO);
16179   }
16180
16181   return SDValue();
16182 }
16183
16184 // Check whether a boolean test is testing a boolean value generated by
16185 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16186 // code.
16187 //
16188 // Simplify the following patterns:
16189 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16190 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16191 // to (Op EFLAGS Cond)
16192 //
16193 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16194 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16195 // to (Op EFLAGS !Cond)
16196 //
16197 // where Op could be BRCOND or CMOV.
16198 //
16199 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16200   // Quit if not CMP and SUB with its value result used.
16201   if (Cmp.getOpcode() != X86ISD::CMP &&
16202       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16203       return SDValue();
16204
16205   // Quit if not used as a boolean value.
16206   if (CC != X86::COND_E && CC != X86::COND_NE)
16207     return SDValue();
16208
16209   // Check CMP operands. One of them should be 0 or 1 and the other should be
16210   // an SetCC or extended from it.
16211   SDValue Op1 = Cmp.getOperand(0);
16212   SDValue Op2 = Cmp.getOperand(1);
16213
16214   SDValue SetCC;
16215   const ConstantSDNode* C = 0;
16216   bool needOppositeCond = (CC == X86::COND_E);
16217   bool checkAgainstTrue = false; // Is it a comparison against 1?
16218
16219   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16220     SetCC = Op2;
16221   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16222     SetCC = Op1;
16223   else // Quit if all operands are not constants.
16224     return SDValue();
16225
16226   if (C->getZExtValue() == 1) {
16227     needOppositeCond = !needOppositeCond;
16228     checkAgainstTrue = true;
16229   } else if (C->getZExtValue() != 0)
16230     // Quit if the constant is neither 0 or 1.
16231     return SDValue();
16232
16233   bool truncatedToBoolWithAnd = false;
16234   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16235   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16236          SetCC.getOpcode() == ISD::TRUNCATE ||
16237          SetCC.getOpcode() == ISD::AND) {
16238     if (SetCC.getOpcode() == ISD::AND) {
16239       int OpIdx = -1;
16240       ConstantSDNode *CS;
16241       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16242           CS->getZExtValue() == 1)
16243         OpIdx = 1;
16244       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16245           CS->getZExtValue() == 1)
16246         OpIdx = 0;
16247       if (OpIdx == -1)
16248         break;
16249       SetCC = SetCC.getOperand(OpIdx);
16250       truncatedToBoolWithAnd = true;
16251     } else
16252       SetCC = SetCC.getOperand(0);
16253   }
16254
16255   switch (SetCC.getOpcode()) {
16256   case X86ISD::SETCC_CARRY:
16257     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16258     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16259     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16260     // truncated to i1 using 'and'.
16261     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16262       break;
16263     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16264            "Invalid use of SETCC_CARRY!");
16265     // FALL THROUGH
16266   case X86ISD::SETCC:
16267     // Set the condition code or opposite one if necessary.
16268     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16269     if (needOppositeCond)
16270       CC = X86::GetOppositeBranchCondition(CC);
16271     return SetCC.getOperand(1);
16272   case X86ISD::CMOV: {
16273     // Check whether false/true value has canonical one, i.e. 0 or 1.
16274     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16275     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16276     // Quit if true value is not a constant.
16277     if (!TVal)
16278       return SDValue();
16279     // Quit if false value is not a constant.
16280     if (!FVal) {
16281       SDValue Op = SetCC.getOperand(0);
16282       // Skip 'zext' or 'trunc' node.
16283       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16284           Op.getOpcode() == ISD::TRUNCATE)
16285         Op = Op.getOperand(0);
16286       // A special case for rdrand/rdseed, where 0 is set if false cond is
16287       // found.
16288       if ((Op.getOpcode() != X86ISD::RDRAND &&
16289            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16290         return SDValue();
16291     }
16292     // Quit if false value is not the constant 0 or 1.
16293     bool FValIsFalse = true;
16294     if (FVal && FVal->getZExtValue() != 0) {
16295       if (FVal->getZExtValue() != 1)
16296         return SDValue();
16297       // If FVal is 1, opposite cond is needed.
16298       needOppositeCond = !needOppositeCond;
16299       FValIsFalse = false;
16300     }
16301     // Quit if TVal is not the constant opposite of FVal.
16302     if (FValIsFalse && TVal->getZExtValue() != 1)
16303       return SDValue();
16304     if (!FValIsFalse && TVal->getZExtValue() != 0)
16305       return SDValue();
16306     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16307     if (needOppositeCond)
16308       CC = X86::GetOppositeBranchCondition(CC);
16309     return SetCC.getOperand(3);
16310   }
16311   }
16312
16313   return SDValue();
16314 }
16315
16316 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16317 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16318                                   TargetLowering::DAGCombinerInfo &DCI,
16319                                   const X86Subtarget *Subtarget) {
16320   SDLoc DL(N);
16321
16322   // If the flag operand isn't dead, don't touch this CMOV.
16323   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16324     return SDValue();
16325
16326   SDValue FalseOp = N->getOperand(0);
16327   SDValue TrueOp = N->getOperand(1);
16328   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16329   SDValue Cond = N->getOperand(3);
16330
16331   if (CC == X86::COND_E || CC == X86::COND_NE) {
16332     switch (Cond.getOpcode()) {
16333     default: break;
16334     case X86ISD::BSR:
16335     case X86ISD::BSF:
16336       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16337       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16338         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16339     }
16340   }
16341
16342   SDValue Flags;
16343
16344   Flags = checkBoolTestSetCCCombine(Cond, CC);
16345   if (Flags.getNode() &&
16346       // Extra check as FCMOV only supports a subset of X86 cond.
16347       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16348     SDValue Ops[] = { FalseOp, TrueOp,
16349                       DAG.getConstant(CC, MVT::i8), Flags };
16350     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16351                        Ops, array_lengthof(Ops));
16352   }
16353
16354   // If this is a select between two integer constants, try to do some
16355   // optimizations.  Note that the operands are ordered the opposite of SELECT
16356   // operands.
16357   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16358     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16359       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16360       // larger than FalseC (the false value).
16361       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16362         CC = X86::GetOppositeBranchCondition(CC);
16363         std::swap(TrueC, FalseC);
16364         std::swap(TrueOp, FalseOp);
16365       }
16366
16367       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16368       // This is efficient for any integer data type (including i8/i16) and
16369       // shift amount.
16370       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16371         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16372                            DAG.getConstant(CC, MVT::i8), Cond);
16373
16374         // Zero extend the condition if needed.
16375         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16376
16377         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16378         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16379                            DAG.getConstant(ShAmt, MVT::i8));
16380         if (N->getNumValues() == 2)  // Dead flag value?
16381           return DCI.CombineTo(N, Cond, SDValue());
16382         return Cond;
16383       }
16384
16385       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16386       // for any integer data type, including i8/i16.
16387       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16388         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16389                            DAG.getConstant(CC, MVT::i8), Cond);
16390
16391         // Zero extend the condition if needed.
16392         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16393                            FalseC->getValueType(0), Cond);
16394         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16395                            SDValue(FalseC, 0));
16396
16397         if (N->getNumValues() == 2)  // Dead flag value?
16398           return DCI.CombineTo(N, Cond, SDValue());
16399         return Cond;
16400       }
16401
16402       // Optimize cases that will turn into an LEA instruction.  This requires
16403       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16404       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16405         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16406         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16407
16408         bool isFastMultiplier = false;
16409         if (Diff < 10) {
16410           switch ((unsigned char)Diff) {
16411           default: break;
16412           case 1:  // result = add base, cond
16413           case 2:  // result = lea base(    , cond*2)
16414           case 3:  // result = lea base(cond, cond*2)
16415           case 4:  // result = lea base(    , cond*4)
16416           case 5:  // result = lea base(cond, cond*4)
16417           case 8:  // result = lea base(    , cond*8)
16418           case 9:  // result = lea base(cond, cond*8)
16419             isFastMultiplier = true;
16420             break;
16421           }
16422         }
16423
16424         if (isFastMultiplier) {
16425           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16426           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16427                              DAG.getConstant(CC, MVT::i8), Cond);
16428           // Zero extend the condition if needed.
16429           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16430                              Cond);
16431           // Scale the condition by the difference.
16432           if (Diff != 1)
16433             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16434                                DAG.getConstant(Diff, Cond.getValueType()));
16435
16436           // Add the base if non-zero.
16437           if (FalseC->getAPIntValue() != 0)
16438             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16439                                SDValue(FalseC, 0));
16440           if (N->getNumValues() == 2)  // Dead flag value?
16441             return DCI.CombineTo(N, Cond, SDValue());
16442           return Cond;
16443         }
16444       }
16445     }
16446   }
16447
16448   // Handle these cases:
16449   //   (select (x != c), e, c) -> select (x != c), e, x),
16450   //   (select (x == c), c, e) -> select (x == c), x, e)
16451   // where the c is an integer constant, and the "select" is the combination
16452   // of CMOV and CMP.
16453   //
16454   // The rationale for this change is that the conditional-move from a constant
16455   // needs two instructions, however, conditional-move from a register needs
16456   // only one instruction.
16457   //
16458   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16459   //  some instruction-combining opportunities. This opt needs to be
16460   //  postponed as late as possible.
16461   //
16462   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16463     // the DCI.xxxx conditions are provided to postpone the optimization as
16464     // late as possible.
16465
16466     ConstantSDNode *CmpAgainst = 0;
16467     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16468         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16469         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16470
16471       if (CC == X86::COND_NE &&
16472           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16473         CC = X86::GetOppositeBranchCondition(CC);
16474         std::swap(TrueOp, FalseOp);
16475       }
16476
16477       if (CC == X86::COND_E &&
16478           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16479         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16480                           DAG.getConstant(CC, MVT::i8), Cond };
16481         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16482                            array_lengthof(Ops));
16483       }
16484     }
16485   }
16486
16487   return SDValue();
16488 }
16489
16490 /// PerformMulCombine - Optimize a single multiply with constant into two
16491 /// in order to implement it with two cheaper instructions, e.g.
16492 /// LEA + SHL, LEA + LEA.
16493 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16494                                  TargetLowering::DAGCombinerInfo &DCI) {
16495   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16496     return SDValue();
16497
16498   EVT VT = N->getValueType(0);
16499   if (VT != MVT::i64)
16500     return SDValue();
16501
16502   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16503   if (!C)
16504     return SDValue();
16505   uint64_t MulAmt = C->getZExtValue();
16506   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16507     return SDValue();
16508
16509   uint64_t MulAmt1 = 0;
16510   uint64_t MulAmt2 = 0;
16511   if ((MulAmt % 9) == 0) {
16512     MulAmt1 = 9;
16513     MulAmt2 = MulAmt / 9;
16514   } else if ((MulAmt % 5) == 0) {
16515     MulAmt1 = 5;
16516     MulAmt2 = MulAmt / 5;
16517   } else if ((MulAmt % 3) == 0) {
16518     MulAmt1 = 3;
16519     MulAmt2 = MulAmt / 3;
16520   }
16521   if (MulAmt2 &&
16522       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16523     SDLoc DL(N);
16524
16525     if (isPowerOf2_64(MulAmt2) &&
16526         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16527       // If second multiplifer is pow2, issue it first. We want the multiply by
16528       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16529       // is an add.
16530       std::swap(MulAmt1, MulAmt2);
16531
16532     SDValue NewMul;
16533     if (isPowerOf2_64(MulAmt1))
16534       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16535                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16536     else
16537       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16538                            DAG.getConstant(MulAmt1, VT));
16539
16540     if (isPowerOf2_64(MulAmt2))
16541       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16542                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16543     else
16544       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16545                            DAG.getConstant(MulAmt2, VT));
16546
16547     // Do not add new nodes to DAG combiner worklist.
16548     DCI.CombineTo(N, NewMul, false);
16549   }
16550   return SDValue();
16551 }
16552
16553 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16554   SDValue N0 = N->getOperand(0);
16555   SDValue N1 = N->getOperand(1);
16556   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16557   EVT VT = N0.getValueType();
16558
16559   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16560   // since the result of setcc_c is all zero's or all ones.
16561   if (VT.isInteger() && !VT.isVector() &&
16562       N1C && N0.getOpcode() == ISD::AND &&
16563       N0.getOperand(1).getOpcode() == ISD::Constant) {
16564     SDValue N00 = N0.getOperand(0);
16565     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16566         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16567           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16568          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16569       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16570       APInt ShAmt = N1C->getAPIntValue();
16571       Mask = Mask.shl(ShAmt);
16572       if (Mask != 0)
16573         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16574                            N00, DAG.getConstant(Mask, VT));
16575     }
16576   }
16577
16578   // Hardware support for vector shifts is sparse which makes us scalarize the
16579   // vector operations in many cases. Also, on sandybridge ADD is faster than
16580   // shl.
16581   // (shl V, 1) -> add V,V
16582   if (isSplatVector(N1.getNode())) {
16583     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16584     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16585     // We shift all of the values by one. In many cases we do not have
16586     // hardware support for this operation. This is better expressed as an ADD
16587     // of two values.
16588     if (N1C && (1 == N1C->getZExtValue())) {
16589       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16590     }
16591   }
16592
16593   return SDValue();
16594 }
16595
16596 /// \brief Returns a vector of 0s if the node in input is a vector logical
16597 /// shift by a constant amount which is known to be bigger than or equal 
16598 /// to the vector element size in bits.
16599 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16600                                       const X86Subtarget *Subtarget) {
16601   EVT VT = N->getValueType(0);
16602
16603   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16604       (!Subtarget->hasInt256() ||
16605        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16606     return SDValue();
16607
16608   SDValue Amt = N->getOperand(1);
16609   SDLoc DL(N);
16610   if (isSplatVector(Amt.getNode())) {
16611     SDValue SclrAmt = Amt->getOperand(0);
16612     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16613       APInt ShiftAmt = C->getAPIntValue();
16614       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16615
16616       // SSE2/AVX2 logical shifts always return a vector of 0s
16617       // if the shift amount is bigger than or equal to 
16618       // the element size. The constant shift amount will be
16619       // encoded as a 8-bit immediate.
16620       if (ShiftAmt.trunc(8).uge(MaxAmount))
16621         return getZeroVector(VT, Subtarget, DAG, DL);
16622     }
16623   }
16624
16625   return SDValue();
16626 }
16627
16628 /// PerformShiftCombine - Combine shifts.
16629 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16630                                    TargetLowering::DAGCombinerInfo &DCI,
16631                                    const X86Subtarget *Subtarget) {
16632   if (N->getOpcode() == ISD::SHL) {
16633     SDValue V = PerformSHLCombine(N, DAG);
16634     if (V.getNode()) return V;
16635   }
16636
16637   if (N->getOpcode() != ISD::SRA) {
16638     // Try to fold this logical shift into a zero vector.
16639     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16640     if (V.getNode()) return V;
16641   }
16642
16643   return SDValue();
16644 }
16645
16646 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16647 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16648 // and friends.  Likewise for OR -> CMPNEQSS.
16649 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16650                             TargetLowering::DAGCombinerInfo &DCI,
16651                             const X86Subtarget *Subtarget) {
16652   unsigned opcode;
16653
16654   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16655   // we're requiring SSE2 for both.
16656   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16657     SDValue N0 = N->getOperand(0);
16658     SDValue N1 = N->getOperand(1);
16659     SDValue CMP0 = N0->getOperand(1);
16660     SDValue CMP1 = N1->getOperand(1);
16661     SDLoc DL(N);
16662
16663     // The SETCCs should both refer to the same CMP.
16664     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16665       return SDValue();
16666
16667     SDValue CMP00 = CMP0->getOperand(0);
16668     SDValue CMP01 = CMP0->getOperand(1);
16669     EVT     VT    = CMP00.getValueType();
16670
16671     if (VT == MVT::f32 || VT == MVT::f64) {
16672       bool ExpectingFlags = false;
16673       // Check for any users that want flags:
16674       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16675            !ExpectingFlags && UI != UE; ++UI)
16676         switch (UI->getOpcode()) {
16677         default:
16678         case ISD::BR_CC:
16679         case ISD::BRCOND:
16680         case ISD::SELECT:
16681           ExpectingFlags = true;
16682           break;
16683         case ISD::CopyToReg:
16684         case ISD::SIGN_EXTEND:
16685         case ISD::ZERO_EXTEND:
16686         case ISD::ANY_EXTEND:
16687           break;
16688         }
16689
16690       if (!ExpectingFlags) {
16691         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16692         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16693
16694         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16695           X86::CondCode tmp = cc0;
16696           cc0 = cc1;
16697           cc1 = tmp;
16698         }
16699
16700         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16701             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16702           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16703           X86ISD::NodeType NTOperator = is64BitFP ?
16704             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16705           // FIXME: need symbolic constants for these magic numbers.
16706           // See X86ATTInstPrinter.cpp:printSSECC().
16707           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16708           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16709                                               DAG.getConstant(x86cc, MVT::i8));
16710           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16711                                               OnesOrZeroesF);
16712           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16713                                       DAG.getConstant(1, MVT::i32));
16714           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16715           return OneBitOfTruth;
16716         }
16717       }
16718     }
16719   }
16720   return SDValue();
16721 }
16722
16723 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16724 /// so it can be folded inside ANDNP.
16725 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16726   EVT VT = N->getValueType(0);
16727
16728   // Match direct AllOnes for 128 and 256-bit vectors
16729   if (ISD::isBuildVectorAllOnes(N))
16730     return true;
16731
16732   // Look through a bit convert.
16733   if (N->getOpcode() == ISD::BITCAST)
16734     N = N->getOperand(0).getNode();
16735
16736   // Sometimes the operand may come from a insert_subvector building a 256-bit
16737   // allones vector
16738   if (VT.is256BitVector() &&
16739       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16740     SDValue V1 = N->getOperand(0);
16741     SDValue V2 = N->getOperand(1);
16742
16743     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16744         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16745         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16746         ISD::isBuildVectorAllOnes(V2.getNode()))
16747       return true;
16748   }
16749
16750   return false;
16751 }
16752
16753 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16754 // register. In most cases we actually compare or select YMM-sized registers
16755 // and mixing the two types creates horrible code. This method optimizes
16756 // some of the transition sequences.
16757 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16758                                  TargetLowering::DAGCombinerInfo &DCI,
16759                                  const X86Subtarget *Subtarget) {
16760   EVT VT = N->getValueType(0);
16761   if (!VT.is256BitVector())
16762     return SDValue();
16763
16764   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16765           N->getOpcode() == ISD::ZERO_EXTEND ||
16766           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16767
16768   SDValue Narrow = N->getOperand(0);
16769   EVT NarrowVT = Narrow->getValueType(0);
16770   if (!NarrowVT.is128BitVector())
16771     return SDValue();
16772
16773   if (Narrow->getOpcode() != ISD::XOR &&
16774       Narrow->getOpcode() != ISD::AND &&
16775       Narrow->getOpcode() != ISD::OR)
16776     return SDValue();
16777
16778   SDValue N0  = Narrow->getOperand(0);
16779   SDValue N1  = Narrow->getOperand(1);
16780   SDLoc DL(Narrow);
16781
16782   // The Left side has to be a trunc.
16783   if (N0.getOpcode() != ISD::TRUNCATE)
16784     return SDValue();
16785
16786   // The type of the truncated inputs.
16787   EVT WideVT = N0->getOperand(0)->getValueType(0);
16788   if (WideVT != VT)
16789     return SDValue();
16790
16791   // The right side has to be a 'trunc' or a constant vector.
16792   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16793   bool RHSConst = (isSplatVector(N1.getNode()) &&
16794                    isa<ConstantSDNode>(N1->getOperand(0)));
16795   if (!RHSTrunc && !RHSConst)
16796     return SDValue();
16797
16798   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16799
16800   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16801     return SDValue();
16802
16803   // Set N0 and N1 to hold the inputs to the new wide operation.
16804   N0 = N0->getOperand(0);
16805   if (RHSConst) {
16806     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16807                      N1->getOperand(0));
16808     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16809     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16810   } else if (RHSTrunc) {
16811     N1 = N1->getOperand(0);
16812   }
16813
16814   // Generate the wide operation.
16815   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16816   unsigned Opcode = N->getOpcode();
16817   switch (Opcode) {
16818   case ISD::ANY_EXTEND:
16819     return Op;
16820   case ISD::ZERO_EXTEND: {
16821     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16822     APInt Mask = APInt::getAllOnesValue(InBits);
16823     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16824     return DAG.getNode(ISD::AND, DL, VT,
16825                        Op, DAG.getConstant(Mask, VT));
16826   }
16827   case ISD::SIGN_EXTEND:
16828     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16829                        Op, DAG.getValueType(NarrowVT));
16830   default:
16831     llvm_unreachable("Unexpected opcode");
16832   }
16833 }
16834
16835 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16836                                  TargetLowering::DAGCombinerInfo &DCI,
16837                                  const X86Subtarget *Subtarget) {
16838   EVT VT = N->getValueType(0);
16839   if (DCI.isBeforeLegalizeOps())
16840     return SDValue();
16841
16842   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16843   if (R.getNode())
16844     return R;
16845
16846   // Create BLSI, and BLSR instructions
16847   // BLSI is X & (-X)
16848   // BLSR is X & (X-1)
16849   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16850     SDValue N0 = N->getOperand(0);
16851     SDValue N1 = N->getOperand(1);
16852     SDLoc DL(N);
16853
16854     // Check LHS for neg
16855     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16856         isZero(N0.getOperand(0)))
16857       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16858
16859     // Check RHS for neg
16860     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16861         isZero(N1.getOperand(0)))
16862       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16863
16864     // Check LHS for X-1
16865     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16866         isAllOnes(N0.getOperand(1)))
16867       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16868
16869     // Check RHS for X-1
16870     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16871         isAllOnes(N1.getOperand(1)))
16872       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16873
16874     return SDValue();
16875   }
16876
16877   // Want to form ANDNP nodes:
16878   // 1) In the hopes of then easily combining them with OR and AND nodes
16879   //    to form PBLEND/PSIGN.
16880   // 2) To match ANDN packed intrinsics
16881   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16882     return SDValue();
16883
16884   SDValue N0 = N->getOperand(0);
16885   SDValue N1 = N->getOperand(1);
16886   SDLoc DL(N);
16887
16888   // Check LHS for vnot
16889   if (N0.getOpcode() == ISD::XOR &&
16890       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16891       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16892     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16893
16894   // Check RHS for vnot
16895   if (N1.getOpcode() == ISD::XOR &&
16896       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16897       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16898     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16899
16900   return SDValue();
16901 }
16902
16903 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16904                                 TargetLowering::DAGCombinerInfo &DCI,
16905                                 const X86Subtarget *Subtarget) {
16906   EVT VT = N->getValueType(0);
16907   if (DCI.isBeforeLegalizeOps())
16908     return SDValue();
16909
16910   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16911   if (R.getNode())
16912     return R;
16913
16914   SDValue N0 = N->getOperand(0);
16915   SDValue N1 = N->getOperand(1);
16916
16917   // look for psign/blend
16918   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16919     if (!Subtarget->hasSSSE3() ||
16920         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16921       return SDValue();
16922
16923     // Canonicalize pandn to RHS
16924     if (N0.getOpcode() == X86ISD::ANDNP)
16925       std::swap(N0, N1);
16926     // or (and (m, y), (pandn m, x))
16927     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16928       SDValue Mask = N1.getOperand(0);
16929       SDValue X    = N1.getOperand(1);
16930       SDValue Y;
16931       if (N0.getOperand(0) == Mask)
16932         Y = N0.getOperand(1);
16933       if (N0.getOperand(1) == Mask)
16934         Y = N0.getOperand(0);
16935
16936       // Check to see if the mask appeared in both the AND and ANDNP and
16937       if (!Y.getNode())
16938         return SDValue();
16939
16940       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16941       // Look through mask bitcast.
16942       if (Mask.getOpcode() == ISD::BITCAST)
16943         Mask = Mask.getOperand(0);
16944       if (X.getOpcode() == ISD::BITCAST)
16945         X = X.getOperand(0);
16946       if (Y.getOpcode() == ISD::BITCAST)
16947         Y = Y.getOperand(0);
16948
16949       EVT MaskVT = Mask.getValueType();
16950
16951       // Validate that the Mask operand is a vector sra node.
16952       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16953       // there is no psrai.b
16954       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16955       unsigned SraAmt = ~0;
16956       if (Mask.getOpcode() == ISD::SRA) {
16957         SDValue Amt = Mask.getOperand(1);
16958         if (isSplatVector(Amt.getNode())) {
16959           SDValue SclrAmt = Amt->getOperand(0);
16960           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16961             SraAmt = C->getZExtValue();
16962         }
16963       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16964         SDValue SraC = Mask.getOperand(1);
16965         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16966       }
16967       if ((SraAmt + 1) != EltBits)
16968         return SDValue();
16969
16970       SDLoc DL(N);
16971
16972       // Now we know we at least have a plendvb with the mask val.  See if
16973       // we can form a psignb/w/d.
16974       // psign = x.type == y.type == mask.type && y = sub(0, x);
16975       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16976           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16977           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16978         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16979                "Unsupported VT for PSIGN");
16980         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16981         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16982       }
16983       // PBLENDVB only available on SSE 4.1
16984       if (!Subtarget->hasSSE41())
16985         return SDValue();
16986
16987       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16988
16989       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16990       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16991       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16992       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16993       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16994     }
16995   }
16996
16997   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16998     return SDValue();
16999
17000   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17001   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17002     std::swap(N0, N1);
17003   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17004     return SDValue();
17005   if (!N0.hasOneUse() || !N1.hasOneUse())
17006     return SDValue();
17007
17008   SDValue ShAmt0 = N0.getOperand(1);
17009   if (ShAmt0.getValueType() != MVT::i8)
17010     return SDValue();
17011   SDValue ShAmt1 = N1.getOperand(1);
17012   if (ShAmt1.getValueType() != MVT::i8)
17013     return SDValue();
17014   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17015     ShAmt0 = ShAmt0.getOperand(0);
17016   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17017     ShAmt1 = ShAmt1.getOperand(0);
17018
17019   SDLoc DL(N);
17020   unsigned Opc = X86ISD::SHLD;
17021   SDValue Op0 = N0.getOperand(0);
17022   SDValue Op1 = N1.getOperand(0);
17023   if (ShAmt0.getOpcode() == ISD::SUB) {
17024     Opc = X86ISD::SHRD;
17025     std::swap(Op0, Op1);
17026     std::swap(ShAmt0, ShAmt1);
17027   }
17028
17029   unsigned Bits = VT.getSizeInBits();
17030   if (ShAmt1.getOpcode() == ISD::SUB) {
17031     SDValue Sum = ShAmt1.getOperand(0);
17032     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17033       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17034       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17035         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17036       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17037         return DAG.getNode(Opc, DL, VT,
17038                            Op0, Op1,
17039                            DAG.getNode(ISD::TRUNCATE, DL,
17040                                        MVT::i8, ShAmt0));
17041     }
17042   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17043     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17044     if (ShAmt0C &&
17045         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17046       return DAG.getNode(Opc, DL, VT,
17047                          N0.getOperand(0), N1.getOperand(0),
17048                          DAG.getNode(ISD::TRUNCATE, DL,
17049                                        MVT::i8, ShAmt0));
17050   }
17051
17052   return SDValue();
17053 }
17054
17055 // Generate NEG and CMOV for integer abs.
17056 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17057   EVT VT = N->getValueType(0);
17058
17059   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17060   // 8-bit integer abs to NEG and CMOV.
17061   if (VT.isInteger() && VT.getSizeInBits() == 8)
17062     return SDValue();
17063
17064   SDValue N0 = N->getOperand(0);
17065   SDValue N1 = N->getOperand(1);
17066   SDLoc DL(N);
17067
17068   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17069   // and change it to SUB and CMOV.
17070   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17071       N0.getOpcode() == ISD::ADD &&
17072       N0.getOperand(1) == N1 &&
17073       N1.getOpcode() == ISD::SRA &&
17074       N1.getOperand(0) == N0.getOperand(0))
17075     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17076       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17077         // Generate SUB & CMOV.
17078         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17079                                   DAG.getConstant(0, VT), N0.getOperand(0));
17080
17081         SDValue Ops[] = { N0.getOperand(0), Neg,
17082                           DAG.getConstant(X86::COND_GE, MVT::i8),
17083                           SDValue(Neg.getNode(), 1) };
17084         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17085                            Ops, array_lengthof(Ops));
17086       }
17087   return SDValue();
17088 }
17089
17090 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17091 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17092                                  TargetLowering::DAGCombinerInfo &DCI,
17093                                  const X86Subtarget *Subtarget) {
17094   EVT VT = N->getValueType(0);
17095   if (DCI.isBeforeLegalizeOps())
17096     return SDValue();
17097
17098   if (Subtarget->hasCMov()) {
17099     SDValue RV = performIntegerAbsCombine(N, DAG);
17100     if (RV.getNode())
17101       return RV;
17102   }
17103
17104   // Try forming BMI if it is available.
17105   if (!Subtarget->hasBMI())
17106     return SDValue();
17107
17108   if (VT != MVT::i32 && VT != MVT::i64)
17109     return SDValue();
17110
17111   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17112
17113   // Create BLSMSK instructions by finding X ^ (X-1)
17114   SDValue N0 = N->getOperand(0);
17115   SDValue N1 = N->getOperand(1);
17116   SDLoc DL(N);
17117
17118   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17119       isAllOnes(N0.getOperand(1)))
17120     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17121
17122   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17123       isAllOnes(N1.getOperand(1)))
17124     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17125
17126   return SDValue();
17127 }
17128
17129 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17130 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17131                                   TargetLowering::DAGCombinerInfo &DCI,
17132                                   const X86Subtarget *Subtarget) {
17133   LoadSDNode *Ld = cast<LoadSDNode>(N);
17134   EVT RegVT = Ld->getValueType(0);
17135   EVT MemVT = Ld->getMemoryVT();
17136   SDLoc dl(Ld);
17137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17138   unsigned RegSz = RegVT.getSizeInBits();
17139
17140   // On Sandybridge unaligned 256bit loads are inefficient.
17141   ISD::LoadExtType Ext = Ld->getExtensionType();
17142   unsigned Alignment = Ld->getAlignment();
17143   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17144   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17145       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17146     unsigned NumElems = RegVT.getVectorNumElements();
17147     if (NumElems < 2)
17148       return SDValue();
17149
17150     SDValue Ptr = Ld->getBasePtr();
17151     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17152
17153     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17154                                   NumElems/2);
17155     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17156                                 Ld->getPointerInfo(), Ld->isVolatile(),
17157                                 Ld->isNonTemporal(), Ld->isInvariant(),
17158                                 Alignment);
17159     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17160     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17161                                 Ld->getPointerInfo(), Ld->isVolatile(),
17162                                 Ld->isNonTemporal(), Ld->isInvariant(),
17163                                 std::min(16U, Alignment));
17164     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17165                              Load1.getValue(1),
17166                              Load2.getValue(1));
17167
17168     SDValue NewVec = DAG.getUNDEF(RegVT);
17169     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17170     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17171     return DCI.CombineTo(N, NewVec, TF, true);
17172   }
17173
17174   // If this is a vector EXT Load then attempt to optimize it using a
17175   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17176   // expansion is still better than scalar code.
17177   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17178   // emit a shuffle and a arithmetic shift.
17179   // TODO: It is possible to support ZExt by zeroing the undef values
17180   // during the shuffle phase or after the shuffle.
17181   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17182       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17183     assert(MemVT != RegVT && "Cannot extend to the same type");
17184     assert(MemVT.isVector() && "Must load a vector from memory");
17185
17186     unsigned NumElems = RegVT.getVectorNumElements();
17187     unsigned MemSz = MemVT.getSizeInBits();
17188     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17189
17190     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17191       return SDValue();
17192
17193     // All sizes must be a power of two.
17194     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17195       return SDValue();
17196
17197     // Attempt to load the original value using scalar loads.
17198     // Find the largest scalar type that divides the total loaded size.
17199     MVT SclrLoadTy = MVT::i8;
17200     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17201          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17202       MVT Tp = (MVT::SimpleValueType)tp;
17203       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17204         SclrLoadTy = Tp;
17205       }
17206     }
17207
17208     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17209     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17210         (64 <= MemSz))
17211       SclrLoadTy = MVT::f64;
17212
17213     // Calculate the number of scalar loads that we need to perform
17214     // in order to load our vector from memory.
17215     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17216     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17217       return SDValue();
17218
17219     unsigned loadRegZize = RegSz;
17220     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17221       loadRegZize /= 2;
17222
17223     // Represent our vector as a sequence of elements which are the
17224     // largest scalar that we can load.
17225     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17226       loadRegZize/SclrLoadTy.getSizeInBits());
17227
17228     // Represent the data using the same element type that is stored in
17229     // memory. In practice, we ''widen'' MemVT.
17230     EVT WideVecVT =
17231           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17232                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17233
17234     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17235       "Invalid vector type");
17236
17237     // We can't shuffle using an illegal type.
17238     if (!TLI.isTypeLegal(WideVecVT))
17239       return SDValue();
17240
17241     SmallVector<SDValue, 8> Chains;
17242     SDValue Ptr = Ld->getBasePtr();
17243     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17244                                         TLI.getPointerTy());
17245     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17246
17247     for (unsigned i = 0; i < NumLoads; ++i) {
17248       // Perform a single load.
17249       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17250                                        Ptr, Ld->getPointerInfo(),
17251                                        Ld->isVolatile(), Ld->isNonTemporal(),
17252                                        Ld->isInvariant(), Ld->getAlignment());
17253       Chains.push_back(ScalarLoad.getValue(1));
17254       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17255       // another round of DAGCombining.
17256       if (i == 0)
17257         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17258       else
17259         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17260                           ScalarLoad, DAG.getIntPtrConstant(i));
17261
17262       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17263     }
17264
17265     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17266                                Chains.size());
17267
17268     // Bitcast the loaded value to a vector of the original element type, in
17269     // the size of the target vector type.
17270     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17271     unsigned SizeRatio = RegSz/MemSz;
17272
17273     if (Ext == ISD::SEXTLOAD) {
17274       // If we have SSE4.1 we can directly emit a VSEXT node.
17275       if (Subtarget->hasSSE41()) {
17276         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17277         return DCI.CombineTo(N, Sext, TF, true);
17278       }
17279
17280       // Otherwise we'll shuffle the small elements in the high bits of the
17281       // larger type and perform an arithmetic shift. If the shift is not legal
17282       // it's better to scalarize.
17283       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17284         return SDValue();
17285
17286       // Redistribute the loaded elements into the different locations.
17287       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17288       for (unsigned i = 0; i != NumElems; ++i)
17289         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17290
17291       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17292                                            DAG.getUNDEF(WideVecVT),
17293                                            &ShuffleVec[0]);
17294
17295       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17296
17297       // Build the arithmetic shift.
17298       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17299                      MemVT.getVectorElementType().getSizeInBits();
17300       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17301                           DAG.getConstant(Amt, RegVT));
17302
17303       return DCI.CombineTo(N, Shuff, TF, true);
17304     }
17305
17306     // Redistribute the loaded elements into the different locations.
17307     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17308     for (unsigned i = 0; i != NumElems; ++i)
17309       ShuffleVec[i*SizeRatio] = i;
17310
17311     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17312                                          DAG.getUNDEF(WideVecVT),
17313                                          &ShuffleVec[0]);
17314
17315     // Bitcast to the requested type.
17316     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17317     // Replace the original load with the new sequence
17318     // and return the new chain.
17319     return DCI.CombineTo(N, Shuff, TF, true);
17320   }
17321
17322   return SDValue();
17323 }
17324
17325 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17326 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17327                                    const X86Subtarget *Subtarget) {
17328   StoreSDNode *St = cast<StoreSDNode>(N);
17329   EVT VT = St->getValue().getValueType();
17330   EVT StVT = St->getMemoryVT();
17331   SDLoc dl(St);
17332   SDValue StoredVal = St->getOperand(1);
17333   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17334
17335   // If we are saving a concatenation of two XMM registers, perform two stores.
17336   // On Sandy Bridge, 256-bit memory operations are executed by two
17337   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17338   // memory  operation.
17339   unsigned Alignment = St->getAlignment();
17340   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17341   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17342       StVT == VT && !IsAligned) {
17343     unsigned NumElems = VT.getVectorNumElements();
17344     if (NumElems < 2)
17345       return SDValue();
17346
17347     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17348     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17349
17350     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17351     SDValue Ptr0 = St->getBasePtr();
17352     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17353
17354     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17355                                 St->getPointerInfo(), St->isVolatile(),
17356                                 St->isNonTemporal(), Alignment);
17357     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17358                                 St->getPointerInfo(), St->isVolatile(),
17359                                 St->isNonTemporal(),
17360                                 std::min(16U, Alignment));
17361     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17362   }
17363
17364   // Optimize trunc store (of multiple scalars) to shuffle and store.
17365   // First, pack all of the elements in one place. Next, store to memory
17366   // in fewer chunks.
17367   if (St->isTruncatingStore() && VT.isVector()) {
17368     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17369     unsigned NumElems = VT.getVectorNumElements();
17370     assert(StVT != VT && "Cannot truncate to the same type");
17371     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17372     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17373
17374     // From, To sizes and ElemCount must be pow of two
17375     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17376     // We are going to use the original vector elt for storing.
17377     // Accumulated smaller vector elements must be a multiple of the store size.
17378     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17379
17380     unsigned SizeRatio  = FromSz / ToSz;
17381
17382     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17383
17384     // Create a type on which we perform the shuffle
17385     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17386             StVT.getScalarType(), NumElems*SizeRatio);
17387
17388     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17389
17390     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17391     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17392     for (unsigned i = 0; i != NumElems; ++i)
17393       ShuffleVec[i] = i * SizeRatio;
17394
17395     // Can't shuffle using an illegal type.
17396     if (!TLI.isTypeLegal(WideVecVT))
17397       return SDValue();
17398
17399     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17400                                          DAG.getUNDEF(WideVecVT),
17401                                          &ShuffleVec[0]);
17402     // At this point all of the data is stored at the bottom of the
17403     // register. We now need to save it to mem.
17404
17405     // Find the largest store unit
17406     MVT StoreType = MVT::i8;
17407     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17408          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17409       MVT Tp = (MVT::SimpleValueType)tp;
17410       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17411         StoreType = Tp;
17412     }
17413
17414     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17415     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17416         (64 <= NumElems * ToSz))
17417       StoreType = MVT::f64;
17418
17419     // Bitcast the original vector into a vector of store-size units
17420     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17421             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17422     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17423     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17424     SmallVector<SDValue, 8> Chains;
17425     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17426                                         TLI.getPointerTy());
17427     SDValue Ptr = St->getBasePtr();
17428
17429     // Perform one or more big stores into memory.
17430     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17431       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17432                                    StoreType, ShuffWide,
17433                                    DAG.getIntPtrConstant(i));
17434       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17435                                 St->getPointerInfo(), St->isVolatile(),
17436                                 St->isNonTemporal(), St->getAlignment());
17437       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17438       Chains.push_back(Ch);
17439     }
17440
17441     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17442                                Chains.size());
17443   }
17444
17445   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17446   // the FP state in cases where an emms may be missing.
17447   // A preferable solution to the general problem is to figure out the right
17448   // places to insert EMMS.  This qualifies as a quick hack.
17449
17450   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17451   if (VT.getSizeInBits() != 64)
17452     return SDValue();
17453
17454   const Function *F = DAG.getMachineFunction().getFunction();
17455   bool NoImplicitFloatOps = F->getAttributes().
17456     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17457   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17458                      && Subtarget->hasSSE2();
17459   if ((VT.isVector() ||
17460        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17461       isa<LoadSDNode>(St->getValue()) &&
17462       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17463       St->getChain().hasOneUse() && !St->isVolatile()) {
17464     SDNode* LdVal = St->getValue().getNode();
17465     LoadSDNode *Ld = 0;
17466     int TokenFactorIndex = -1;
17467     SmallVector<SDValue, 8> Ops;
17468     SDNode* ChainVal = St->getChain().getNode();
17469     // Must be a store of a load.  We currently handle two cases:  the load
17470     // is a direct child, and it's under an intervening TokenFactor.  It is
17471     // possible to dig deeper under nested TokenFactors.
17472     if (ChainVal == LdVal)
17473       Ld = cast<LoadSDNode>(St->getChain());
17474     else if (St->getValue().hasOneUse() &&
17475              ChainVal->getOpcode() == ISD::TokenFactor) {
17476       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17477         if (ChainVal->getOperand(i).getNode() == LdVal) {
17478           TokenFactorIndex = i;
17479           Ld = cast<LoadSDNode>(St->getValue());
17480         } else
17481           Ops.push_back(ChainVal->getOperand(i));
17482       }
17483     }
17484
17485     if (!Ld || !ISD::isNormalLoad(Ld))
17486       return SDValue();
17487
17488     // If this is not the MMX case, i.e. we are just turning i64 load/store
17489     // into f64 load/store, avoid the transformation if there are multiple
17490     // uses of the loaded value.
17491     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17492       return SDValue();
17493
17494     SDLoc LdDL(Ld);
17495     SDLoc StDL(N);
17496     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17497     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17498     // pair instead.
17499     if (Subtarget->is64Bit() || F64IsLegal) {
17500       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17501       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17502                                   Ld->getPointerInfo(), Ld->isVolatile(),
17503                                   Ld->isNonTemporal(), Ld->isInvariant(),
17504                                   Ld->getAlignment());
17505       SDValue NewChain = NewLd.getValue(1);
17506       if (TokenFactorIndex != -1) {
17507         Ops.push_back(NewChain);
17508         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17509                                Ops.size());
17510       }
17511       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17512                           St->getPointerInfo(),
17513                           St->isVolatile(), St->isNonTemporal(),
17514                           St->getAlignment());
17515     }
17516
17517     // Otherwise, lower to two pairs of 32-bit loads / stores.
17518     SDValue LoAddr = Ld->getBasePtr();
17519     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17520                                  DAG.getConstant(4, MVT::i32));
17521
17522     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17523                                Ld->getPointerInfo(),
17524                                Ld->isVolatile(), Ld->isNonTemporal(),
17525                                Ld->isInvariant(), Ld->getAlignment());
17526     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17527                                Ld->getPointerInfo().getWithOffset(4),
17528                                Ld->isVolatile(), Ld->isNonTemporal(),
17529                                Ld->isInvariant(),
17530                                MinAlign(Ld->getAlignment(), 4));
17531
17532     SDValue NewChain = LoLd.getValue(1);
17533     if (TokenFactorIndex != -1) {
17534       Ops.push_back(LoLd);
17535       Ops.push_back(HiLd);
17536       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17537                              Ops.size());
17538     }
17539
17540     LoAddr = St->getBasePtr();
17541     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17542                          DAG.getConstant(4, MVT::i32));
17543
17544     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17545                                 St->getPointerInfo(),
17546                                 St->isVolatile(), St->isNonTemporal(),
17547                                 St->getAlignment());
17548     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17549                                 St->getPointerInfo().getWithOffset(4),
17550                                 St->isVolatile(),
17551                                 St->isNonTemporal(),
17552                                 MinAlign(St->getAlignment(), 4));
17553     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17554   }
17555   return SDValue();
17556 }
17557
17558 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17559 /// and return the operands for the horizontal operation in LHS and RHS.  A
17560 /// horizontal operation performs the binary operation on successive elements
17561 /// of its first operand, then on successive elements of its second operand,
17562 /// returning the resulting values in a vector.  For example, if
17563 ///   A = < float a0, float a1, float a2, float a3 >
17564 /// and
17565 ///   B = < float b0, float b1, float b2, float b3 >
17566 /// then the result of doing a horizontal operation on A and B is
17567 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17568 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17569 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17570 /// set to A, RHS to B, and the routine returns 'true'.
17571 /// Note that the binary operation should have the property that if one of the
17572 /// operands is UNDEF then the result is UNDEF.
17573 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17574   // Look for the following pattern: if
17575   //   A = < float a0, float a1, float a2, float a3 >
17576   //   B = < float b0, float b1, float b2, float b3 >
17577   // and
17578   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17579   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17580   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17581   // which is A horizontal-op B.
17582
17583   // At least one of the operands should be a vector shuffle.
17584   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17585       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17586     return false;
17587
17588   EVT VT = LHS.getValueType();
17589
17590   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17591          "Unsupported vector type for horizontal add/sub");
17592
17593   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17594   // operate independently on 128-bit lanes.
17595   unsigned NumElts = VT.getVectorNumElements();
17596   unsigned NumLanes = VT.getSizeInBits()/128;
17597   unsigned NumLaneElts = NumElts / NumLanes;
17598   assert((NumLaneElts % 2 == 0) &&
17599          "Vector type should have an even number of elements in each lane");
17600   unsigned HalfLaneElts = NumLaneElts/2;
17601
17602   // View LHS in the form
17603   //   LHS = VECTOR_SHUFFLE A, B, LMask
17604   // If LHS is not a shuffle then pretend it is the shuffle
17605   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17606   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17607   // type VT.
17608   SDValue A, B;
17609   SmallVector<int, 16> LMask(NumElts);
17610   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17611     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17612       A = LHS.getOperand(0);
17613     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17614       B = LHS.getOperand(1);
17615     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17616     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17617   } else {
17618     if (LHS.getOpcode() != ISD::UNDEF)
17619       A = LHS;
17620     for (unsigned i = 0; i != NumElts; ++i)
17621       LMask[i] = i;
17622   }
17623
17624   // Likewise, view RHS in the form
17625   //   RHS = VECTOR_SHUFFLE C, D, RMask
17626   SDValue C, D;
17627   SmallVector<int, 16> RMask(NumElts);
17628   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17629     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17630       C = RHS.getOperand(0);
17631     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17632       D = RHS.getOperand(1);
17633     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17634     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17635   } else {
17636     if (RHS.getOpcode() != ISD::UNDEF)
17637       C = RHS;
17638     for (unsigned i = 0; i != NumElts; ++i)
17639       RMask[i] = i;
17640   }
17641
17642   // Check that the shuffles are both shuffling the same vectors.
17643   if (!(A == C && B == D) && !(A == D && B == C))
17644     return false;
17645
17646   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17647   if (!A.getNode() && !B.getNode())
17648     return false;
17649
17650   // If A and B occur in reverse order in RHS, then "swap" them (which means
17651   // rewriting the mask).
17652   if (A != C)
17653     CommuteVectorShuffleMask(RMask, NumElts);
17654
17655   // At this point LHS and RHS are equivalent to
17656   //   LHS = VECTOR_SHUFFLE A, B, LMask
17657   //   RHS = VECTOR_SHUFFLE A, B, RMask
17658   // Check that the masks correspond to performing a horizontal operation.
17659   for (unsigned i = 0; i != NumElts; ++i) {
17660     int LIdx = LMask[i], RIdx = RMask[i];
17661
17662     // Ignore any UNDEF components.
17663     if (LIdx < 0 || RIdx < 0 ||
17664         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17665         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17666       continue;
17667
17668     // Check that successive elements are being operated on.  If not, this is
17669     // not a horizontal operation.
17670     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17671     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17672     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17673     if (!(LIdx == Index && RIdx == Index + 1) &&
17674         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17675       return false;
17676   }
17677
17678   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17679   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17680   return true;
17681 }
17682
17683 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17684 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17685                                   const X86Subtarget *Subtarget) {
17686   EVT VT = N->getValueType(0);
17687   SDValue LHS = N->getOperand(0);
17688   SDValue RHS = N->getOperand(1);
17689
17690   // Try to synthesize horizontal adds from adds of shuffles.
17691   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17692        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17693       isHorizontalBinOp(LHS, RHS, true))
17694     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17695   return SDValue();
17696 }
17697
17698 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17699 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17700                                   const X86Subtarget *Subtarget) {
17701   EVT VT = N->getValueType(0);
17702   SDValue LHS = N->getOperand(0);
17703   SDValue RHS = N->getOperand(1);
17704
17705   // Try to synthesize horizontal subs from subs of shuffles.
17706   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17707        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17708       isHorizontalBinOp(LHS, RHS, false))
17709     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17710   return SDValue();
17711 }
17712
17713 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17714 /// X86ISD::FXOR nodes.
17715 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17716   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17717   // F[X]OR(0.0, x) -> x
17718   // F[X]OR(x, 0.0) -> x
17719   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17720     if (C->getValueAPF().isPosZero())
17721       return N->getOperand(1);
17722   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17723     if (C->getValueAPF().isPosZero())
17724       return N->getOperand(0);
17725   return SDValue();
17726 }
17727
17728 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17729 /// X86ISD::FMAX nodes.
17730 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17731   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17732
17733   // Only perform optimizations if UnsafeMath is used.
17734   if (!DAG.getTarget().Options.UnsafeFPMath)
17735     return SDValue();
17736
17737   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17738   // into FMINC and FMAXC, which are Commutative operations.
17739   unsigned NewOp = 0;
17740   switch (N->getOpcode()) {
17741     default: llvm_unreachable("unknown opcode");
17742     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17743     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17744   }
17745
17746   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17747                      N->getOperand(0), N->getOperand(1));
17748 }
17749
17750 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17751 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17752   // FAND(0.0, x) -> 0.0
17753   // FAND(x, 0.0) -> 0.0
17754   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17755     if (C->getValueAPF().isPosZero())
17756       return N->getOperand(0);
17757   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17758     if (C->getValueAPF().isPosZero())
17759       return N->getOperand(1);
17760   return SDValue();
17761 }
17762
17763 static SDValue PerformBTCombine(SDNode *N,
17764                                 SelectionDAG &DAG,
17765                                 TargetLowering::DAGCombinerInfo &DCI) {
17766   // BT ignores high bits in the bit index operand.
17767   SDValue Op1 = N->getOperand(1);
17768   if (Op1.hasOneUse()) {
17769     unsigned BitWidth = Op1.getValueSizeInBits();
17770     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17771     APInt KnownZero, KnownOne;
17772     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17773                                           !DCI.isBeforeLegalizeOps());
17774     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17775     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17776         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17777       DCI.CommitTargetLoweringOpt(TLO);
17778   }
17779   return SDValue();
17780 }
17781
17782 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17783   SDValue Op = N->getOperand(0);
17784   if (Op.getOpcode() == ISD::BITCAST)
17785     Op = Op.getOperand(0);
17786   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17787   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17788       VT.getVectorElementType().getSizeInBits() ==
17789       OpVT.getVectorElementType().getSizeInBits()) {
17790     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17791   }
17792   return SDValue();
17793 }
17794
17795 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17796                                                const X86Subtarget *Subtarget) {
17797   EVT VT = N->getValueType(0);
17798   if (!VT.isVector())
17799     return SDValue();
17800
17801   SDValue N0 = N->getOperand(0);
17802   SDValue N1 = N->getOperand(1);
17803   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17804   SDLoc dl(N);
17805
17806   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17807   // both SSE and AVX2 since there is no sign-extended shift right
17808   // operation on a vector with 64-bit elements.
17809   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17810   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17811   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17812       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17813     SDValue N00 = N0.getOperand(0);
17814
17815     // EXTLOAD has a better solution on AVX2,
17816     // it may be replaced with X86ISD::VSEXT node.
17817     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17818       if (!ISD::isNormalLoad(N00.getNode()))
17819         return SDValue();
17820
17821     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17822         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17823                                   N00, N1);
17824       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17825     }
17826   }
17827   return SDValue();
17828 }
17829
17830 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17831                                   TargetLowering::DAGCombinerInfo &DCI,
17832                                   const X86Subtarget *Subtarget) {
17833   if (!DCI.isBeforeLegalizeOps())
17834     return SDValue();
17835
17836   if (!Subtarget->hasFp256())
17837     return SDValue();
17838
17839   EVT VT = N->getValueType(0);
17840   if (VT.isVector() && VT.getSizeInBits() == 256) {
17841     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17842     if (R.getNode())
17843       return R;
17844   }
17845
17846   return SDValue();
17847 }
17848
17849 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17850                                  const X86Subtarget* Subtarget) {
17851   SDLoc dl(N);
17852   EVT VT = N->getValueType(0);
17853
17854   // Let legalize expand this if it isn't a legal type yet.
17855   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17856     return SDValue();
17857
17858   EVT ScalarVT = VT.getScalarType();
17859   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17860       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17861     return SDValue();
17862
17863   SDValue A = N->getOperand(0);
17864   SDValue B = N->getOperand(1);
17865   SDValue C = N->getOperand(2);
17866
17867   bool NegA = (A.getOpcode() == ISD::FNEG);
17868   bool NegB = (B.getOpcode() == ISD::FNEG);
17869   bool NegC = (C.getOpcode() == ISD::FNEG);
17870
17871   // Negative multiplication when NegA xor NegB
17872   bool NegMul = (NegA != NegB);
17873   if (NegA)
17874     A = A.getOperand(0);
17875   if (NegB)
17876     B = B.getOperand(0);
17877   if (NegC)
17878     C = C.getOperand(0);
17879
17880   unsigned Opcode;
17881   if (!NegMul)
17882     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17883   else
17884     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17885
17886   return DAG.getNode(Opcode, dl, VT, A, B, C);
17887 }
17888
17889 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17890                                   TargetLowering::DAGCombinerInfo &DCI,
17891                                   const X86Subtarget *Subtarget) {
17892   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17893   //           (and (i32 x86isd::setcc_carry), 1)
17894   // This eliminates the zext. This transformation is necessary because
17895   // ISD::SETCC is always legalized to i8.
17896   SDLoc dl(N);
17897   SDValue N0 = N->getOperand(0);
17898   EVT VT = N->getValueType(0);
17899
17900   if (N0.getOpcode() == ISD::AND &&
17901       N0.hasOneUse() &&
17902       N0.getOperand(0).hasOneUse()) {
17903     SDValue N00 = N0.getOperand(0);
17904     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17905       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17906       if (!C || C->getZExtValue() != 1)
17907         return SDValue();
17908       return DAG.getNode(ISD::AND, dl, VT,
17909                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17910                                      N00.getOperand(0), N00.getOperand(1)),
17911                          DAG.getConstant(1, VT));
17912     }
17913   }
17914
17915   if (VT.is256BitVector()) {
17916     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17917     if (R.getNode())
17918       return R;
17919   }
17920
17921   return SDValue();
17922 }
17923
17924 // Optimize x == -y --> x+y == 0
17925 //          x != -y --> x+y != 0
17926 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17927   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17928   SDValue LHS = N->getOperand(0);
17929   SDValue RHS = N->getOperand(1);
17930
17931   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17932     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17933       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17934         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17935                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17936         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17937                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17938       }
17939   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17941       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17942         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17943                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17944         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17945                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17946       }
17947   return SDValue();
17948 }
17949
17950 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17951 // as "sbb reg,reg", since it can be extended without zext and produces
17952 // an all-ones bit which is more useful than 0/1 in some cases.
17953 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17954   return DAG.getNode(ISD::AND, DL, MVT::i8,
17955                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17956                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17957                      DAG.getConstant(1, MVT::i8));
17958 }
17959
17960 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17961 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17962                                    TargetLowering::DAGCombinerInfo &DCI,
17963                                    const X86Subtarget *Subtarget) {
17964   SDLoc DL(N);
17965   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17966   SDValue EFLAGS = N->getOperand(1);
17967
17968   if (CC == X86::COND_A) {
17969     // Try to convert COND_A into COND_B in an attempt to facilitate
17970     // materializing "setb reg".
17971     //
17972     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17973     // cannot take an immediate as its first operand.
17974     //
17975     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17976         EFLAGS.getValueType().isInteger() &&
17977         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17978       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17979                                    EFLAGS.getNode()->getVTList(),
17980                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17981       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17982       return MaterializeSETB(DL, NewEFLAGS, DAG);
17983     }
17984   }
17985
17986   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17987   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17988   // cases.
17989   if (CC == X86::COND_B)
17990     return MaterializeSETB(DL, EFLAGS, DAG);
17991
17992   SDValue Flags;
17993
17994   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17995   if (Flags.getNode()) {
17996     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17997     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17998   }
17999
18000   return SDValue();
18001 }
18002
18003 // Optimize branch condition evaluation.
18004 //
18005 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18006                                     TargetLowering::DAGCombinerInfo &DCI,
18007                                     const X86Subtarget *Subtarget) {
18008   SDLoc DL(N);
18009   SDValue Chain = N->getOperand(0);
18010   SDValue Dest = N->getOperand(1);
18011   SDValue EFLAGS = N->getOperand(3);
18012   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18013
18014   SDValue Flags;
18015
18016   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18017   if (Flags.getNode()) {
18018     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18019     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18020                        Flags);
18021   }
18022
18023   return SDValue();
18024 }
18025
18026 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18027                                         const X86TargetLowering *XTLI) {
18028   SDValue Op0 = N->getOperand(0);
18029   EVT InVT = Op0->getValueType(0);
18030
18031   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18032   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18033     SDLoc dl(N);
18034     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18035     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18036     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18037   }
18038
18039   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18040   // a 32-bit target where SSE doesn't support i64->FP operations.
18041   if (Op0.getOpcode() == ISD::LOAD) {
18042     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18043     EVT VT = Ld->getValueType(0);
18044     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18045         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18046         !XTLI->getSubtarget()->is64Bit() &&
18047         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18048       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18049                                           Ld->getChain(), Op0, DAG);
18050       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18051       return FILDChain;
18052     }
18053   }
18054   return SDValue();
18055 }
18056
18057 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18058 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18059                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18060   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18061   // the result is either zero or one (depending on the input carry bit).
18062   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18063   if (X86::isZeroNode(N->getOperand(0)) &&
18064       X86::isZeroNode(N->getOperand(1)) &&
18065       // We don't have a good way to replace an EFLAGS use, so only do this when
18066       // dead right now.
18067       SDValue(N, 1).use_empty()) {
18068     SDLoc DL(N);
18069     EVT VT = N->getValueType(0);
18070     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18071     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18072                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18073                                            DAG.getConstant(X86::COND_B,MVT::i8),
18074                                            N->getOperand(2)),
18075                                DAG.getConstant(1, VT));
18076     return DCI.CombineTo(N, Res1, CarryOut);
18077   }
18078
18079   return SDValue();
18080 }
18081
18082 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18083 //      (add Y, (setne X, 0)) -> sbb -1, Y
18084 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18085 //      (sub (setne X, 0), Y) -> adc -1, Y
18086 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18087   SDLoc DL(N);
18088
18089   // Look through ZExts.
18090   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18091   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18092     return SDValue();
18093
18094   SDValue SetCC = Ext.getOperand(0);
18095   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18096     return SDValue();
18097
18098   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18099   if (CC != X86::COND_E && CC != X86::COND_NE)
18100     return SDValue();
18101
18102   SDValue Cmp = SetCC.getOperand(1);
18103   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18104       !X86::isZeroNode(Cmp.getOperand(1)) ||
18105       !Cmp.getOperand(0).getValueType().isInteger())
18106     return SDValue();
18107
18108   SDValue CmpOp0 = Cmp.getOperand(0);
18109   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18110                                DAG.getConstant(1, CmpOp0.getValueType()));
18111
18112   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18113   if (CC == X86::COND_NE)
18114     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18115                        DL, OtherVal.getValueType(), OtherVal,
18116                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18117   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18118                      DL, OtherVal.getValueType(), OtherVal,
18119                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18120 }
18121
18122 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18123 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18124                                  const X86Subtarget *Subtarget) {
18125   EVT VT = N->getValueType(0);
18126   SDValue Op0 = N->getOperand(0);
18127   SDValue Op1 = N->getOperand(1);
18128
18129   // Try to synthesize horizontal adds from adds of shuffles.
18130   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18131        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18132       isHorizontalBinOp(Op0, Op1, true))
18133     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18134
18135   return OptimizeConditionalInDecrement(N, DAG);
18136 }
18137
18138 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18139                                  const X86Subtarget *Subtarget) {
18140   SDValue Op0 = N->getOperand(0);
18141   SDValue Op1 = N->getOperand(1);
18142
18143   // X86 can't encode an immediate LHS of a sub. See if we can push the
18144   // negation into a preceding instruction.
18145   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18146     // If the RHS of the sub is a XOR with one use and a constant, invert the
18147     // immediate. Then add one to the LHS of the sub so we can turn
18148     // X-Y -> X+~Y+1, saving one register.
18149     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18150         isa<ConstantSDNode>(Op1.getOperand(1))) {
18151       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18152       EVT VT = Op0.getValueType();
18153       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18154                                    Op1.getOperand(0),
18155                                    DAG.getConstant(~XorC, VT));
18156       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18157                          DAG.getConstant(C->getAPIntValue()+1, VT));
18158     }
18159   }
18160
18161   // Try to synthesize horizontal adds from adds of shuffles.
18162   EVT VT = N->getValueType(0);
18163   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18164        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18165       isHorizontalBinOp(Op0, Op1, true))
18166     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18167
18168   return OptimizeConditionalInDecrement(N, DAG);
18169 }
18170
18171 /// performVZEXTCombine - Performs build vector combines
18172 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18173                                         TargetLowering::DAGCombinerInfo &DCI,
18174                                         const X86Subtarget *Subtarget) {
18175   // (vzext (bitcast (vzext (x)) -> (vzext x)
18176   SDValue In = N->getOperand(0);
18177   while (In.getOpcode() == ISD::BITCAST)
18178     In = In.getOperand(0);
18179
18180   if (In.getOpcode() != X86ISD::VZEXT)
18181     return SDValue();
18182
18183   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18184                      In.getOperand(0));
18185 }
18186
18187 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18188                                              DAGCombinerInfo &DCI) const {
18189   SelectionDAG &DAG = DCI.DAG;
18190   switch (N->getOpcode()) {
18191   default: break;
18192   case ISD::EXTRACT_VECTOR_ELT:
18193     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18194   case ISD::VSELECT:
18195   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18196   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18197   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18198   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18199   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18200   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18201   case ISD::SHL:
18202   case ISD::SRA:
18203   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18204   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18205   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18206   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18207   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18208   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18209   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18210   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18211   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18212   case X86ISD::FXOR:
18213   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18214   case X86ISD::FMIN:
18215   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18216   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18217   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18218   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18219   case ISD::ANY_EXTEND:
18220   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18221   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18222   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18223   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18224   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18225   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18226   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18227   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18228   case X86ISD::SHUFP:       // Handle all target specific shuffles
18229   case X86ISD::PALIGNR:
18230   case X86ISD::UNPCKH:
18231   case X86ISD::UNPCKL:
18232   case X86ISD::MOVHLPS:
18233   case X86ISD::MOVLHPS:
18234   case X86ISD::PSHUFD:
18235   case X86ISD::PSHUFHW:
18236   case X86ISD::PSHUFLW:
18237   case X86ISD::MOVSS:
18238   case X86ISD::MOVSD:
18239   case X86ISD::VPERMILP:
18240   case X86ISD::VPERM2X128:
18241   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18242   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18243   }
18244
18245   return SDValue();
18246 }
18247
18248 /// isTypeDesirableForOp - Return true if the target has native support for
18249 /// the specified value type and it is 'desirable' to use the type for the
18250 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18251 /// instruction encodings are longer and some i16 instructions are slow.
18252 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18253   if (!isTypeLegal(VT))
18254     return false;
18255   if (VT != MVT::i16)
18256     return true;
18257
18258   switch (Opc) {
18259   default:
18260     return true;
18261   case ISD::LOAD:
18262   case ISD::SIGN_EXTEND:
18263   case ISD::ZERO_EXTEND:
18264   case ISD::ANY_EXTEND:
18265   case ISD::SHL:
18266   case ISD::SRL:
18267   case ISD::SUB:
18268   case ISD::ADD:
18269   case ISD::MUL:
18270   case ISD::AND:
18271   case ISD::OR:
18272   case ISD::XOR:
18273     return false;
18274   }
18275 }
18276
18277 /// IsDesirableToPromoteOp - This method query the target whether it is
18278 /// beneficial for dag combiner to promote the specified node. If true, it
18279 /// should return the desired promotion type by reference.
18280 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18281   EVT VT = Op.getValueType();
18282   if (VT != MVT::i16)
18283     return false;
18284
18285   bool Promote = false;
18286   bool Commute = false;
18287   switch (Op.getOpcode()) {
18288   default: break;
18289   case ISD::LOAD: {
18290     LoadSDNode *LD = cast<LoadSDNode>(Op);
18291     // If the non-extending load has a single use and it's not live out, then it
18292     // might be folded.
18293     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18294                                                      Op.hasOneUse()*/) {
18295       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18296              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18297         // The only case where we'd want to promote LOAD (rather then it being
18298         // promoted as an operand is when it's only use is liveout.
18299         if (UI->getOpcode() != ISD::CopyToReg)
18300           return false;
18301       }
18302     }
18303     Promote = true;
18304     break;
18305   }
18306   case ISD::SIGN_EXTEND:
18307   case ISD::ZERO_EXTEND:
18308   case ISD::ANY_EXTEND:
18309     Promote = true;
18310     break;
18311   case ISD::SHL:
18312   case ISD::SRL: {
18313     SDValue N0 = Op.getOperand(0);
18314     // Look out for (store (shl (load), x)).
18315     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18316       return false;
18317     Promote = true;
18318     break;
18319   }
18320   case ISD::ADD:
18321   case ISD::MUL:
18322   case ISD::AND:
18323   case ISD::OR:
18324   case ISD::XOR:
18325     Commute = true;
18326     // fallthrough
18327   case ISD::SUB: {
18328     SDValue N0 = Op.getOperand(0);
18329     SDValue N1 = Op.getOperand(1);
18330     if (!Commute && MayFoldLoad(N1))
18331       return false;
18332     // Avoid disabling potential load folding opportunities.
18333     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18334       return false;
18335     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18336       return false;
18337     Promote = true;
18338   }
18339   }
18340
18341   PVT = MVT::i32;
18342   return Promote;
18343 }
18344
18345 //===----------------------------------------------------------------------===//
18346 //                           X86 Inline Assembly Support
18347 //===----------------------------------------------------------------------===//
18348
18349 namespace {
18350   // Helper to match a string separated by whitespace.
18351   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18352     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18353
18354     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18355       StringRef piece(*args[i]);
18356       if (!s.startswith(piece)) // Check if the piece matches.
18357         return false;
18358
18359       s = s.substr(piece.size());
18360       StringRef::size_type pos = s.find_first_not_of(" \t");
18361       if (pos == 0) // We matched a prefix.
18362         return false;
18363
18364       s = s.substr(pos);
18365     }
18366
18367     return s.empty();
18368   }
18369   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18370 }
18371
18372 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18373   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18374
18375   std::string AsmStr = IA->getAsmString();
18376
18377   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18378   if (!Ty || Ty->getBitWidth() % 16 != 0)
18379     return false;
18380
18381   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18382   SmallVector<StringRef, 4> AsmPieces;
18383   SplitString(AsmStr, AsmPieces, ";\n");
18384
18385   switch (AsmPieces.size()) {
18386   default: return false;
18387   case 1:
18388     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18389     // we will turn this bswap into something that will be lowered to logical
18390     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18391     // lower so don't worry about this.
18392     // bswap $0
18393     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18394         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18395         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18396         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18397         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18398         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18399       // No need to check constraints, nothing other than the equivalent of
18400       // "=r,0" would be valid here.
18401       return IntrinsicLowering::LowerToByteSwap(CI);
18402     }
18403
18404     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18405     if (CI->getType()->isIntegerTy(16) &&
18406         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18407         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18408          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18409       AsmPieces.clear();
18410       const std::string &ConstraintsStr = IA->getConstraintString();
18411       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18412       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18413       if (AsmPieces.size() == 4 &&
18414           AsmPieces[0] == "~{cc}" &&
18415           AsmPieces[1] == "~{dirflag}" &&
18416           AsmPieces[2] == "~{flags}" &&
18417           AsmPieces[3] == "~{fpsr}")
18418       return IntrinsicLowering::LowerToByteSwap(CI);
18419     }
18420     break;
18421   case 3:
18422     if (CI->getType()->isIntegerTy(32) &&
18423         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18424         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18425         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18426         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18427       AsmPieces.clear();
18428       const std::string &ConstraintsStr = IA->getConstraintString();
18429       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18430       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18431       if (AsmPieces.size() == 4 &&
18432           AsmPieces[0] == "~{cc}" &&
18433           AsmPieces[1] == "~{dirflag}" &&
18434           AsmPieces[2] == "~{flags}" &&
18435           AsmPieces[3] == "~{fpsr}")
18436         return IntrinsicLowering::LowerToByteSwap(CI);
18437     }
18438
18439     if (CI->getType()->isIntegerTy(64)) {
18440       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18441       if (Constraints.size() >= 2 &&
18442           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18443           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18444         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18445         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18446             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18447             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18448           return IntrinsicLowering::LowerToByteSwap(CI);
18449       }
18450     }
18451     break;
18452   }
18453   return false;
18454 }
18455
18456 /// getConstraintType - Given a constraint letter, return the type of
18457 /// constraint it is for this target.
18458 X86TargetLowering::ConstraintType
18459 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18460   if (Constraint.size() == 1) {
18461     switch (Constraint[0]) {
18462     case 'R':
18463     case 'q':
18464     case 'Q':
18465     case 'f':
18466     case 't':
18467     case 'u':
18468     case 'y':
18469     case 'x':
18470     case 'Y':
18471     case 'l':
18472       return C_RegisterClass;
18473     case 'a':
18474     case 'b':
18475     case 'c':
18476     case 'd':
18477     case 'S':
18478     case 'D':
18479     case 'A':
18480       return C_Register;
18481     case 'I':
18482     case 'J':
18483     case 'K':
18484     case 'L':
18485     case 'M':
18486     case 'N':
18487     case 'G':
18488     case 'C':
18489     case 'e':
18490     case 'Z':
18491       return C_Other;
18492     default:
18493       break;
18494     }
18495   }
18496   return TargetLowering::getConstraintType(Constraint);
18497 }
18498
18499 /// Examine constraint type and operand type and determine a weight value.
18500 /// This object must already have been set up with the operand type
18501 /// and the current alternative constraint selected.
18502 TargetLowering::ConstraintWeight
18503   X86TargetLowering::getSingleConstraintMatchWeight(
18504     AsmOperandInfo &info, const char *constraint) const {
18505   ConstraintWeight weight = CW_Invalid;
18506   Value *CallOperandVal = info.CallOperandVal;
18507     // If we don't have a value, we can't do a match,
18508     // but allow it at the lowest weight.
18509   if (CallOperandVal == NULL)
18510     return CW_Default;
18511   Type *type = CallOperandVal->getType();
18512   // Look at the constraint type.
18513   switch (*constraint) {
18514   default:
18515     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18516   case 'R':
18517   case 'q':
18518   case 'Q':
18519   case 'a':
18520   case 'b':
18521   case 'c':
18522   case 'd':
18523   case 'S':
18524   case 'D':
18525   case 'A':
18526     if (CallOperandVal->getType()->isIntegerTy())
18527       weight = CW_SpecificReg;
18528     break;
18529   case 'f':
18530   case 't':
18531   case 'u':
18532     if (type->isFloatingPointTy())
18533       weight = CW_SpecificReg;
18534     break;
18535   case 'y':
18536     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18537       weight = CW_SpecificReg;
18538     break;
18539   case 'x':
18540   case 'Y':
18541     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18542         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18543       weight = CW_Register;
18544     break;
18545   case 'I':
18546     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18547       if (C->getZExtValue() <= 31)
18548         weight = CW_Constant;
18549     }
18550     break;
18551   case 'J':
18552     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18553       if (C->getZExtValue() <= 63)
18554         weight = CW_Constant;
18555     }
18556     break;
18557   case 'K':
18558     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18559       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18560         weight = CW_Constant;
18561     }
18562     break;
18563   case 'L':
18564     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18565       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18566         weight = CW_Constant;
18567     }
18568     break;
18569   case 'M':
18570     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18571       if (C->getZExtValue() <= 3)
18572         weight = CW_Constant;
18573     }
18574     break;
18575   case 'N':
18576     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18577       if (C->getZExtValue() <= 0xff)
18578         weight = CW_Constant;
18579     }
18580     break;
18581   case 'G':
18582   case 'C':
18583     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18584       weight = CW_Constant;
18585     }
18586     break;
18587   case 'e':
18588     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18589       if ((C->getSExtValue() >= -0x80000000LL) &&
18590           (C->getSExtValue() <= 0x7fffffffLL))
18591         weight = CW_Constant;
18592     }
18593     break;
18594   case 'Z':
18595     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18596       if (C->getZExtValue() <= 0xffffffff)
18597         weight = CW_Constant;
18598     }
18599     break;
18600   }
18601   return weight;
18602 }
18603
18604 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18605 /// with another that has more specific requirements based on the type of the
18606 /// corresponding operand.
18607 const char *X86TargetLowering::
18608 LowerXConstraint(EVT ConstraintVT) const {
18609   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18610   // 'f' like normal targets.
18611   if (ConstraintVT.isFloatingPoint()) {
18612     if (Subtarget->hasSSE2())
18613       return "Y";
18614     if (Subtarget->hasSSE1())
18615       return "x";
18616   }
18617
18618   return TargetLowering::LowerXConstraint(ConstraintVT);
18619 }
18620
18621 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18622 /// vector.  If it is invalid, don't add anything to Ops.
18623 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18624                                                      std::string &Constraint,
18625                                                      std::vector<SDValue>&Ops,
18626                                                      SelectionDAG &DAG) const {
18627   SDValue Result(0, 0);
18628
18629   // Only support length 1 constraints for now.
18630   if (Constraint.length() > 1) return;
18631
18632   char ConstraintLetter = Constraint[0];
18633   switch (ConstraintLetter) {
18634   default: break;
18635   case 'I':
18636     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18637       if (C->getZExtValue() <= 31) {
18638         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18639         break;
18640       }
18641     }
18642     return;
18643   case 'J':
18644     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18645       if (C->getZExtValue() <= 63) {
18646         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18647         break;
18648       }
18649     }
18650     return;
18651   case 'K':
18652     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18653       if (isInt<8>(C->getSExtValue())) {
18654         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18655         break;
18656       }
18657     }
18658     return;
18659   case 'N':
18660     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18661       if (C->getZExtValue() <= 255) {
18662         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18663         break;
18664       }
18665     }
18666     return;
18667   case 'e': {
18668     // 32-bit signed value
18669     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18670       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18671                                            C->getSExtValue())) {
18672         // Widen to 64 bits here to get it sign extended.
18673         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18674         break;
18675       }
18676     // FIXME gcc accepts some relocatable values here too, but only in certain
18677     // memory models; it's complicated.
18678     }
18679     return;
18680   }
18681   case 'Z': {
18682     // 32-bit unsigned value
18683     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18684       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18685                                            C->getZExtValue())) {
18686         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18687         break;
18688       }
18689     }
18690     // FIXME gcc accepts some relocatable values here too, but only in certain
18691     // memory models; it's complicated.
18692     return;
18693   }
18694   case 'i': {
18695     // Literal immediates are always ok.
18696     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18697       // Widen to 64 bits here to get it sign extended.
18698       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18699       break;
18700     }
18701
18702     // In any sort of PIC mode addresses need to be computed at runtime by
18703     // adding in a register or some sort of table lookup.  These can't
18704     // be used as immediates.
18705     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18706       return;
18707
18708     // If we are in non-pic codegen mode, we allow the address of a global (with
18709     // an optional displacement) to be used with 'i'.
18710     GlobalAddressSDNode *GA = 0;
18711     int64_t Offset = 0;
18712
18713     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18714     while (1) {
18715       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18716         Offset += GA->getOffset();
18717         break;
18718       } else if (Op.getOpcode() == ISD::ADD) {
18719         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18720           Offset += C->getZExtValue();
18721           Op = Op.getOperand(0);
18722           continue;
18723         }
18724       } else if (Op.getOpcode() == ISD::SUB) {
18725         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18726           Offset += -C->getZExtValue();
18727           Op = Op.getOperand(0);
18728           continue;
18729         }
18730       }
18731
18732       // Otherwise, this isn't something we can handle, reject it.
18733       return;
18734     }
18735
18736     const GlobalValue *GV = GA->getGlobal();
18737     // If we require an extra load to get this address, as in PIC mode, we
18738     // can't accept it.
18739     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18740                                                         getTargetMachine())))
18741       return;
18742
18743     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18744                                         GA->getValueType(0), Offset);
18745     break;
18746   }
18747   }
18748
18749   if (Result.getNode()) {
18750     Ops.push_back(Result);
18751     return;
18752   }
18753   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18754 }
18755
18756 std::pair<unsigned, const TargetRegisterClass*>
18757 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18758                                                 MVT VT) const {
18759   // First, see if this is a constraint that directly corresponds to an LLVM
18760   // register class.
18761   if (Constraint.size() == 1) {
18762     // GCC Constraint Letters
18763     switch (Constraint[0]) {
18764     default: break;
18765       // TODO: Slight differences here in allocation order and leaving
18766       // RIP in the class. Do they matter any more here than they do
18767       // in the normal allocation?
18768     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18769       if (Subtarget->is64Bit()) {
18770         if (VT == MVT::i32 || VT == MVT::f32)
18771           return std::make_pair(0U, &X86::GR32RegClass);
18772         if (VT == MVT::i16)
18773           return std::make_pair(0U, &X86::GR16RegClass);
18774         if (VT == MVT::i8 || VT == MVT::i1)
18775           return std::make_pair(0U, &X86::GR8RegClass);
18776         if (VT == MVT::i64 || VT == MVT::f64)
18777           return std::make_pair(0U, &X86::GR64RegClass);
18778         break;
18779       }
18780       // 32-bit fallthrough
18781     case 'Q':   // Q_REGS
18782       if (VT == MVT::i32 || VT == MVT::f32)
18783         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18784       if (VT == MVT::i16)
18785         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18786       if (VT == MVT::i8 || VT == MVT::i1)
18787         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18788       if (VT == MVT::i64)
18789         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18790       break;
18791     case 'r':   // GENERAL_REGS
18792     case 'l':   // INDEX_REGS
18793       if (VT == MVT::i8 || VT == MVT::i1)
18794         return std::make_pair(0U, &X86::GR8RegClass);
18795       if (VT == MVT::i16)
18796         return std::make_pair(0U, &X86::GR16RegClass);
18797       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18798         return std::make_pair(0U, &X86::GR32RegClass);
18799       return std::make_pair(0U, &X86::GR64RegClass);
18800     case 'R':   // LEGACY_REGS
18801       if (VT == MVT::i8 || VT == MVT::i1)
18802         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18803       if (VT == MVT::i16)
18804         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18805       if (VT == MVT::i32 || !Subtarget->is64Bit())
18806         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18807       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18808     case 'f':  // FP Stack registers.
18809       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18810       // value to the correct fpstack register class.
18811       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18812         return std::make_pair(0U, &X86::RFP32RegClass);
18813       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18814         return std::make_pair(0U, &X86::RFP64RegClass);
18815       return std::make_pair(0U, &X86::RFP80RegClass);
18816     case 'y':   // MMX_REGS if MMX allowed.
18817       if (!Subtarget->hasMMX()) break;
18818       return std::make_pair(0U, &X86::VR64RegClass);
18819     case 'Y':   // SSE_REGS if SSE2 allowed
18820       if (!Subtarget->hasSSE2()) break;
18821       // FALL THROUGH.
18822     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18823       if (!Subtarget->hasSSE1()) break;
18824
18825       switch (VT.SimpleTy) {
18826       default: break;
18827       // Scalar SSE types.
18828       case MVT::f32:
18829       case MVT::i32:
18830         return std::make_pair(0U, &X86::FR32RegClass);
18831       case MVT::f64:
18832       case MVT::i64:
18833         return std::make_pair(0U, &X86::FR64RegClass);
18834       // Vector types.
18835       case MVT::v16i8:
18836       case MVT::v8i16:
18837       case MVT::v4i32:
18838       case MVT::v2i64:
18839       case MVT::v4f32:
18840       case MVT::v2f64:
18841         return std::make_pair(0U, &X86::VR128RegClass);
18842       // AVX types.
18843       case MVT::v32i8:
18844       case MVT::v16i16:
18845       case MVT::v8i32:
18846       case MVT::v4i64:
18847       case MVT::v8f32:
18848       case MVT::v4f64:
18849         return std::make_pair(0U, &X86::VR256RegClass);
18850       case MVT::v8f64:
18851       case MVT::v16f32:
18852       case MVT::v16i32:
18853       case MVT::v8i64:
18854         return std::make_pair(0U, &X86::VR512RegClass);
18855       }
18856       break;
18857     }
18858   }
18859
18860   // Use the default implementation in TargetLowering to convert the register
18861   // constraint into a member of a register class.
18862   std::pair<unsigned, const TargetRegisterClass*> Res;
18863   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18864
18865   // Not found as a standard register?
18866   if (Res.second == 0) {
18867     // Map st(0) -> st(7) -> ST0
18868     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18869         tolower(Constraint[1]) == 's' &&
18870         tolower(Constraint[2]) == 't' &&
18871         Constraint[3] == '(' &&
18872         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18873         Constraint[5] == ')' &&
18874         Constraint[6] == '}') {
18875
18876       Res.first = X86::ST0+Constraint[4]-'0';
18877       Res.second = &X86::RFP80RegClass;
18878       return Res;
18879     }
18880
18881     // GCC allows "st(0)" to be called just plain "st".
18882     if (StringRef("{st}").equals_lower(Constraint)) {
18883       Res.first = X86::ST0;
18884       Res.second = &X86::RFP80RegClass;
18885       return Res;
18886     }
18887
18888     // flags -> EFLAGS
18889     if (StringRef("{flags}").equals_lower(Constraint)) {
18890       Res.first = X86::EFLAGS;
18891       Res.second = &X86::CCRRegClass;
18892       return Res;
18893     }
18894
18895     // 'A' means EAX + EDX.
18896     if (Constraint == "A") {
18897       Res.first = X86::EAX;
18898       Res.second = &X86::GR32_ADRegClass;
18899       return Res;
18900     }
18901     return Res;
18902   }
18903
18904   // Otherwise, check to see if this is a register class of the wrong value
18905   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18906   // turn into {ax},{dx}.
18907   if (Res.second->hasType(VT))
18908     return Res;   // Correct type already, nothing to do.
18909
18910   // All of the single-register GCC register classes map their values onto
18911   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18912   // really want an 8-bit or 32-bit register, map to the appropriate register
18913   // class and return the appropriate register.
18914   if (Res.second == &X86::GR16RegClass) {
18915     if (VT == MVT::i8 || VT == MVT::i1) {
18916       unsigned DestReg = 0;
18917       switch (Res.first) {
18918       default: break;
18919       case X86::AX: DestReg = X86::AL; break;
18920       case X86::DX: DestReg = X86::DL; break;
18921       case X86::CX: DestReg = X86::CL; break;
18922       case X86::BX: DestReg = X86::BL; break;
18923       }
18924       if (DestReg) {
18925         Res.first = DestReg;
18926         Res.second = &X86::GR8RegClass;
18927       }
18928     } else if (VT == MVT::i32 || VT == MVT::f32) {
18929       unsigned DestReg = 0;
18930       switch (Res.first) {
18931       default: break;
18932       case X86::AX: DestReg = X86::EAX; break;
18933       case X86::DX: DestReg = X86::EDX; break;
18934       case X86::CX: DestReg = X86::ECX; break;
18935       case X86::BX: DestReg = X86::EBX; break;
18936       case X86::SI: DestReg = X86::ESI; break;
18937       case X86::DI: DestReg = X86::EDI; break;
18938       case X86::BP: DestReg = X86::EBP; break;
18939       case X86::SP: DestReg = X86::ESP; break;
18940       }
18941       if (DestReg) {
18942         Res.first = DestReg;
18943         Res.second = &X86::GR32RegClass;
18944       }
18945     } else if (VT == MVT::i64 || VT == MVT::f64) {
18946       unsigned DestReg = 0;
18947       switch (Res.first) {
18948       default: break;
18949       case X86::AX: DestReg = X86::RAX; break;
18950       case X86::DX: DestReg = X86::RDX; break;
18951       case X86::CX: DestReg = X86::RCX; break;
18952       case X86::BX: DestReg = X86::RBX; break;
18953       case X86::SI: DestReg = X86::RSI; break;
18954       case X86::DI: DestReg = X86::RDI; break;
18955       case X86::BP: DestReg = X86::RBP; break;
18956       case X86::SP: DestReg = X86::RSP; break;
18957       }
18958       if (DestReg) {
18959         Res.first = DestReg;
18960         Res.second = &X86::GR64RegClass;
18961       }
18962     }
18963   } else if (Res.second == &X86::FR32RegClass ||
18964              Res.second == &X86::FR64RegClass ||
18965              Res.second == &X86::VR128RegClass ||
18966              Res.second == &X86::VR256RegClass ||
18967              Res.second == &X86::FR32XRegClass ||
18968              Res.second == &X86::FR64XRegClass ||
18969              Res.second == &X86::VR128XRegClass ||
18970              Res.second == &X86::VR256XRegClass ||
18971              Res.second == &X86::VR512RegClass) {
18972     // Handle references to XMM physical registers that got mapped into the
18973     // wrong class.  This can happen with constraints like {xmm0} where the
18974     // target independent register mapper will just pick the first match it can
18975     // find, ignoring the required type.
18976
18977     if (VT == MVT::f32 || VT == MVT::i32)
18978       Res.second = &X86::FR32RegClass;
18979     else if (VT == MVT::f64 || VT == MVT::i64)
18980       Res.second = &X86::FR64RegClass;
18981     else if (X86::VR128RegClass.hasType(VT))
18982       Res.second = &X86::VR128RegClass;
18983     else if (X86::VR256RegClass.hasType(VT))
18984       Res.second = &X86::VR256RegClass;
18985     else if (X86::VR512RegClass.hasType(VT))
18986       Res.second = &X86::VR512RegClass;
18987   }
18988
18989   return Res;
18990 }